Compare commits

..

5 Commits

Author SHA1 Message Date
TakahashiNguyen 6eb075c4b5 fix: add field role for user model (#32)
Release package / release (push) Successful in 13m22s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #32
2026-04-20 08:39:50 +00:00
gitea-actions 4ab284e966 chore: release [ci skip] 2026-04-20 07:58:34 +00:00
TakahashiNguyen b7bf0164e6 fix: better redis connection (#31)
Release package / release (push) Successful in 16m13s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #31
2026-04-20 07:42:22 +00:00
gitea-actions 715fbaf202 chore: release [ci skip] 2026-04-19 11:14:18 +00:00
TakahashiNguyen a5359db271 fix: add sms otp protocol (#30)
Release package / release (push) Successful in 13m39s
Co-authored-by: TakahashiNg <83152264+TakahashiNguyen@users.noreply.github.com>
Reviewed-on: #30
2026-04-19 11:00:45 +00:00
19 changed files with 66 additions and 241 deletions
-2
View File
@@ -5,7 +5,5 @@
"tabWidth": 2,
"trailingComma": "all",
"useTabs": true,
"xmlSortAttributesByKey": true,
"xmlQuoteAttributes": "double",
"plugins": ["prettier-plugin-java", "@prettier/plugin-xml"]
}
+14
View File
@@ -1,3 +1,17 @@
## [1.5.9](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.8...v1.5.9) (2026-04-20)
### Bug Fixes
* better redis connection ([#31](https://git.demonkernel.io.vn/FoodSurf/backend/issues/31)) ([b7bf016](https://git.demonkernel.io.vn/FoodSurf/backend/commit/b7bf0164e6a4a7f37324c4cdab5c8e6158e81615))
## [1.5.8](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.7...v1.5.8) (2026-04-19)
### Bug Fixes
* add sms otp protocol ([#30](https://git.demonkernel.io.vn/FoodSurf/backend/issues/30)) ([a5359db](https://git.demonkernel.io.vn/FoodSurf/backend/commit/a5359db271fc020dfc579fb62c2aa468852070a8))
## [1.5.7](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.5.6...v1.5.7) (2026-04-19)
+1 -6
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.7</version>
<version>1.5.9</version>
<relativePath>../pom.xml</relativePath>
</parent>
@@ -49,11 +49,6 @@
<artifactId>lib</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-h2</artifactId>
@@ -10,6 +10,10 @@ import java.util.UUID;
@Table(name = Role.Customer)
public class CustomerEntity extends UserModel {
public CustomerEntity() {
super(Role.Customer);
}
@Transactional
public void signup(String phone) {
this.signup(phone, phone, UUID.randomUUID().toString().substring(0, 32));
@@ -12,6 +12,10 @@ public class ManagerEntity extends UserModel {
public boolean isVerified;
public ManagerEntity() {
super(Role.Manager);
}
public void signup(
String name,
String phone,
@@ -23,6 +23,15 @@ public abstract class UserModel extends BaseEntity {
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public String hashedPassword;
@Transient
public String role;
protected UserModel(String role) {
this.role = role;
}
public UserModel() {}
@Transactional
public void signup(String name, String phone, String rawPassword) {
UserModel existedUser = UserModel.find("phone", phone).firstResult();
@@ -22,7 +22,10 @@ public class AccountService {
.entity("InvalidPhoneNumber")
.build();
otpService.generateAndSaveOtp(input.phone);
String otp = otpService.generateAndSaveOtp(input.phone);
// Ở đây bạn sẽ gọi Kafka để gửi SMS thực tế
System.out.println("OTP cho " + input.phone + " là: " + otp);
return Response.accepted().build();
}
@@ -1,11 +1,9 @@
package com.drinkool.services;
import com.drinkool.utils.SmsApi;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.redis.datasource.value.ValueCommands;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.io.IOException;
import java.util.Random;
@ApplicationScoped
@@ -13,29 +11,18 @@ public class OtpService {
private final ValueCommands<String, String> countCommands;
@Inject
SmsApi smsApi;
@Inject
public OtpService(RedisDataSource ds) {
this.countCommands = ds.value(String.class);
}
public void generateAndSaveOtp(String phone) {
public String generateAndSaveOtp(String phone) {
String otp = String.format("%06d", new Random().nextInt(1000000));
String key = "otp:" + phone;
countCommands.setex(key, 300, otp);
String smsStatus = null;
try {
smsStatus = smsApi.sendSMS(phone, "Mã OTP drinkool của bạn là " + otp);
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("SMS API response: " + smsStatus);
}
return otp;
}
public boolean verifyOtp(String phone, String inputOtp) {
@@ -1,113 +0,0 @@
package com.drinkool.utils;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.*;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@ApplicationScoped
public class SmsApi {
public static final String API_URL = "https://api.speedsms.vn/index.php";
protected String mAccessToken;
protected String mBrandName;
public SmsApi(
@ConfigProperty(name = "sms.api.token") String accessToken
// @ConfigProperty(name = "sms.api.brand") String brandName
) {
this.mAccessToken = accessToken;
this.mBrandName = "";
}
/**
* Get user information
* @param: none
* @return: json string
* */
public String getUserInfo() throws IOException {
URI uri = URI.create(API_URL + "/user/info");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("GET");
String userCredentials = mAccessToken + ":x";
String basicAuth =
"Basic " +
DatatypeConverter.printBase64Binary(userCredentials.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String inputLine = "";
StringBuffer buffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
buffer.append(inputLine);
}
in.close();
return buffer.toString();
}
/**
* Send SMS
* @param
* @return: json string
* */
public String sendSMS(String to, String content)
throws IOException {
String json =
"{\"to\": [\"" +
to +
"\"], \"content\": \"" +
EncodeNonAsciiCharacters(content) +
"\", \"type\":" +
4 +
", \"brandname\":\"" +
this.mBrandName +
"\"}";
URI uri = URI.create(API_URL + "/sms/send");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setRequestMethod("POST");
String userCredentials = mAccessToken + ":x";
String basicAuth =
"Basic " +
DatatypeConverter.printBase64Binary(userCredentials.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String inputLine = "";
StringBuffer buffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
buffer.append(inputLine);
}
in.close();
return buffer.toString();
}
private String EncodeNonAsciiCharacters(String value) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
int unit = (int) c;
if (unit > 127) {
String hex = String.format("%04x", (int) unit);
String encodedValue = "\\u" + hex;
sb.append(encodedValue);
} else {
sb.append(c);
}
}
return sb.toString();
}
}
@@ -27,7 +27,4 @@ quarkus.index-dependency.lib.artifact-id=lib
quarkus.native.container-build=true
quarkus.native.remote-container-build=true
quarkus.native.additional-build-args=--initialize-at-run-time=com.password4j.AlgorithmFinder,--future-defaults=all
quarkus.native.resources.includes=com/google/i18n/phonenumbers/data/**/*
# Sms API
sms.api.token=vc6kYQey8nFG7uRe7U4eYB3Iwq2JAiQa
quarkus.native.resources.includes=com/google/i18n/phonenumbers/data/**/*
@@ -12,7 +12,11 @@ import org.junit.jupiter.api.Test;
@Entity
@Table(name = "test_users")
class TestUserEntity extends UserModel {}
class TestUserEntity extends UserModel {
public TestUserEntity() {
super("TestRole");
}
}
@QuarkusTest
public class UserModelTest {
@@ -1,19 +1,16 @@
package com.drinkool.services;
import static io.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.drinkool.*;
import com.drinkool.dtos.*;
import com.drinkool.entities.CustomerEntity;
import com.drinkool.utils.SmsApi;
import io.quarkus.test.junit.*;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
import java.io.IOException;
import org.junit.jupiter.api.*;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
@QuarkusTest
public class CustomerServiceTest {
@@ -21,15 +18,6 @@ public class CustomerServiceTest {
@Inject
OtpService otpService;
SmsApi smsApiMock;
@BeforeEach
public void setup() {
SmsApi mock = mock(SmsApi.class);
QuarkusMock.installMockForType(mock, SmsApi.class);
this.smsApiMock = mock;
}
@Test
void testSignup() {
String phone = Utils.generateRandomPhone();
@@ -126,7 +114,7 @@ public class CustomerServiceTest {
}
@Test
public void testQuickLogin_Success() throws IOException {
public void testQuickLogin_Success() {
String phone = Utils.generateRandomPhone();
QuickSignup input = new QuickSignup();
@@ -141,18 +129,7 @@ public class CustomerServiceTest {
QuickLogin payload = new QuickLogin();
payload.phone = phone;
otpService.generateAndSaveOtp(phone);
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(
String.class
);
verify(smsApiMock).sendSMS(eq(phone), contentCaptor.capture());
// 4. Trích xuất mã OTP từ nội dung tin nhắn đã bắt được
// Giả sử tin nhắn có định dạng: "... là 123456"
String sentMessage = contentCaptor.getValue();
payload.otp = sentMessage.substring(sentMessage.length() - 6);
payload.otp = otpService.generateAndSaveOtp(phone);
given()
.contentType(ContentType.JSON)
@@ -1,17 +1,11 @@
package com.drinkool.services;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import com.drinkool.utils.SmsApi;
import io.quarkus.redis.datasource.RedisDataSource;
import io.quarkus.test.junit.*;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import java.io.IOException;
import java.util.Random;
import org.junit.jupiter.api.*;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
@QuarkusTest
public class OtpServiceTest {
@@ -19,53 +13,24 @@ public class OtpServiceTest {
@Inject
OtpService otpService;
@Inject
RedisDataSource redisDataSource;
SmsApi smsApiMock;
@BeforeEach
public void setup() {
SmsApi mock = mock(SmsApi.class);
QuarkusMock.installMockForType(mock, SmsApi.class);
this.smsApiMock = mock;
}
// 1. Test case: Tạo và lưu OTP thành công
@Test
public void testGenerateAndSaveOtp() {
String phone =
"+8477" + String.format("%07d", new Random().nextInt(10000000));
String redisKey = "otp:" + phone;
String otp = otpService.generateAndSaveOtp(phone);
otpService.generateAndSaveOtp(phone);
String otpFromRedis = redisDataSource.value(String.class).get(redisKey);
assertNotNull(otpFromRedis, "Mã OTP phải tồn tại trong Redis");
assertEquals(6, otpFromRedis.length(), "Mã OTP phải có 6 chữ số");
long ttl = redisDataSource.key().ttl(redisKey);
assertTrue(ttl > 0 && ttl <= 300, "TTL của OTP phải hợp lệ");
assertNotNull(otp, "OTP sinh ra không được null");
assertEquals(6, otp.length(), "OTP phải có độ dài đúng 6 ký tự");
assertTrue(otp.matches("\\d{6}"), "OTP chỉ được chứa các chữ số");
}
// 2. Test case: Xác thực OTP thành công
@Test
public void testVerifyOtpSuccess() throws IOException {
public void testVerifyOtpSuccess() {
String phone =
"+8477" + String.format("%07d", new Random().nextInt(10000000));
otpService.generateAndSaveOtp(phone);
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(
String.class
);
verify(smsApiMock).sendSMS(eq(phone), contentCaptor.capture());
// 4. Trích xuất mã OTP từ nội dung tin nhắn đã bắt được
// Giả sử tin nhắn có định dạng: "... là 123456"
String sentMessage = contentCaptor.getValue();
String generatedOtp = sentMessage.substring(sentMessage.length() - 6);
String generatedOtp = otpService.generateAndSaveOtp(phone);
// Xác thực với OTP vừa tạo ra
boolean verifyResult = otpService.verifyOtp(phone, generatedOtp);
@@ -103,21 +68,10 @@ public class OtpServiceTest {
// 5. Test case: Đảm bảo OTP chỉ được sử dụng 1 lần (đã bị xóa sau khi verify thành công bằng lệnh getdel)
@Test
public void testVerifyOtpConsumedAfterSuccess() throws IOException {
public void testVerifyOtpConsumedAfterSuccess() {
String phone =
"+8477" + String.format("%07d", new Random().nextInt(10000000));
otpService.generateAndSaveOtp(phone);
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(
String.class
);
verify(smsApiMock).sendSMS(eq(phone), contentCaptor.capture());
// 4. Trích xuất mã OTP từ nội dung tin nhắn đã bắt được
// Giả sử tin nhắn có định dạng: "... là 123456"
String sentMessage = contentCaptor.getValue();
String generatedOtp = sentMessage.substring(sentMessage.length() - 6);
String generatedOtp = otpService.generateAndSaveOtp(phone);
// Lần 1: Xác thực thành công
assertTrue(otpService.verifyOtp(phone, generatedOtp));
@@ -8,6 +8,3 @@ quarkus.http.host=0.0.0.0
## Orm
%test.quarkus.hibernate-orm.database.generation=drop-and-create
# Sms API
sms.api.token=your_sms_api_token_here
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.7</version>
<version>1.5.9</version>
<relativePath>../pom.xml</relativePath>
</parent>
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.7</version>
<version>1.5.9</version>
<relativePath>../pom.xml</relativePath>
</parent>
+3 -8
View File
@@ -15,7 +15,7 @@ spec:
spec:
containers:
- name: account-pod
image: git.demonkernel.io.vn/foodsurf/account-service:1.5.7
image: git.demonkernel.io.vn/foodsurf/account-service:1.5.9
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
@@ -37,11 +37,6 @@ spec:
secretKeyRef:
name: postgres-credentials
key: url
- name: SMS_API_TOKEN
valueFrom:
secretKeyRef:
name: sms-api-token
key: value
resources:
requests:
memory: "32Mi"
@@ -78,7 +73,7 @@ spec:
spec:
containers:
- name: eatery-pod
image: git.demonkernel.io.vn/foodsurf/eatery-service:1.5.7
image: git.demonkernel.io.vn/foodsurf/eatery-service:1.5.9
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
@@ -134,7 +129,7 @@ spec:
spec:
containers:
- name: gateway-pod
image: git.demonkernel.io.vn/foodsurf/gateway-service:1.5.7
image: git.demonkernel.io.vn/foodsurf/gateway-service:1.5.9
imagePullPolicy: IfNotPresent
ports:
- containerPort: 8080
+1 -1
View File
@@ -9,7 +9,7 @@
<parent>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.7</version>
<version>1.5.9</version>
<relativePath>../pom.xml</relativePath>
</parent>
+1 -1
View File
@@ -7,7 +7,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.drinkool</groupId>
<artifactId>drinkool</artifactId>
<version>1.5.7</version>
<version>1.5.9</version>
<packaging>pom</packaging>
<properties>
<maven.compiler.source>25</maven.compiler.source>