Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fdcecf8368 | |||
| 9bf7233436 | |||
| 00cc6a0f1f | |||
| c632504b4f |
@@ -16,6 +16,7 @@ RUN apt-get update --fix-missing && apt-get install --no-install-recommends --no
|
||||
docker-buildx \
|
||||
git \
|
||||
docker.io \
|
||||
nodejs \
|
||||
maven \
|
||||
libz-dev
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
"redhat.vscode-xml",
|
||||
"esbenp.prettier-vscode",
|
||||
"PeterSchmalfeldt.explorer-exclude",
|
||||
"redhat.java"
|
||||
"redhat.java",
|
||||
"ryanluker.vscode-coverage-gutters"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -38,8 +38,13 @@ jobs:
|
||||
./mvnw -B install \
|
||||
-Dquarkus.container-image.push=false \
|
||||
|
||||
- name: Publish Test Report
|
||||
uses: scacap/action-surefire-report@v1
|
||||
if: failure()
|
||||
- name: Jacoco Report to PR
|
||||
uses: madrapps/jacoco-report@v1.7.2
|
||||
if: always()
|
||||
with:
|
||||
github_token: ${{ secrets.ACCESS_TOKEN }}
|
||||
paths: |
|
||||
./**/jacoco.xml,
|
||||
token: ${{ secrets.ACCESS_TOKEN }}
|
||||
min-coverage-overall: 40
|
||||
min-coverage-changed-files: 60
|
||||
title: "📊 Báo cáo Độ bao phủ Kiểm thử (Test Coverage)"
|
||||
|
||||
@@ -1,3 +1,15 @@
|
||||
# [1.4.0](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.3.0...v1.4.0) (2026-04-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* update ci script ([#18](https://git.demonkernel.io.vn/FoodSurf/backend/issues/18)) ([e77edb0](https://git.demonkernel.io.vn/FoodSurf/backend/commit/e77edb0e7402afaca494221270d2e289dac3448b))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* init k8s and customer service ([#15](https://git.demonkernel.io.vn/FoodSurf/backend/issues/15)) ([837f5f5](https://git.demonkernel.io.vn/FoodSurf/backend/commit/837f5f595a3b1c5ea5e261f60f265834081071ea))
|
||||
|
||||
# [1.1.0-dev.1](https://git.demonkernel.io.vn/FoodSurf/backend/compare/v1.0.0...v1.1.0-dev.1) (2026-03-24)
|
||||
|
||||
|
||||
|
||||
+9
-17
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>drinkool</artifactId>
|
||||
<version>1.1.0-dev.1</version>
|
||||
<version>1.4.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
<packaging>quarkus</packaging>
|
||||
|
||||
<properties>
|
||||
<quarkus.package.jar.enabled>false</quarkus.package.jar.enabled>
|
||||
<skipITs>false</skipITs>
|
||||
<quarkus.native.enabled>true</quarkus.native.enabled>
|
||||
<compiler-plugin.version>3.15.0</compiler-plugin.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@@ -43,6 +46,11 @@
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jacoco</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
@@ -158,20 +166,4 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>native</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>native</name>
|
||||
</property>
|
||||
</activation>
|
||||
<properties>
|
||||
<quarkus.package.jar.enabled>false</quarkus.package.jar.enabled>
|
||||
<skipITs>false</skipITs>
|
||||
<quarkus.native.enabled>true</quarkus.native.enabled>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
package com.drinkool.entities;
|
||||
|
||||
import com.drinkool.Role;
|
||||
import com.drinkool.models.UserModel;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.transaction.Transactional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "customer")
|
||||
public class CustomerEntity extends UserModel {}
|
||||
@Table(name = Role.Customer)
|
||||
public class CustomerEntity extends UserModel {
|
||||
|
||||
@Transactional
|
||||
public void signup(String phone) {
|
||||
this.signup(phone, phone, UUID.randomUUID().toString().substring(0, 32));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.drinkool.entities;
|
||||
|
||||
import com.drinkool.Role;
|
||||
import com.drinkool.models.UserModel;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = Role.Manager)
|
||||
public class ManagerEntity extends UserModel {
|
||||
|
||||
public String eateryName;
|
||||
|
||||
public boolean isVerified;
|
||||
|
||||
public void signup(
|
||||
String name,
|
||||
String phone,
|
||||
String rawPassword,
|
||||
String eateryName
|
||||
) {
|
||||
this.eateryName = eateryName;
|
||||
|
||||
this.isVerified = false;
|
||||
|
||||
this.signup(name, phone, rawPassword);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import com.password4j.Password;
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.transaction.*;
|
||||
import jakarta.ws.rs.BadRequestException;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Inheritance(strategy = InheritanceType.JOINED)
|
||||
@@ -24,19 +23,12 @@ public abstract class UserModel extends BaseEntity {
|
||||
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
|
||||
public String hashedPassword;
|
||||
|
||||
@Transactional
|
||||
public void signup(String phone) {
|
||||
this.signup(phone, phone, UUID.randomUUID().toString().substring(0, 32));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void signup(String name, String phone, String rawPassword) {
|
||||
// Check existed user
|
||||
UserModel existedUser = find("phone", phone).firstResult();
|
||||
UserModel existedUser = UserModel.find("phone", phone).firstResult();
|
||||
|
||||
if (existedUser != null) throw new BadRequestException("ExistedUser");
|
||||
|
||||
// Set user
|
||||
this.name = name;
|
||||
|
||||
if (!PhoneValidator.isValidInternationalPhone(phone)) {
|
||||
@@ -47,7 +39,6 @@ public abstract class UserModel extends BaseEntity {
|
||||
|
||||
this.hashedPassword = Password.hash(rawPassword).withArgon2().getResult();
|
||||
|
||||
// Save user
|
||||
this.persist();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.dtos.SmsOtp;
|
||||
import com.drinkool.models.UserModel;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
@Path("")
|
||||
public class AccountService {
|
||||
|
||||
@Inject
|
||||
OtpService otpService;
|
||||
|
||||
@POST
|
||||
@Path(Url.SmsOtp)
|
||||
public Response smsOtp(SmsOtp input) {
|
||||
UserModel customer = UserModel.find("phone", input.phone).firstResult();
|
||||
|
||||
if (customer == null) return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity("InvalidPhoneNumber")
|
||||
.build();
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
+11
-5
@@ -1,6 +1,6 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import com.drinkool.Jwt;
|
||||
import com.drinkool.InternalValue;
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.models.UserModel;
|
||||
import jakarta.transaction.Transactional;
|
||||
@@ -8,17 +8,23 @@ import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.UUID;
|
||||
|
||||
@Path("")
|
||||
public class UserService {
|
||||
public abstract class BaseService {
|
||||
|
||||
private UserModel model;
|
||||
|
||||
public BaseService(UserModel model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
@SuppressWarnings("static-access")
|
||||
@POST
|
||||
@Path(Url.Me)
|
||||
@Transactional
|
||||
public Response me(@HeaderParam(Jwt.userId) UUID id) {
|
||||
public Response me(@HeaderParam(InternalValue.userId) UUID id) {
|
||||
if (id == null) return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity("InvalidUserId")
|
||||
.build();
|
||||
|
||||
return Response.ok(UserModel.find("id", id).firstResult()).build();
|
||||
return Response.ok(model.find("id", id).firstResult()).build();
|
||||
}
|
||||
}
|
||||
+15
-33
@@ -1,8 +1,6 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import com.drinkool.Jwt;
|
||||
import com.drinkool.Role;
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.*;
|
||||
import com.drinkool.dtos.*;
|
||||
import com.drinkool.entities.CustomerEntity;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -10,12 +8,16 @@ import jakarta.transaction.Transactional;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
|
||||
@Path("")
|
||||
public class AuthenticationService {
|
||||
@Path(Role.Customer)
|
||||
public class CustomerService extends BaseService {
|
||||
|
||||
@Inject
|
||||
OtpService otpService;
|
||||
|
||||
public CustomerService() {
|
||||
super(new CustomerEntity());
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path(Url.Signup)
|
||||
@Transactional
|
||||
@@ -25,8 +27,8 @@ public class AuthenticationService {
|
||||
newCustomer.signup(input.name, input.phone, input.password);
|
||||
|
||||
return Response.status(Response.Status.CREATED)
|
||||
.header(Jwt.userId, newCustomer.id.toString())
|
||||
.header(Jwt.role, Role.Customer)
|
||||
.header(InternalValue.userId, newCustomer.id.toString())
|
||||
.header(InternalValue.role, Role.Customer)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -39,8 +41,8 @@ public class AuthenticationService {
|
||||
newCustomer.signup(input.phone);
|
||||
|
||||
return Response.status(Response.Status.CREATED)
|
||||
.header(Jwt.userId, newCustomer.id.toString())
|
||||
.header(Jwt.role, Role.Customer)
|
||||
.header(InternalValue.userId, newCustomer.id.toString())
|
||||
.header(InternalValue.role, Role.Customer)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -63,8 +65,8 @@ public class AuthenticationService {
|
||||
.build();
|
||||
|
||||
return Response.accepted()
|
||||
.header(Jwt.userId, customer.id.toString())
|
||||
.header(Jwt.role, Role.Customer)
|
||||
.header(InternalValue.userId, customer.id.toString())
|
||||
.header(InternalValue.role, Role.Customer)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -83,28 +85,8 @@ public class AuthenticationService {
|
||||
).firstResult();
|
||||
|
||||
return Response.accepted()
|
||||
.header(Jwt.userId, customer.id.toString())
|
||||
.header(Jwt.role, Role.Customer)
|
||||
.header(InternalValue.userId, customer.id.toString())
|
||||
.header(InternalValue.role, Role.Customer)
|
||||
.build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path(Url.SmsOtp)
|
||||
public Response smsOtp(SmsOtp input) {
|
||||
CustomerEntity customer = CustomerEntity.find(
|
||||
"phone",
|
||||
input.phone
|
||||
).firstResult();
|
||||
|
||||
if (customer == null) return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity("InvalidPhoneNumber")
|
||||
.build();
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import com.drinkool.*;
|
||||
import com.drinkool.dtos.*;
|
||||
import com.drinkool.entities.ManagerEntity;
|
||||
import jakarta.transaction.Transactional;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
|
||||
@Path(Role.Manager)
|
||||
public class ManagerService {
|
||||
|
||||
@POST
|
||||
@Path(Url.Signup)
|
||||
@Transactional
|
||||
public Response signup(ManagerSignup input) {
|
||||
ManagerEntity newManager = new ManagerEntity();
|
||||
|
||||
newManager.signup(
|
||||
input.name,
|
||||
input.phone,
|
||||
input.password,
|
||||
input.eateryName
|
||||
);
|
||||
|
||||
return Response.status(Response.Status.CREATED)
|
||||
.header(InternalValue.userId, newManager.id.toString())
|
||||
.header(InternalValue.role, Role.Manager)
|
||||
.build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path(Url.Login)
|
||||
public Response login(Login input) {
|
||||
ManagerEntity customer = ManagerEntity.find(
|
||||
"phone",
|
||||
input.phone
|
||||
).firstResult();
|
||||
|
||||
if (customer == null) return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity("InvalidPhoneNumber")
|
||||
.build();
|
||||
|
||||
if (!customer.login(input.password)) return Response.status(
|
||||
Response.Status.BAD_REQUEST
|
||||
)
|
||||
.entity("InvalidPassword")
|
||||
.build();
|
||||
|
||||
return Response.accepted()
|
||||
.header(InternalValue.userId, customer.id.toString())
|
||||
.header(InternalValue.role, Role.Manager)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -21,4 +21,8 @@ quarkus.redis.hosts=redis://localhost:6379
|
||||
|
||||
# Dependency
|
||||
quarkus.index-dependency.lib.group-id=com.drinkool
|
||||
quarkus.index-dependency.lib.artifact-id=lib
|
||||
quarkus.index-dependency.lib.artifact-id=lib
|
||||
|
||||
# Build
|
||||
quarkus.native.container-build=false
|
||||
quarkus.native.additional-build-args=--initialize-at-run-time=com.password4j.AlgorithmFinder,--future-defaults=all
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.drinkool;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class Utils {
|
||||
|
||||
public static Random random = new Random();
|
||||
|
||||
public static String generateRandomPhone() {
|
||||
return "+8477" + String.format("%07d", random.nextInt(10000000));
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,29 @@
|
||||
package com.drinkool.entities;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.drinkool.*;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
@QuarkusTest
|
||||
public class CustomerEntityTest {
|
||||
|
||||
@Inject
|
||||
EntityManager entityManager;
|
||||
|
||||
@Test
|
||||
@Transactional
|
||||
public void testCustomerPersistence() {
|
||||
// 1. Khởi tạo đúng Entity (CustomerEntity chứ không phải CustomerEntityTest)
|
||||
CustomerEntity customer = new CustomerEntity();
|
||||
public void testSignupOneParamSuccess() {
|
||||
CustomerEntity user = new CustomerEntity();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
|
||||
// Gán đúng biến name, phone và hashedPassword (các trường kế thừa từ UserModel)
|
||||
customer.name = "Nguyen Van A";
|
||||
customer.phone = "+84987654321";
|
||||
customer.hashedPassword = "dummy_hashed_password";
|
||||
user.signup(phone);
|
||||
|
||||
// 2. Lưu vào DB
|
||||
entityManager.persist(customer);
|
||||
entityManager.flush();
|
||||
entityManager.clear();
|
||||
|
||||
// 3. Truy vấn lại để kiểm tra (Sửa lại class map của query thành CustomerEntity)
|
||||
var query = entityManager.createQuery(
|
||||
"SELECT c FROM CustomerEntity c WHERE c.phone = :phone",
|
||||
CustomerEntity.class
|
||||
assertNotNull(user.id, "ID not null after persist");
|
||||
assertEquals(phone, user.name, "Tên mặc định phải là số điện thoại");
|
||||
assertEquals(phone, user.phone);
|
||||
assertNotNull(
|
||||
user.hashedPassword,
|
||||
"Password tự động phải được tạo và hash"
|
||||
);
|
||||
query.setParameter("phone", "+84987654321");
|
||||
|
||||
// Nhận kết quả về đúng kiểu CustomerEntity
|
||||
CustomerEntity savedCustomer = query.getSingleResult();
|
||||
|
||||
// 4. Assert (Kiểm chứng)
|
||||
Assertions.assertNotNull(savedCustomer, "Customer không được null");
|
||||
Assertions.assertEquals(
|
||||
"Nguyen Van A",
|
||||
savedCustomer.name,
|
||||
"Tên không khớp"
|
||||
);
|
||||
Assertions.assertEquals(
|
||||
"+84987654321",
|
||||
savedCustomer.phone,
|
||||
"Số điện thoại không khớp"
|
||||
);
|
||||
Assertions.assertNotNull(savedCustomer.id, "ID chưa được sinh ra");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,24 +44,6 @@ public class UserModelTest {
|
||||
assertNotNull(savedUser, "Phải tìm thấy user trong database");
|
||||
}
|
||||
|
||||
// 2. Test case: Đăng ký thành công (chỉ dùng số điện thoại)
|
||||
@Test
|
||||
@Transactional
|
||||
public void testSignupOneParamSuccess() {
|
||||
TestUserEntity user = new TestUserEntity();
|
||||
String phone = generateValidPhone();
|
||||
|
||||
user.signup(phone);
|
||||
|
||||
assertNotNull(user.id, "ID not null after persist");
|
||||
assertEquals(phone, user.name, "Tên mặc định phải là số điện thoại");
|
||||
assertEquals(phone, user.phone);
|
||||
assertNotNull(
|
||||
user.hashedPassword,
|
||||
"Password tự động phải được tạo và hash"
|
||||
);
|
||||
}
|
||||
|
||||
// 3. Test case: Đăng ký thất bại do số điện thoại đã tồn tại
|
||||
@Test
|
||||
@Transactional
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import static io.restassured.RestAssured.*;
|
||||
|
||||
import com.drinkool.*;
|
||||
import com.drinkool.dtos.*;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@QuarkusTest
|
||||
public class AccountServiceTest {
|
||||
|
||||
@Test
|
||||
void testSmsOtp() {
|
||||
String phone = Utils.generateRandomPhone();
|
||||
SmsOtp input = new SmsOtp();
|
||||
input.phone = phone;
|
||||
|
||||
Signup signup = new Signup();
|
||||
signup.phone = phone;
|
||||
signup.name = "sms user";
|
||||
signup.password = "password123";
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(signup)
|
||||
.when()
|
||||
.post(Role.Customer + Url.Signup)
|
||||
.then();
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.SmsOtp)
|
||||
.then()
|
||||
.statusCode(202);
|
||||
}
|
||||
}
|
||||
+9
-15
@@ -3,20 +3,18 @@ package com.drinkool.services;
|
||||
import static io.restassured.RestAssured.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
|
||||
import com.drinkool.Jwt;
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.dtos.QuickSignup;
|
||||
|
||||
import com.drinkool.*;
|
||||
import com.drinkool.dtos.*;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@QuarkusTest
|
||||
public class UserServiceTest {
|
||||
public class BaseServiceTest {
|
||||
|
||||
@Test
|
||||
public void testMeEndpointWithHeader() {
|
||||
String phone = AuthenticationServiceTest.generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
QuickSignup input = new QuickSignup();
|
||||
input.phone = phone;
|
||||
|
||||
@@ -24,16 +22,16 @@ public class UserServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.QuickSignup)
|
||||
.post(Role.Customer + Url.QuickSignup)
|
||||
.then()
|
||||
.extract()
|
||||
.header(Jwt.userId);
|
||||
.header(InternalValue.userId);
|
||||
|
||||
given()
|
||||
.header(Jwt.userId, testUserId)
|
||||
.header(InternalValue.userId, testUserId)
|
||||
.contentType(ContentType.JSON)
|
||||
.when()
|
||||
.post(Url.Me)
|
||||
.post(Role.Customer + Url.Me)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("id", is(testUserId));
|
||||
@@ -41,10 +39,6 @@ public class UserServiceTest {
|
||||
|
||||
@Test
|
||||
public void testMeEndpointWithoutHeader() {
|
||||
given()
|
||||
.when()
|
||||
.post(Url.Me)
|
||||
.then()
|
||||
.statusCode(400);
|
||||
given().when().post(Role.Customer + Url.Me).then().statusCode(400);
|
||||
}
|
||||
}
|
||||
+35
-40
@@ -4,28 +4,23 @@ import static io.restassured.RestAssured.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.drinkool.Jwt;
|
||||
import com.drinkool.Role;
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.*;
|
||||
import com.drinkool.dtos.*;
|
||||
import com.drinkool.entities.CustomerEntity;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import java.util.Random;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@QuarkusTest
|
||||
public class AuthenticationServiceTest {
|
||||
public class CustomerServiceTest {
|
||||
|
||||
public static Random random = new Random();
|
||||
|
||||
public static String generateRandomPhone() {
|
||||
return "+8477" + String.format("%07d", random.nextInt(10000000));
|
||||
}
|
||||
@Inject
|
||||
OtpService otpService;
|
||||
|
||||
@Test
|
||||
void testSignup() {
|
||||
String phone = generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
Signup input = new Signup();
|
||||
input.name = "Test User";
|
||||
input.phone = phone;
|
||||
@@ -35,7 +30,7 @@ public class AuthenticationServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.Signup)
|
||||
.post(Role.Customer + Url.Signup)
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
@@ -45,7 +40,7 @@ public class AuthenticationServiceTest {
|
||||
|
||||
@Test
|
||||
void testQuickSignup() {
|
||||
String phone = generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
QuickSignup input = new QuickSignup();
|
||||
input.phone = phone;
|
||||
|
||||
@@ -53,10 +48,10 @@ public class AuthenticationServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.QuickSignup)
|
||||
.post(Role.Customer + Url.QuickSignup)
|
||||
.then()
|
||||
.header(Jwt.userId, notNullValue())
|
||||
.header(Jwt.role, is(Role.Customer))
|
||||
.header(InternalValue.userId, notNullValue())
|
||||
.header(InternalValue.role, is(Role.Customer))
|
||||
.statusCode(201);
|
||||
|
||||
assertEquals(1, CustomerEntity.find("phone", phone).count());
|
||||
@@ -65,7 +60,7 @@ public class AuthenticationServiceTest {
|
||||
@Test
|
||||
void testLoginSuccess() {
|
||||
// BƯỚC 1: Tạo user trước bằng signup
|
||||
String phone = generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
Signup signupData = new Signup();
|
||||
signupData.name = "Login User";
|
||||
signupData.phone = phone;
|
||||
@@ -74,7 +69,7 @@ public class AuthenticationServiceTest {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(signupData)
|
||||
.post(Url.Signup)
|
||||
.post(Role.Customer + Url.Signup)
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
@@ -87,14 +82,14 @@ public class AuthenticationServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(loginInput)
|
||||
.when()
|
||||
.post(Url.Login)
|
||||
.post(Role.Customer + Url.Login)
|
||||
.then()
|
||||
.statusCode(202);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoginFailWrongPassword() {
|
||||
String phone = generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
Signup signupData = new Signup();
|
||||
signupData.name = "Wrong Pass User";
|
||||
signupData.phone = phone;
|
||||
@@ -103,7 +98,7 @@ public class AuthenticationServiceTest {
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(signupData)
|
||||
.post(Url.Signup)
|
||||
.post(Role.Customer + Url.Signup)
|
||||
.then()
|
||||
.statusCode(201);
|
||||
|
||||
@@ -115,41 +110,41 @@ public class AuthenticationServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(loginInput)
|
||||
.when()
|
||||
.post(Url.Login)
|
||||
.post(Role.Customer + Url.Login)
|
||||
.then()
|
||||
.statusCode(400); // BadRequestException
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSmsOtp() {
|
||||
String phone = generateRandomPhone();
|
||||
SmsOtp input = new SmsOtp();
|
||||
public void testQuickLogin_Success() {
|
||||
String phone = Utils.generateRandomPhone();
|
||||
|
||||
QuickSignup input = new QuickSignup();
|
||||
input.phone = phone;
|
||||
|
||||
Signup signup = new Signup();
|
||||
signup.phone = phone;
|
||||
signup.name = "sms user";
|
||||
signup.password = "password123";
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(signup)
|
||||
.when()
|
||||
.post(Url.Signup)
|
||||
.then();
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.SmsOtp)
|
||||
.post(Role.Customer + Url.QuickSignup)
|
||||
.then();
|
||||
|
||||
QuickLogin payload = new QuickLogin();
|
||||
payload.phone = phone;
|
||||
payload.otp = otpService.generateAndSaveOtp(phone);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body(payload)
|
||||
.when()
|
||||
.post(Role.Customer + Url.QuickLogin)
|
||||
.then()
|
||||
.statusCode(202);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testQuickLoginFailInvalidOtp() {
|
||||
String phone = generateRandomPhone();
|
||||
String phone = Utils.generateRandomPhone();
|
||||
QuickLogin input = new QuickLogin();
|
||||
input.phone = phone;
|
||||
input.otp = "000000"; // Giả sử mã này luôn sai vì chưa được tạo
|
||||
@@ -158,7 +153,7 @@ public class AuthenticationServiceTest {
|
||||
.contentType(ContentType.JSON)
|
||||
.body(input)
|
||||
.when()
|
||||
.post(Url.QuickLogin)
|
||||
.post(Role.Customer + Url.QuickLogin)
|
||||
.then()
|
||||
.statusCode(401);
|
||||
}
|
||||
+13
-21
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>drinkool</artifactId>
|
||||
<version>1.1.0-dev.1</version>
|
||||
<version>1.4.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
<packaging>quarkus</packaging>
|
||||
|
||||
<properties>
|
||||
<quarkus.package.jar.enabled>false</quarkus.package.jar.enabled>
|
||||
<skipITs>false</skipITs>
|
||||
<quarkus.native.enabled>true</quarkus.native.enabled>
|
||||
<compiler-plugin.version>3.15.0</compiler-plugin.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
@@ -43,6 +46,11 @@
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jacoco</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
@@ -66,10 +74,6 @@
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-messaging-kafka</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jdbc-postgresql</artifactId>
|
||||
@@ -86,6 +90,10 @@
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-rest-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-container-image-docker</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-junit</artifactId>
|
||||
@@ -144,20 +152,4 @@
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>native</id>
|
||||
<activation>
|
||||
<property>
|
||||
<name>native</name>
|
||||
</property>
|
||||
</activation>
|
||||
<properties>
|
||||
<quarkus.package.jar.enabled>false</quarkus.package.jar.enabled>
|
||||
<skipITs>false</skipITs>
|
||||
<quarkus.native.enabled>true</quarkus.native.enabled>
|
||||
</properties>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
# Kafka
|
||||
kafka.bootstrap.servers=localhost:9092
|
||||
|
||||
# Postgress
|
||||
## Cấu hình Database
|
||||
quarkus.datasource.db-kind=postgresql
|
||||
@@ -11,6 +8,19 @@ quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/eatery
|
||||
## Tự động tạo bảng từ Entity (chỉ dùng cho môi trường dev)
|
||||
quarkus.hibernate-orm.database.generation=update
|
||||
|
||||
# Docker
|
||||
quarkus.container-image.registry=git.demonkernel.io.vn
|
||||
quarkus.container-image.group=foodsurf
|
||||
quarkus.container-image.name=eatery-service
|
||||
quarkus.container-image.push=true
|
||||
quarkus.container-image.build=true
|
||||
quarkus.container-image.builder=docker
|
||||
quarkus.container-image.additional-tags=latest
|
||||
|
||||
# Dependency
|
||||
quarkus.index-dependency.lib.group-id=com.drinkool
|
||||
quarkus.index-dependency.lib.artifact-id=lib
|
||||
quarkus.index-dependency.lib.artifact-id=lib
|
||||
|
||||
# Build
|
||||
quarkus.native.container-build=false
|
||||
quarkus.native.additional-build-args=--future-defaults=all
|
||||
+24
-10
@@ -1,15 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>drinkool</artifactId>
|
||||
<version>1.1.0-dev.1</version>
|
||||
<version>1.4.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@@ -23,9 +23,11 @@
|
||||
<compiler-plugin.version>3.15.0</compiler-plugin.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<project.reporting.outputEncoding
|
||||
>UTF-8</project.reporting.outputEncoding>
|
||||
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
|
||||
<quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id>
|
||||
<quarkus.platform.group-id
|
||||
>io.quarkus.platform</quarkus.platform.group-id>
|
||||
<quarkus.platform.version>3.32.4</quarkus.platform.version>
|
||||
<skipITs>true</skipITs>
|
||||
<surefire-plugin.version>3.5.4</surefire-plugin.version>
|
||||
@@ -44,6 +46,16 @@
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jacoco</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bitbucket.b_c</groupId>
|
||||
<artifactId>jose4j</artifactId>
|
||||
<version>0.9.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
@@ -102,7 +114,8 @@
|
||||
<configuration>
|
||||
<argLine>@{argLine}</argLine>
|
||||
<systemPropertyVariables>
|
||||
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||
<java.util.logging.manager
|
||||
>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||
<maven.home>${maven.home}</maven.home>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
@@ -123,11 +136,12 @@
|
||||
<systemPropertyVariables>
|
||||
<native.image.path>
|
||||
${project.build.directory}/${project.build.finalName}-runner</native.image.path>
|
||||
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||
<java.util.logging.manager
|
||||
>org.jboss.logmanager.LogManager</java.util.logging.manager>
|
||||
<maven.home>${maven.home}</maven.home>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
</project>
|
||||
|
||||
+7
-2
@@ -8,8 +8,8 @@ import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.eclipse.microprofile.rest.client.inject.RestClient;
|
||||
|
||||
@Path("/api/v1/customers")
|
||||
public class CustomerGatewayResource {
|
||||
@Path("/api/" + Role.Customer)
|
||||
class CustomerGatewayResource {
|
||||
|
||||
@Inject
|
||||
@RestClient
|
||||
@@ -26,4 +26,9 @@ public class CustomerGatewayResource {
|
||||
public Uni<Response> proxyLogin(Login input) {
|
||||
return accountService.login(input);
|
||||
}
|
||||
|
||||
@GET
|
||||
public Uni<Response> me() {
|
||||
return accountService.me();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.drinkool.filters;
|
||||
|
||||
import com.drinkool.InternalValue;
|
||||
import io.smallrye.mutiny.Uni;
|
||||
import jakarta.ws.rs.Priorities;
|
||||
import jakarta.ws.rs.container.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
import java.util.*;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.jboss.resteasy.reactive.server.ServerRequestFilter;
|
||||
import org.jboss.resteasy.reactive.server.ServerResponseFilter;
|
||||
import org.jose4j.jws.AlgorithmIdentifiers;
|
||||
import org.jose4j.jws.JsonWebSignature;
|
||||
import org.jose4j.jwt.JwtClaims;
|
||||
import org.jose4j.jwt.consumer.JwtConsumer;
|
||||
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
|
||||
import org.jose4j.keys.HmacKey;
|
||||
|
||||
public class InternalHeaderGatewayFilter {
|
||||
|
||||
@ConfigProperty(name = "gateway.jwt.secret")
|
||||
String SECRET_KEY;
|
||||
|
||||
private boolean isSystemClaim(String key) {
|
||||
return List.of("iss", "sub", "aud", "exp", "nbf", "iat", "jti").contains(
|
||||
key
|
||||
);
|
||||
}
|
||||
|
||||
@ServerRequestFilter(preMatching = true)
|
||||
public Uni<Response> handleRequestHeaders(
|
||||
ContainerRequestContext requestContext
|
||||
) {
|
||||
requestContext
|
||||
.getHeaders()
|
||||
.keySet()
|
||||
.removeIf(
|
||||
key ->
|
||||
key.equalsIgnoreCase(InternalValue.headerId) ||
|
||||
key.toLowerCase().startsWith(InternalValue.headerId.toLowerCase())
|
||||
);
|
||||
|
||||
Map<String, Cookie> cookies = requestContext.getCookies();
|
||||
Cookie authCookie = cookies.get(InternalValue.cookieName);
|
||||
|
||||
if (authCookie == null) return Uni.createFrom().nullItem();
|
||||
|
||||
return Uni.createFrom().item(() -> {
|
||||
try {
|
||||
String token = authCookie.getValue();
|
||||
|
||||
JwtConsumer jwtConsumer = new JwtConsumerBuilder()
|
||||
.setRequireExpirationTime()
|
||||
.setVerificationKey(new HmacKey(SECRET_KEY.getBytes()))
|
||||
.build();
|
||||
|
||||
JwtClaims claims = jwtConsumer.processToClaims(token);
|
||||
|
||||
Map<String, Object> allClaims = claims.getClaimsMap();
|
||||
|
||||
allClaims.forEach((key, value) -> {
|
||||
if (!isSystemClaim(key) && value != null) {
|
||||
String headerName = InternalValue.headerId + (key);
|
||||
|
||||
requestContext.getHeaders().add(headerName, value.toString());
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED)
|
||||
.entity("InvalidToken")
|
||||
.build();
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@ServerResponseFilter(priority = Priorities.USER + 100)
|
||||
public void handleResponseHeaders(ContainerResponseContext responseContext) {
|
||||
JwtClaims claims = new JwtClaims();
|
||||
boolean hasInternalData = false;
|
||||
|
||||
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
|
||||
|
||||
List<String> keysToRemove = new ArrayList<>();
|
||||
|
||||
for (String key : headers.keySet()) {
|
||||
if (key.toLowerCase().startsWith(InternalValue.headerId.toLowerCase())) {
|
||||
Object value = headers.getFirst(key);
|
||||
if (value != null) {
|
||||
String claimKey = key.substring(InternalValue.headerId.length());
|
||||
claims.setClaim(claimKey, value.toString());
|
||||
hasInternalData = true;
|
||||
}
|
||||
keysToRemove.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
for (String key : keysToRemove) {
|
||||
headers.remove(key);
|
||||
}
|
||||
|
||||
if (hasInternalData) {
|
||||
try {
|
||||
claims.setExpirationTimeMinutesInTheFuture(60);
|
||||
claims.setGeneratedJwtId();
|
||||
claims.setIssuedAtToNow();
|
||||
|
||||
JsonWebSignature jws = new JsonWebSignature();
|
||||
jws.setPayload(claims.toJson());
|
||||
jws.setKey(new HmacKey(SECRET_KEY.getBytes()));
|
||||
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
|
||||
|
||||
String jwt = jws.getCompactSerialization();
|
||||
|
||||
NewCookie jwtCookie = new NewCookie.Builder(InternalValue.cookieName)
|
||||
.value(jwt)
|
||||
.path("/")
|
||||
.httpOnly(true)
|
||||
.secure(true)
|
||||
.sameSite(NewCookie.SameSite.STRICT)
|
||||
.maxAge(3600)
|
||||
.build();
|
||||
|
||||
headers.add(HttpHeaders.SET_COOKIE, jwtCookie);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.drinkool.services;
|
||||
|
||||
import com.drinkool.Role;
|
||||
import com.drinkool.Url;
|
||||
import com.drinkool.dtos.*;
|
||||
import io.smallrye.mutiny.Uni;
|
||||
@@ -8,7 +9,7 @@ import jakarta.ws.rs.core.Response;
|
||||
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
|
||||
|
||||
@RegisterRestClient(configKey = "account")
|
||||
@Path("")
|
||||
@Path(Role.Customer)
|
||||
public interface AccountService {
|
||||
@POST
|
||||
@Path(Url.Signup)
|
||||
@@ -29,4 +30,7 @@ public interface AccountService {
|
||||
@POST
|
||||
@Path(Url.SmsOtp)
|
||||
Uni<Response> smsOtp(SmsOtp input);
|
||||
|
||||
@GET
|
||||
Uni<Response> me();
|
||||
}
|
||||
|
||||
@@ -9,3 +9,4 @@ quarkus.container-image.additional-tags=latest
|
||||
|
||||
# Build
|
||||
quarkus.native.container-build=false
|
||||
quarkus.native.additional-build-args=--future-defaults=all
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package com.drinkool.filters;
|
||||
|
||||
import static io.restassured.RestAssured.*;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.drinkool.InternalValue;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.eclipse.microprofile.config.inject.ConfigProperty;
|
||||
import org.jose4j.jws.AlgorithmIdentifiers;
|
||||
import org.jose4j.jws.JsonWebSignature;
|
||||
import org.jose4j.jwt.JwtClaims;
|
||||
import org.jose4j.keys.HmacKey;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@QuarkusTest
|
||||
public class InternalHeaderGatewayFilterTest {
|
||||
|
||||
@ConfigProperty(name = "gateway.jwt.secret")
|
||||
String TEST_SECRET;
|
||||
|
||||
private String createTestToken(String userId) throws Exception {
|
||||
JwtClaims claims = new JwtClaims();
|
||||
claims.setExpirationTimeMinutesInTheFuture(10);
|
||||
claims.setClaim("UserId", userId);
|
||||
claims.setClaim("Role", "user");
|
||||
|
||||
JsonWebSignature jws = new JsonWebSignature();
|
||||
jws.setPayload(claims.toJson());
|
||||
jws.setKey(new HmacKey(TEST_SECRET.getBytes()));
|
||||
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
|
||||
return jws.getCompactSerialization();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Nên xóa header X-Internal nếu client tự ý gửi lên")
|
||||
public void testShouldRemoveClentInternalHeaders() {
|
||||
given()
|
||||
.header("X-Internal-userId", "hacker-id")
|
||||
.when()
|
||||
.get("/test-gateway")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(is("not-found")); // Filter phải xóa sạch trước khi vào Resource
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Nên trích xuất JWT từ Cookie và gắn vào Header nội bộ")
|
||||
public void testValidJwtInCookie() throws Exception {
|
||||
String token = createTestToken("user123");
|
||||
|
||||
given()
|
||||
.cookie(InternalValue.cookieName, token)
|
||||
.when()
|
||||
.get("/test-gateway")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(is("user123")); // Resource nhận được userId từ Header do Filter gắn vào
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Nên trả về 401 nếu JWT sai chữ ký")
|
||||
public void testInvalidSignature() {
|
||||
given()
|
||||
.cookie(InternalValue.cookieName, "invalid.token.string")
|
||||
.when()
|
||||
.get("/test-gateway")
|
||||
.then()
|
||||
.statusCode(401)
|
||||
.body(containsString("InvalidToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"Nên đóng gói X-Internal headers từ service thành JWT gửi về client"
|
||||
)
|
||||
public void testResponseFilterConvertsHeadersToJwt() throws Exception {
|
||||
String token = createTestToken("user123");
|
||||
|
||||
Response response = given()
|
||||
.cookie(InternalValue.cookieName, token)
|
||||
.when()
|
||||
.post("/test-gateway/update")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.cookie(InternalValue.cookieName) // Kiểm tra có Set-Cookie trả về không
|
||||
.header("X-Internal-newStatus", nullValue()) // Header nội bộ phải bị xóa khỏi response
|
||||
.extract()
|
||||
.response();
|
||||
|
||||
String setCookie = response.getHeader("Set-Cookie");
|
||||
assertTrue(setCookie.contains("HttpOnly"));
|
||||
assertTrue(setCookie.contains("SameSite=Strict"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.drinkool.utils;
|
||||
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
@Path("/test-gateway")
|
||||
public class TestResource {
|
||||
|
||||
@GET
|
||||
public Response getHeaders(@Context HttpHeaders headers) {
|
||||
// Trả về header nội bộ để chúng ta kiểm tra xem Filter có gắn đúng không
|
||||
String userId = headers.getHeaderString("X-Internal-userId");
|
||||
return Response.ok().entity(userId != null ? userId : "not-found").build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/update")
|
||||
public Response updateInternal(
|
||||
@HeaderParam("X-Internal-userId") String userId
|
||||
) {
|
||||
// Giả lập service trả về header nội bộ để Gateway đóng gói vào JWT
|
||||
return Response.ok("updated")
|
||||
.header("X-Internal-newStatus", "active")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Quarkus
|
||||
quarkus.http.host=0.0.0.0
|
||||
|
||||
# JWT
|
||||
gateway.jwt.secret=1uZk07Hqu1316z9YqrcSGPTTJDhMWU1ZhFSLBrDQvmU=
|
||||
@@ -15,7 +15,7 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: account-pod
|
||||
image: git.demonkernel.io.vn/foodsurf/account-service:latest
|
||||
image: git.demonkernel.io.vn/foodsurf/account-service:1.4.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
@@ -38,20 +38,12 @@ spec:
|
||||
name: postgres-credentials
|
||||
key: url
|
||||
resources:
|
||||
limits:
|
||||
cpu: "500m"
|
||||
memory: "512Mi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "256Mi"
|
||||
volumeMounts:
|
||||
- name: keys-volume
|
||||
mountPath: "/etc/keys"
|
||||
readOnly: true
|
||||
volumes:
|
||||
- name: keys-volume
|
||||
secret:
|
||||
secretName: jwt-keys
|
||||
memory: "32Mi"
|
||||
cpu: "50m"
|
||||
limits:
|
||||
memory: "64Mi"
|
||||
cpu: "250m"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
@@ -64,7 +56,63 @@ spec:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
---
|
||||
# 2. GATEWAY SERVICE
|
||||
# 2. EATERY SERVICE
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: eatery-deploy
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: eatery
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: eatery
|
||||
spec:
|
||||
containers:
|
||||
- name: eatery-pod
|
||||
image: git.demonkernel.io.vn/foodsurf/eatery-service:1.4.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
env:
|
||||
- name: QUARKUS_DATASOURCE_PASSWORD
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: postgres-credentials
|
||||
key: password
|
||||
- name: QUARKUS_DATASOURCE_USERNAME
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: postgres-credentials
|
||||
key: username
|
||||
- name: QUARKUS_DATASOURCE_JDBC_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: postgres-credentials
|
||||
key: url
|
||||
resources:
|
||||
requests:
|
||||
memory: "32Mi"
|
||||
cpu: "50m"
|
||||
limits:
|
||||
memory: "64Mi"
|
||||
cpu: "250m"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: eatery-service
|
||||
spec:
|
||||
selector:
|
||||
app: eatery
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
---
|
||||
# 3. GATEWAY SERVICE
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
@@ -81,28 +129,25 @@ spec:
|
||||
spec:
|
||||
containers:
|
||||
- name: gateway-pod
|
||||
image: git.demonkernel.io.vn/foodsurf/gateway-service:latest
|
||||
image: git.demonkernel.io.vn/foodsurf/gateway-service:1.4.0
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- containerPort: 8080
|
||||
env:
|
||||
- name: QUARKUS_REST_CLIENT_ACCOUNT_URL
|
||||
value: "http://account-service"
|
||||
- name: GATEWAY_JWT_SECRET
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: jwt-secret
|
||||
key: secret
|
||||
resources:
|
||||
limits:
|
||||
cpu: "500m"
|
||||
memory: "512Mi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "256Mi"
|
||||
volumeMounts:
|
||||
- name: keys-volume
|
||||
mountPath: "/etc/keys"
|
||||
readOnly: true
|
||||
volumes:
|
||||
- name: keys-volume
|
||||
secret:
|
||||
secretName: jwt-keys
|
||||
memory: "32Mi"
|
||||
cpu: "50m"
|
||||
limits:
|
||||
memory: "64Mi"
|
||||
cpu: "250m"
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
@@ -117,7 +162,7 @@ spec:
|
||||
targetPort: 8080
|
||||
nodePort: 32080
|
||||
---
|
||||
# 3. REDIS
|
||||
# 4. REDIS
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
<parent>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>drinkool</artifactId>
|
||||
<version>1.1.0-dev.1</version>
|
||||
<version>1.4.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.drinkool;
|
||||
|
||||
public class InternalValue {
|
||||
|
||||
public static final String cookieName = "auth";
|
||||
public static final String headerId = "X-Internal-";
|
||||
public static final String userId = headerId + "UserId";
|
||||
public static final String role = headerId + "Role";
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.drinkool;
|
||||
|
||||
public class Jwt {
|
||||
public static final String headerId = "X-Internal-";
|
||||
public static final String userId = headerId + "UserId";
|
||||
public static final String role = headerId + "Role";
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.drinkool;
|
||||
|
||||
public class Role {
|
||||
public static final String Customer = "customer";
|
||||
|
||||
public static final String Customer = "customer";
|
||||
public static final String Manager = "manager";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.drinkool.dtos;
|
||||
|
||||
public class ManagerSignup extends Signup {
|
||||
public String eateryName;
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.drinkool</groupId>
|
||||
<artifactId>drinkool</artifactId>
|
||||
<version>1.1.0-dev.1</version>
|
||||
<version>1.4.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<properties>
|
||||
<maven.compiler.source>25</maven.compiler.source>
|
||||
@@ -30,6 +30,26 @@
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.quarkus</groupId>
|
||||
<artifactId>quarkus-jacoco</artifactId>
|
||||
<scope>test</scope>
|
||||
<version>${quarkus.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
</project>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<quarkus.jacoco.data-file>${maven.multiModuleProjectDirectory}/target/jacoco.exec</quarkus.jacoco.data-file>
|
||||
<quarkus.jacoco.reuse-data-file>true</quarkus.jacoco.reuse-data-file>
|
||||
<quarkus.jacoco.report-location>${maven.multiModuleProjectDirectory}/target/coverage</quarkus.jacoco.report-location>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Reference in New Issue
Block a user