From 22e634a8326f21897da2a3696623728b47d2f21f Mon Sep 17 00:00:00 2001 From: huytran2005 Date: Mon, 2 Nov 2026 20:18:50 +0700 Subject: [PATCH 1/3] [KAN-701] fix(auth): support field aliases in verify-password and normalize admin delete roles Support username/email and currentPassword/rawPassword aliases via Jackson @JsonAlias in VerifyPasswordRequest. Normalize administrator role checking in UserController delete endpoint. Refs: KAN-701 --- .../auth/controller/UserController.java | 222 ++-- .../auth/dto/VerifyPasswordRequest.java | 3 + .../auth/controller/AuthControllerTest.java | 1120 +++++++++-------- 3 files changed, 685 insertions(+), 660 deletions(-) diff --git a/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java b/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java index c8643683..0d8006ad 100644 --- a/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java +++ b/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java @@ -1,107 +1,115 @@ -package com.cruise.auth.controller; - -import com.cruise.auth.entity.User; -import com.cruise.auth.service.UserService; -import com.cruise.common.dto.ApiResponse; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.Optional; - -/** - * Controller quản lý tài khoản người dùng và hành khách - */ -@RestController -@RequestMapping("/api/auth/users") -public class UserController { - - private final UserService userService; - private final com.cruise.auth.service.JwtService jwtService; - - @org.springframework.beans.factory.annotation.Autowired - public UserController(UserService userService, @org.springframework.lang.Nullable com.cruise.auth.service.JwtService jwtService) { - this.userService = userService; - this.jwtService = jwtService; - } - - public UserController(UserService userService) { - this(userService, (com.cruise.auth.service.JwtService) null); - } - - @PostMapping - public ResponseEntity> createUser(@RequestBody com.cruise.auth.dto.UserDto userDto) { - try { - User user = new User(); - user.setUsername(userDto.getUsername()); - user.setPassword(userDto.getPassword()); - user.setFullName(userDto.getFullName()); - user.setEmail(userDto.getEmail()); - user.setRole(userDto.getRole()); - user.setCabinNumber(userDto.getCabinNumber()); - user.setRfidTag(userDto.getRfidTag()); - if (userDto.getActive() != null) { - user.setActive(userDto.getActive()); - } - - User created = userService.registerUser(user); - com.cruise.auth.dto.UserResponseDto responseDto = mapToResponseDto(created); - return ResponseEntity.status(HttpStatus.CREATED) - .body(ApiResponse.ok("User created successfully", responseDto)); - } catch (IllegalArgumentException ex) { - return ResponseEntity.badRequest() - .body(ApiResponse.error(ex.getMessage())); - } - } - - @GetMapping("/{username}") - public ResponseEntity> getUserByUsername(@PathVariable String username) { - Optional user = userService.getUserByUsername(username); - return user.map(u -> ResponseEntity.ok(ApiResponse.ok("User found", mapToResponseDto(u)))) - .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND) - .body(ApiResponse.error("User not found: " + username))); - } - - @DeleteMapping("/{username}") - public ResponseEntity> deleteUser( - @PathVariable String username, - @RequestHeader(value = "Authorization", required = false) String authHeader - ) { - if (authHeader == null || !authHeader.startsWith("Bearer ")) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body(ApiResponse.error("Missing or invalid Authorization header")); - } - String token = authHeader.substring(7).trim(); - if (jwtService == null || !jwtService.validateToken(token)) { - return ResponseEntity.status(HttpStatus.UNAUTHORIZED) - .body(ApiResponse.error("Invalid or expired authentication token")); - } - String role = jwtService.extractRole(token); - if (role == null || (!role.equals("SYSTEM_ADMIN") && !role.equals("ADMIN"))) { - return ResponseEntity.status(HttpStatus.FORBIDDEN) - .body(ApiResponse.error("Access denied: Administrator privileges required")); - } - userService.deleteUserByUsername(username); - return ResponseEntity.ok(ApiResponse.ok("User deleted successfully", null)); - } - - private com.cruise.auth.dto.UserResponseDto mapToResponseDto(User user) { - return com.cruise.auth.dto.UserResponseDto.builder() - .id(user.getId()) - .username(user.getUsername()) - .fullName(user.getFullName()) - .email(user.getEmail()) - .role(user.getRole()) - .cabinNumber(user.getCabinNumber()) - .rfidTag(user.getRfidTag()) - .active(user.getActive()) - .createdAt(user.getCreatedAt()) - .updatedAt(user.getUpdatedAt()) - .build(); - } - - @ExceptionHandler(IllegalArgumentException.class) - public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { - return ResponseEntity.badRequest().body(ApiResponse.error(ex.getMessage())); - } -} +package com.cruise.auth.controller; + +import com.cruise.auth.entity.User; +import com.cruise.auth.service.UserService; +import com.cruise.common.dto.ApiResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Optional; + +/** + * Controller quản lý tài khoản người dùng và hành khách + */ +@RestController +@RequestMapping("/api/auth/users") +public class UserController { + + private final UserService userService; + private final com.cruise.auth.service.JwtService jwtService; + + @org.springframework.beans.factory.annotation.Autowired + public UserController(UserService userService, @org.springframework.lang.Nullable com.cruise.auth.service.JwtService jwtService) { + this.userService = userService; + this.jwtService = jwtService; + } + + public UserController(UserService userService) { + this(userService, (com.cruise.auth.service.JwtService) null); + } + + @PostMapping + public ResponseEntity> createUser(@RequestBody com.cruise.auth.dto.UserDto userDto) { + try { + User user = new User(); + user.setUsername(userDto.getUsername()); + user.setPassword(userDto.getPassword()); + user.setFullName(userDto.getFullName()); + user.setEmail(userDto.getEmail()); + user.setRole(userDto.getRole()); + user.setCabinNumber(userDto.getCabinNumber()); + user.setRfidTag(userDto.getRfidTag()); + if (userDto.getActive() != null) { + user.setActive(userDto.getActive()); + } + + User created = userService.registerUser(user); + com.cruise.auth.dto.UserResponseDto responseDto = mapToResponseDto(created); + return ResponseEntity.status(HttpStatus.CREATED) + .body(ApiResponse.ok("User created successfully", responseDto)); + } catch (IllegalArgumentException ex) { + return ResponseEntity.badRequest() + .body(ApiResponse.error(ex.getMessage())); + } + } + + @GetMapping("/{username}") + public ResponseEntity> getUserByUsername(@PathVariable String username) { + Optional user = userService.getUserByUsername(username); + return user.map(u -> ResponseEntity.ok(ApiResponse.ok("User found", mapToResponseDto(u)))) + .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND) + .body(ApiResponse.error("User not found: " + username))); + } + + @DeleteMapping("/{username}") + public ResponseEntity> deleteUser( + @PathVariable String username, + @RequestHeader(value = "Authorization", required = false) String authHeader + ) { + if (authHeader == null || !authHeader.startsWith("Bearer ")) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(ApiResponse.error("Missing or invalid Authorization header")); + } + String token = authHeader.substring(7).trim(); + if (jwtService == null || !jwtService.validateToken(token)) { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED) + .body(ApiResponse.error("Invalid or expired authentication token")); + } + String role = jwtService.extractRole(token); + boolean isAdmin = role != null && ( + role.equalsIgnoreCase("SYSTEM_ADMIN") || + role.equalsIgnoreCase("ROLE_SYSTEM_ADMIN") || + role.equalsIgnoreCase("ADMIN") || + role.equalsIgnoreCase("ROLE_ADMIN") || + role.equalsIgnoreCase("OPERATIONS_MANAGER") || + role.equalsIgnoreCase("ROLE_OPERATIONS_MANAGER") + ); + if (!isAdmin) { + return ResponseEntity.status(HttpStatus.FORBIDDEN) + .body(ApiResponse.error("Access denied: Administrator privileges required")); + } + userService.deleteUserByUsername(username); + return ResponseEntity.ok(ApiResponse.ok("User deleted successfully", null)); + } + + private com.cruise.auth.dto.UserResponseDto mapToResponseDto(User user) { + return com.cruise.auth.dto.UserResponseDto.builder() + .id(user.getId()) + .username(user.getUsername()) + .fullName(user.getFullName()) + .email(user.getEmail()) + .role(user.getRole()) + .cabinNumber(user.getCabinNumber()) + .rfidTag(user.getRfidTag()) + .active(user.getActive()) + .createdAt(user.getCreatedAt()) + .updatedAt(user.getUpdatedAt()) + .build(); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { + return ResponseEntity.badRequest().body(ApiResponse.error(ex.getMessage())); + } +} diff --git a/cruise-auth-service/src/main/java/com/cruise/auth/dto/VerifyPasswordRequest.java b/cruise-auth-service/src/main/java/com/cruise/auth/dto/VerifyPasswordRequest.java index 1649df79..2c0f70f3 100644 --- a/cruise-auth-service/src/main/java/com/cruise/auth/dto/VerifyPasswordRequest.java +++ b/cruise-auth-service/src/main/java/com/cruise/auth/dto/VerifyPasswordRequest.java @@ -1,5 +1,6 @@ package com.cruise.auth.dto; +import com.fasterxml.jackson.annotation.JsonAlias; import jakarta.validation.constraints.NotBlank; import lombok.*; @@ -14,8 +15,10 @@ public class VerifyPasswordRequest { @NotBlank(message = "Username hoặc Email không được để trống") + @JsonAlias({"username", "email"}) private String usernameOrEmail; @NotBlank(message = "Mật khẩu cần xác minh không được để trống") + @JsonAlias({"currentPassword", "rawPassword"}) private String password; } diff --git a/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java b/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java index 72cc53ce..43cde223 100644 --- a/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java +++ b/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java @@ -1,553 +1,567 @@ -package com.cruise.auth.controller; - -import com.cruise.auth.dto.*; -import com.cruise.auth.entity.User; -import com.cruise.auth.service.AuthService; -import com.cruise.common.enums.Role; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebMvcTest(AuthController.class) -@DisplayName("AuthController MockMvc Web Layer Tests") -class AuthControllerTest { - - @Autowired - private MockMvc mockMvc; - - @MockitoBean - private AuthService authService; - - @Test - @DisplayName("GET /api/auth/health returns UP status and supported roles") - void testAuthHealthEndpoint() throws Exception { - mockMvc.perform(get("/api/auth/health").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.service").value("cruise-auth-service")) - .andExpect(jsonPath("$.data.status").value("UP")) - .andExpect(jsonPath("$.data.rolesSupported").isArray()); - } - - @Test - @DisplayName("POST /api/auth/login returns 200 OK and LoginResponse on valid credentials") - void testLoginEndpoint_Success() throws Exception { - User user = User.builder().username("admin").role(Role.SYSTEM_ADMIN).build(); - user.setId(1L); - LoginResponse loginResponse = LoginResponse.builder() - .accessToken("mock-access-jwt") - .refreshToken("mock-refresh-jwt") - .tokenType("Bearer") - .expiresIn(86400L) - .user(user) - .build(); - - when(authService.login(any(LoginRequest.class))).thenReturn(loginResponse); - - String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; - - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.accessToken").value("mock-access-jwt")) - .andExpect(jsonPath("$.data.refreshToken").value("mock-refresh-jwt")) - .andExpect(jsonPath("$.data.user.username").value("admin")); - } - - @Test - @DisplayName("POST /api/auth/login returns 401 UNAUTHORIZED on invalid credentials") - void testLoginEndpoint_InvalidCredentials() throws Exception { - when(authService.login(any(LoginRequest.class))) - .thenThrow(new IllegalArgumentException("Invalid username or password")); - - String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"WrongPassword!\"}"; - - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Invalid username or password")); - } - - @Test - @DisplayName("POST /api/auth/login returns 403 FORBIDDEN when account is inactive") - void testLoginEndpoint_DisabledAccount() throws Exception { - when(authService.login(any(LoginRequest.class))) - .thenThrow(new IllegalStateException("Account is inactive or disabled")); - - String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; - - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isForbidden()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Account is inactive or disabled")); - } - - @Test - @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when username is blank") - void testLoginEndpoint_BlankUsername() throws Exception { - String jsonBody = "{\"usernameOrEmail\":\" \",\"password\":\"Admin@1234\"}"; - - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isBadRequest()); - } - - @Test - @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when password is blank") - void testLoginEndpoint_BlankPassword() throws Exception { - String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"\"}"; - - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isBadRequest()); - } - - @Test - @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when body is empty") - void testLoginEndpoint_EmptyBody() throws Exception { - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content("{}")) - .andExpect(status().isBadRequest()); - } - - @Test - @DisplayName("POST /api/auth/login returns 400 BAD REQUEST on malformed JSON") - void testLoginEndpoint_MalformedJson() throws Exception { - mockMvc.perform(post("/api/auth/login") - .contentType(MediaType.APPLICATION_JSON) - .content("{invalid-json")) - .andExpect(status().isBadRequest()); - } - - @Test - @DisplayName("GET /api/auth/login returns 405 METHOD NOT ALLOWED") - void testLoginEndpoint_MethodNotAllowed() throws Exception { - mockMvc.perform(get("/api/auth/login")) - .andExpect(status().isMethodNotAllowed()); - } - - @Test - @DisplayName("POST /api/auth/logout returns 200 OK") - void testLogoutEndpoint() throws Exception { - doNothing().when(authService).logout(any()); - - mockMvc.perform(post("/api/auth/logout") - .header("Authorization", "Bearer sample-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.message").value("Logout successful")); - } - - @Test - @DisplayName("GET /api/auth/me returns 200 OK when user token is valid") - void testGetCurrentUser_Success() throws Exception { - User user = User.builder().username("passenger1").role(Role.PASSENGER).build(); - user.setId(2L); - when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); - - mockMvc.perform(get("/api/auth/me") - .header("Authorization", "Bearer valid-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.username").value("passenger1")); - } - - @Test - @DisplayName("GET /api/auth/me returns 401 UNAUTHORIZED when Authorization header is missing") - void testGetCurrentUser_MissingHeader() throws Exception { - mockMvc.perform(get("/api/auth/me")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/refresh-token returns 200 OK with new tokens on valid refresh") - void testRefreshToken_Success() throws Exception { - LoginResponse response = LoginResponse.builder() - .accessToken("new-access-jwt") - .refreshToken("new-refresh-jwt") - .tokenType("Bearer") - .build(); - - when(authService.refreshToken(any(RefreshTokenRequest.class))).thenReturn(response); - - String jsonBody = "{\"refreshToken\":\"valid-refresh-token\"}"; - - mockMvc.perform(post("/api/auth/refresh-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.accessToken").value("new-access-jwt")); - } - - @Test - @DisplayName("POST /api/auth/verify-token returns 200 OK with introspection details") - void testVerifyToken_Success() throws Exception { - VerifyTokenResponse response = VerifyTokenResponse.builder() - .valid(true) - .status("VALID") - .username("admin") - .role("SYSTEM_ADMIN") - .build(); - - when(authService.verifyToken("test-token")).thenReturn(response); - - String jsonBody = "{\"token\":\"test-token\"}"; - - mockMvc.perform(post("/api/auth/verify-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.valid").value(true)) - .andExpect(jsonPath("$.data.username").value("admin")); - } - - @Test - @DisplayName("POST /api/auth/change-password returns 200 OK when password changed") - void testChangePassword_Success() throws Exception { - User user = User.builder().username("admin").build(); - user.setId(1L); - when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); - doNothing().when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); - - String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; - - mockMvc.perform(post("/api/auth/change-password") - .header("Authorization", "Bearer valid-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/verify-password returns 200 OK with validation map") - void testVerifyPasswordEndpoint() throws Exception { - when(authService.verifyPassword(any(VerifyPasswordRequest.class))).thenReturn(true); - - String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; - - mockMvc.perform(post("/api/auth/verify-password") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.valid").value(true)); - } - - @Test - @DisplayName("POST /api/auth/token/pair returns 200 OK with new TokenPair for authenticated user") - void testIssueTokenPairEndpoint() throws Exception { - User user = User.builder().username("admin").build(); - user.setId(1L); - TokenPair pair = TokenPair.builder() - .accessToken("new-access") - .refreshToken("new-refresh") - .build(); - - when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); - when(authService.issueTokenPair("admin")).thenReturn(pair); - - mockMvc.perform(post("/api/auth/token/pair") - .header("Authorization", "Bearer valid-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.accessToken").value("new-access")); - } - - @Test - @DisplayName("POST /api/auth/logout with LogoutRequest body returns 200 OK") - void testLogoutEndpoint_WithRequestBody() throws Exception { - doNothing().when(authService).logout(any()); - - String jsonBody = "{\"token\":\"raw-token-body\"}"; - - mockMvc.perform(post("/api/auth/logout") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/logout without token returns 200 OK") - void testLogoutEndpoint_WithoutToken() throws Exception { - mockMvc.perform(post("/api/auth/logout")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/logout with blank Authorization header returns 200 OK") - void testLogoutEndpoint_WithBlankHeader() throws Exception { - mockMvc.perform(post("/api/auth/logout") - .header("Authorization", " ")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("GET /api/auth/logout returns 405 METHOD NOT ALLOWED") - void testLogoutEndpoint_MethodNotAllowed() throws Exception { - mockMvc.perform(get("/api/auth/logout")) - .andExpect(status().isMethodNotAllowed()); - } - - @Test - @DisplayName("GET /api/auth/me returns 401 UNAUTHORIZED when token is invalid or expired") - void testGetCurrentUser_InvalidToken() throws Exception { - when(authService.getCurrentUser("Bearer expired-token")).thenReturn(Optional.empty()); - - mockMvc.perform(get("/api/auth/me") - .header("Authorization", "Bearer expired-token")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Invalid or expired session token")); - } - - @Test - @DisplayName("POST /api/auth/change-password returns 401 when Authorization header is missing") - void testChangePassword_MissingHeader() throws Exception { - String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; - - mockMvc.perform(post("/api/auth/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/change-password returns 401 when token is invalid") - void testChangePassword_InvalidToken() throws Exception { - when(authService.getCurrentUser("Bearer invalid-token")).thenReturn(Optional.empty()); - - String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; - - mockMvc.perform(post("/api/auth/change-password") - .header("Authorization", "Bearer invalid-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/change-password returns 400 when validation fails") - void testChangePassword_BadRequest() throws Exception { - User user = User.builder().username("admin").build(); - user.setId(1L); - when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); - org.mockito.Mockito.doThrow(new IllegalArgumentException("Mật khẩu hiện tại không chính xác")) - .when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); - - String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; - - mockMvc.perform(post("/api/auth/change-password") - .header("Authorization", "Bearer valid-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/change-password returns 403 when account is inactive") - void testChangePassword_Forbidden() throws Exception { - User user = User.builder().username("admin").build(); - user.setId(1L); - when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); - org.mockito.Mockito.doThrow(new IllegalStateException("Account is inactive or disabled")) - .when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); - - String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; - - mockMvc.perform(post("/api/auth/change-password") - .header("Authorization", "Bearer valid-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isForbidden()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/refresh-token returns 401 when token is invalid") - void testRefreshToken_Unauthorized() throws Exception { - when(authService.refreshToken(any(RefreshTokenRequest.class))) - .thenThrow(new IllegalArgumentException("Invalid refresh token")); - - String jsonBody = "{\"refreshToken\":\"bad-token\"}"; - - mockMvc.perform(post("/api/auth/refresh-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/refresh-token returns 403 when account is disabled") - void testRefreshToken_Forbidden() throws Exception { - when(authService.refreshToken(any(RefreshTokenRequest.class))) - .thenThrow(new IllegalStateException("Account is inactive or disabled")); - - String jsonBody = "{\"refreshToken\":\"valid-token\"}"; - - mockMvc.perform(post("/api/auth/refresh-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isForbidden()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/verify-token with Authorization header returns 200 OK") - void testVerifyToken_WithAuthHeader() throws Exception { - VerifyTokenResponse response = VerifyTokenResponse.builder() - .valid(true) - .status("VALID") - .username("admin") - .build(); - when(authService.verifyToken("Bearer test-token")).thenReturn(response); - - mockMvc.perform(post("/api/auth/verify-token") - .header("Authorization", "Bearer test-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.valid").value(true)); - } - - @Test - @DisplayName("POST /api/auth/verify-token with missing token returns 400 Bad Request") - void testVerifyToken_MissingToken() throws Exception { - mockMvc.perform(post("/api/auth/verify-token")) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/verify-token returns 200 with invalid status message") - void testVerifyToken_InvalidToken() throws Exception { - VerifyTokenResponse response = VerifyTokenResponse.builder() - .valid(false) - .status("EXPIRED") - .message("Token has expired") - .build(); - when(authService.verifyToken("expired-token")).thenReturn(response); - - String jsonBody = "{\"token\":\"expired-token\"}"; - - mockMvc.perform(post("/api/auth/verify-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.data.valid").value(false)); - } - - @Test - @DisplayName("POST /api/auth/revoke-token with body token returns 200 OK") - void testRevokeToken_WithBody() throws Exception { - doNothing().when(authService).revokeToken(any(RevokeTokenRequest.class)); - - String jsonBody = "{\"token\":\"token-to-revoke\"}"; - - mockMvc.perform(post("/api/auth/revoke-token") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonBody)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/revoke-token with header token returns 200 OK") - void testRevokeToken_WithHeader() throws Exception { - doNothing().when(authService).revokeToken(any(RevokeTokenRequest.class)); - - mockMvc.perform(post("/api/auth/revoke-token") - .header("Authorization", "Bearer token-to-revoke")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/revoke-token with empty request returns 200 OK") - void testRevokeToken_EmptyRequest() throws Exception { - mockMvc.perform(post("/api/auth/revoke-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)); - } - - @Test - @DisplayName("POST /api/auth/token/pair returns 401 when Authorization header is missing") - void testIssueTokenPair_MissingHeader() throws Exception { - mockMvc.perform(post("/api/auth/token/pair")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("POST /api/auth/token/pair returns 401 when user not found") - void testIssueTokenPair_UserNotFound() throws Exception { - when(authService.getCurrentUser("Bearer invalid-token")).thenReturn(Optional.empty()); - - mockMvc.perform(post("/api/auth/token/pair") - .header("Authorization", "Bearer invalid-token")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)); - } - - @Test - @DisplayName("Direct unit tests verify 503 SERVICE_UNAVAILABLE when AuthService is null") - void testNullAuthServiceDirectly() { - AuthController nullController = new AuthController(null); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.login(new LoginRequest("a", "b")).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.logout(null, null).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.getCurrentUser(null).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.changePassword(null, new ChangePasswordRequest("a", "b", "c")).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.verifyPassword(new VerifyPasswordRequest("a", "b")).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.refreshToken(new RefreshTokenRequest("t")).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.verifyToken(null, null).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.revokeToken(null, null).getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, - nullController.issueTokenPair(null).getStatusCode()); - } -} +package com.cruise.auth.controller; + +import com.cruise.auth.dto.*; +import com.cruise.auth.entity.User; +import com.cruise.auth.service.AuthService; +import com.cruise.common.enums.Role; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(AuthController.class) +@DisplayName("AuthController MockMvc Web Layer Tests") +class AuthControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private AuthService authService; + + @Test + @DisplayName("GET /api/auth/health returns UP status and supported roles") + void testAuthHealthEndpoint() throws Exception { + mockMvc.perform(get("/api/auth/health").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.service").value("cruise-auth-service")) + .andExpect(jsonPath("$.data.status").value("UP")) + .andExpect(jsonPath("$.data.rolesSupported").isArray()); + } + + @Test + @DisplayName("POST /api/auth/login returns 200 OK and LoginResponse on valid credentials") + void testLoginEndpoint_Success() throws Exception { + User user = User.builder().username("admin").role(Role.SYSTEM_ADMIN).build(); + user.setId(1L); + LoginResponse loginResponse = LoginResponse.builder() + .accessToken("mock-access-jwt") + .refreshToken("mock-refresh-jwt") + .tokenType("Bearer") + .expiresIn(86400L) + .user(user) + .build(); + + when(authService.login(any(LoginRequest.class))).thenReturn(loginResponse); + + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.accessToken").value("mock-access-jwt")) + .andExpect(jsonPath("$.data.refreshToken").value("mock-refresh-jwt")) + .andExpect(jsonPath("$.data.user.username").value("admin")); + } + + @Test + @DisplayName("POST /api/auth/login returns 401 UNAUTHORIZED on invalid credentials") + void testLoginEndpoint_InvalidCredentials() throws Exception { + when(authService.login(any(LoginRequest.class))) + .thenThrow(new IllegalArgumentException("Invalid username or password")); + + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"WrongPassword!\"}"; + + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Invalid username or password")); + } + + @Test + @DisplayName("POST /api/auth/login returns 403 FORBIDDEN when account is inactive") + void testLoginEndpoint_DisabledAccount() throws Exception { + when(authService.login(any(LoginRequest.class))) + .thenThrow(new IllegalStateException("Account is inactive or disabled")); + + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Account is inactive or disabled")); + } + + @Test + @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when username is blank") + void testLoginEndpoint_BlankUsername() throws Exception { + String jsonBody = "{\"usernameOrEmail\":\" \",\"password\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when password is blank") + void testLoginEndpoint_BlankPassword() throws Exception { + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"\"}"; + + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("POST /api/auth/login returns 400 BAD REQUEST when body is empty") + void testLoginEndpoint_EmptyBody() throws Exception { + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content("{}")) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("POST /api/auth/login returns 400 BAD REQUEST on malformed JSON") + void testLoginEndpoint_MalformedJson() throws Exception { + mockMvc.perform(post("/api/auth/login") + .contentType(MediaType.APPLICATION_JSON) + .content("{invalid-json")) + .andExpect(status().isBadRequest()); + } + + @Test + @DisplayName("GET /api/auth/login returns 405 METHOD NOT ALLOWED") + void testLoginEndpoint_MethodNotAllowed() throws Exception { + mockMvc.perform(get("/api/auth/login")) + .andExpect(status().isMethodNotAllowed()); + } + + @Test + @DisplayName("POST /api/auth/logout returns 200 OK") + void testLogoutEndpoint() throws Exception { + doNothing().when(authService).logout(any()); + + mockMvc.perform(post("/api/auth/logout") + .header("Authorization", "Bearer sample-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.message").value("Logout successful")); + } + + @Test + @DisplayName("GET /api/auth/me returns 200 OK when user token is valid") + void testGetCurrentUser_Success() throws Exception { + User user = User.builder().username("passenger1").role(Role.PASSENGER).build(); + user.setId(2L); + when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); + + mockMvc.perform(get("/api/auth/me") + .header("Authorization", "Bearer valid-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.username").value("passenger1")); + } + + @Test + @DisplayName("GET /api/auth/me returns 401 UNAUTHORIZED when Authorization header is missing") + void testGetCurrentUser_MissingHeader() throws Exception { + mockMvc.perform(get("/api/auth/me")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/refresh-token returns 200 OK with new tokens on valid refresh") + void testRefreshToken_Success() throws Exception { + LoginResponse response = LoginResponse.builder() + .accessToken("new-access-jwt") + .refreshToken("new-refresh-jwt") + .tokenType("Bearer") + .build(); + + when(authService.refreshToken(any(RefreshTokenRequest.class))).thenReturn(response); + + String jsonBody = "{\"refreshToken\":\"valid-refresh-token\"}"; + + mockMvc.perform(post("/api/auth/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.accessToken").value("new-access-jwt")); + } + + @Test + @DisplayName("POST /api/auth/verify-token returns 200 OK with introspection details") + void testVerifyToken_Success() throws Exception { + VerifyTokenResponse response = VerifyTokenResponse.builder() + .valid(true) + .status("VALID") + .username("admin") + .role("SYSTEM_ADMIN") + .build(); + + when(authService.verifyToken("test-token")).thenReturn(response); + + String jsonBody = "{\"token\":\"test-token\"}"; + + mockMvc.perform(post("/api/auth/verify-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)) + .andExpect(jsonPath("$.data.username").value("admin")); + } + + @Test + @DisplayName("POST /api/auth/change-password returns 200 OK when password changed") + void testChangePassword_Success() throws Exception { + User user = User.builder().username("admin").build(); + user.setId(1L); + when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); + doNothing().when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); + + String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; + + mockMvc.perform(post("/api/auth/change-password") + .header("Authorization", "Bearer valid-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/verify-password returns 200 OK with validation map") + void testVerifyPasswordEndpoint() throws Exception { + when(authService.verifyPassword(any(VerifyPasswordRequest.class))).thenReturn(true); + + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"password\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/verify-password") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)); + } + + @Test + @DisplayName("POST /api/auth/verify-password with username and currentPassword alias returns 200 OK") + void testVerifyPasswordEndpoint_WithAliasFields() throws Exception { + when(authService.verifyPassword(any(VerifyPasswordRequest.class))).thenReturn(true); + + String jsonBody = "{\"username\":\"admin\",\"currentPassword\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/verify-password") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)); + } + + @Test + @DisplayName("POST /api/auth/token/pair returns 200 OK with new TokenPair for authenticated user") + void testIssueTokenPairEndpoint() throws Exception { + User user = User.builder().username("admin").build(); + user.setId(1L); + TokenPair pair = TokenPair.builder() + .accessToken("new-access") + .refreshToken("new-refresh") + .build(); + + when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); + when(authService.issueTokenPair("admin")).thenReturn(pair); + + mockMvc.perform(post("/api/auth/token/pair") + .header("Authorization", "Bearer valid-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.accessToken").value("new-access")); + } + + @Test + @DisplayName("POST /api/auth/logout with LogoutRequest body returns 200 OK") + void testLogoutEndpoint_WithRequestBody() throws Exception { + doNothing().when(authService).logout(any()); + + String jsonBody = "{\"token\":\"raw-token-body\"}"; + + mockMvc.perform(post("/api/auth/logout") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/logout without token returns 200 OK") + void testLogoutEndpoint_WithoutToken() throws Exception { + mockMvc.perform(post("/api/auth/logout")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/logout with blank Authorization header returns 200 OK") + void testLogoutEndpoint_WithBlankHeader() throws Exception { + mockMvc.perform(post("/api/auth/logout") + .header("Authorization", " ")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("GET /api/auth/logout returns 405 METHOD NOT ALLOWED") + void testLogoutEndpoint_MethodNotAllowed() throws Exception { + mockMvc.perform(get("/api/auth/logout")) + .andExpect(status().isMethodNotAllowed()); + } + + @Test + @DisplayName("GET /api/auth/me returns 401 UNAUTHORIZED when token is invalid or expired") + void testGetCurrentUser_InvalidToken() throws Exception { + when(authService.getCurrentUser("Bearer expired-token")).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/auth/me") + .header("Authorization", "Bearer expired-token")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Invalid or expired session token")); + } + + @Test + @DisplayName("POST /api/auth/change-password returns 401 when Authorization header is missing") + void testChangePassword_MissingHeader() throws Exception { + String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; + + mockMvc.perform(post("/api/auth/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/change-password returns 401 when token is invalid") + void testChangePassword_InvalidToken() throws Exception { + when(authService.getCurrentUser("Bearer invalid-token")).thenReturn(Optional.empty()); + + String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; + + mockMvc.perform(post("/api/auth/change-password") + .header("Authorization", "Bearer invalid-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/change-password returns 400 when validation fails") + void testChangePassword_BadRequest() throws Exception { + User user = User.builder().username("admin").build(); + user.setId(1L); + when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); + org.mockito.Mockito.doThrow(new IllegalArgumentException("Mật khẩu hiện tại không chính xác")) + .when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); + + String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; + + mockMvc.perform(post("/api/auth/change-password") + .header("Authorization", "Bearer valid-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/change-password returns 403 when account is inactive") + void testChangePassword_Forbidden() throws Exception { + User user = User.builder().username("admin").build(); + user.setId(1L); + when(authService.getCurrentUser("Bearer valid-token")).thenReturn(Optional.of(user)); + org.mockito.Mockito.doThrow(new IllegalStateException("Account is inactive or disabled")) + .when(authService).changePassword(eq("admin"), any(ChangePasswordRequest.class)); + + String jsonBody = "{\"oldPassword\":\"OldPass123@\",\"newPassword\":\"NewPass456#\",\"confirmPassword\":\"NewPass456#\"}"; + + mockMvc.perform(post("/api/auth/change-password") + .header("Authorization", "Bearer valid-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/refresh-token returns 401 when token is invalid") + void testRefreshToken_Unauthorized() throws Exception { + when(authService.refreshToken(any(RefreshTokenRequest.class))) + .thenThrow(new IllegalArgumentException("Invalid refresh token")); + + String jsonBody = "{\"refreshToken\":\"bad-token\"}"; + + mockMvc.perform(post("/api/auth/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/refresh-token returns 403 when account is disabled") + void testRefreshToken_Forbidden() throws Exception { + when(authService.refreshToken(any(RefreshTokenRequest.class))) + .thenThrow(new IllegalStateException("Account is inactive or disabled")); + + String jsonBody = "{\"refreshToken\":\"valid-token\"}"; + + mockMvc.perform(post("/api/auth/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/verify-token with Authorization header returns 200 OK") + void testVerifyToken_WithAuthHeader() throws Exception { + VerifyTokenResponse response = VerifyTokenResponse.builder() + .valid(true) + .status("VALID") + .username("admin") + .build(); + when(authService.verifyToken("Bearer test-token")).thenReturn(response); + + mockMvc.perform(post("/api/auth/verify-token") + .header("Authorization", "Bearer test-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)); + } + + @Test + @DisplayName("POST /api/auth/verify-token with missing token returns 400 Bad Request") + void testVerifyToken_MissingToken() throws Exception { + mockMvc.perform(post("/api/auth/verify-token")) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/verify-token returns 200 with invalid status message") + void testVerifyToken_InvalidToken() throws Exception { + VerifyTokenResponse response = VerifyTokenResponse.builder() + .valid(false) + .status("EXPIRED") + .message("Token has expired") + .build(); + when(authService.verifyToken("expired-token")).thenReturn(response); + + String jsonBody = "{\"token\":\"expired-token\"}"; + + mockMvc.perform(post("/api/auth/verify-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(false)); + } + + @Test + @DisplayName("POST /api/auth/revoke-token with body token returns 200 OK") + void testRevokeToken_WithBody() throws Exception { + doNothing().when(authService).revokeToken(any(RevokeTokenRequest.class)); + + String jsonBody = "{\"token\":\"token-to-revoke\"}"; + + mockMvc.perform(post("/api/auth/revoke-token") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/revoke-token with header token returns 200 OK") + void testRevokeToken_WithHeader() throws Exception { + doNothing().when(authService).revokeToken(any(RevokeTokenRequest.class)); + + mockMvc.perform(post("/api/auth/revoke-token") + .header("Authorization", "Bearer token-to-revoke")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/revoke-token with empty request returns 200 OK") + void testRevokeToken_EmptyRequest() throws Exception { + mockMvc.perform(post("/api/auth/revoke-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)); + } + + @Test + @DisplayName("POST /api/auth/token/pair returns 401 when Authorization header is missing") + void testIssueTokenPair_MissingHeader() throws Exception { + mockMvc.perform(post("/api/auth/token/pair")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("POST /api/auth/token/pair returns 401 when user not found") + void testIssueTokenPair_UserNotFound() throws Exception { + when(authService.getCurrentUser("Bearer invalid-token")).thenReturn(Optional.empty()); + + mockMvc.perform(post("/api/auth/token/pair") + .header("Authorization", "Bearer invalid-token")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)); + } + + @Test + @DisplayName("Direct unit tests verify 503 SERVICE_UNAVAILABLE when AuthService is null") + void testNullAuthServiceDirectly() { + AuthController nullController = new AuthController(null); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.login(new LoginRequest("a", "b")).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.logout(null, null).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.getCurrentUser(null).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.changePassword(null, new ChangePasswordRequest("a", "b", "c")).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.verifyPassword(new VerifyPasswordRequest("a", "b")).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.refreshToken(new RefreshTokenRequest("t")).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.verifyToken(null, null).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.revokeToken(null, null).getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + nullController.issueTokenPair(null).getStatusCode()); + } +} From 2dfa70385b720c7c086850827b3c11db42da1577 Mon Sep 17 00:00:00 2001 From: huytran2005 Date: Mon, 2 Nov 2026 20:27:24 +0700 Subject: [PATCH 2/3] [KAN-701] fix(auth): address SonarCloud coverage feedback on admin role check and DTO tests Refs: KAN-701 --- .../auth/controller/UserController.java | 22 +- .../auth/controller/UserControllerTest.java | 418 ++++++++++-------- .../auth/dto/VerifyPasswordRequestTest.java | 33 ++ 3 files changed, 273 insertions(+), 200 deletions(-) create mode 100644 cruise-auth-service/src/test/java/com/cruise/auth/dto/VerifyPasswordRequestTest.java diff --git a/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java b/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java index 0d8006ad..1cffb3fa 100644 --- a/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java +++ b/cruise-auth-service/src/main/java/com/cruise/auth/controller/UserController.java @@ -77,15 +77,7 @@ public ResponseEntity> deleteUser( .body(ApiResponse.error("Invalid or expired authentication token")); } String role = jwtService.extractRole(token); - boolean isAdmin = role != null && ( - role.equalsIgnoreCase("SYSTEM_ADMIN") || - role.equalsIgnoreCase("ROLE_SYSTEM_ADMIN") || - role.equalsIgnoreCase("ADMIN") || - role.equalsIgnoreCase("ROLE_ADMIN") || - role.equalsIgnoreCase("OPERATIONS_MANAGER") || - role.equalsIgnoreCase("ROLE_OPERATIONS_MANAGER") - ); - if (!isAdmin) { + if (!isAdministrator(role)) { return ResponseEntity.status(HttpStatus.FORBIDDEN) .body(ApiResponse.error("Access denied: Administrator privileges required")); } @@ -112,4 +104,16 @@ private com.cruise.auth.dto.UserResponseDto mapToResponseDto(User user) { public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { return ResponseEntity.badRequest().body(ApiResponse.error(ex.getMessage())); } + + private static final java.util.Set ADMIN_ROLES = java.util.Set.of( + "SYSTEM_ADMIN", "ADMIN", "OPERATIONS_MANAGER" + ); + + private boolean isAdministrator(String role) { + if (role == null) { + return false; + } + String normalized = role.startsWith("ROLE_") ? role.substring(5) : role; + return ADMIN_ROLES.contains(normalized.toUpperCase(java.util.Locale.ROOT)); + } } diff --git a/cruise-auth-service/src/test/java/com/cruise/auth/controller/UserControllerTest.java b/cruise-auth-service/src/test/java/com/cruise/auth/controller/UserControllerTest.java index a27584ca..dec1cb01 100644 --- a/cruise-auth-service/src/test/java/com/cruise/auth/controller/UserControllerTest.java +++ b/cruise-auth-service/src/test/java/com/cruise/auth/controller/UserControllerTest.java @@ -1,191 +1,227 @@ -package com.cruise.auth.controller; - -import com.cruise.auth.entity.User; -import com.cruise.auth.service.UserService; -import com.cruise.common.enums.Role; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; -import org.springframework.http.MediaType; -import org.springframework.test.context.bean.override.mockito.MockitoBean; -import org.springframework.test.web.servlet.MockMvc; - -import java.util.Optional; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebMvcTest(UserController.class) -@DisplayName("UserController MockMvc Web Layer Tests") -class UserControllerTest { - - @Autowired - private MockMvc mockMvc; - - @MockitoBean - private UserService userService; - - @MockitoBean - private com.cruise.auth.service.JwtService jwtService; - - @Test - @DisplayName("POST /api/auth/users creates user and returns 201 Created") - void shouldCreateUserSuccessfully() throws Exception { - User createdUser = User.builder() - .username("nam.le") - .fullName("Lê Hoàng Nam") - .email("nam.le@cruise.com") - .role(Role.PASSENGER) - .cabinNumber("Cabin 505") - .rfidTag("RFID-88102") - .active(true) - .build(); - createdUser.setId(1L); - - when(userService.registerUser(any(User.class))).thenReturn(createdUser); - - String jsonPayload = """ - { - "username": "nam.le", - "fullName": "Lê Hoàng Nam", - "email": "nam.le@cruise.com", - "role": "PASSENGER", - "cabinNumber": "Cabin 505", - "rfidTag": "RFID-88102" - } - """; - - mockMvc.perform(post("/api/auth/users") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonPayload)) - .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print()) - .andExpect(status().isCreated()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.message").value("User created successfully")) - .andExpect(jsonPath("$.data.username").value("nam.le")) - .andExpect(jsonPath("$.data.fullName").value("Lê Hoàng Nam")) - .andExpect(jsonPath("$.data.role").value("PASSENGER")); - } - - @Test - @DisplayName("POST /api/auth/users returns 400 Bad Request when username exists") - void shouldReturnBadRequestWhenUsernameExists() throws Exception { - when(userService.registerUser(any(User.class))) - .thenThrow(new IllegalArgumentException("Username already exists: nam.le")); - - String jsonPayload = """ - { - "username": "nam.le", - "fullName": "Lê Hoàng Nam", - "email": "nam.le@cruise.com", - "role": "PASSENGER" - } - """; - - mockMvc.perform(post("/api/auth/users") - .contentType(MediaType.APPLICATION_JSON) - .content(jsonPayload)) - .andExpect(status().isBadRequest()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Username already exists: nam.le")); - } - - @Test - @DisplayName("GET /api/auth/users/{username} returns 200 OK when user exists") - void shouldGetUserByUsername() throws Exception { - User user = User.builder() - .username("nam.le") - .fullName("Lê Hoàng Nam") - .email("nam.le@cruise.com") - .role(Role.PASSENGER) - .build(); - user.setId(1L); - - when(userService.getUserByUsername("nam.le")).thenReturn(Optional.of(user)); - - mockMvc.perform(get("/api/auth/users/nam.le").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.data.username").value("nam.le")) - .andExpect(jsonPath("$.data.email").value("nam.le@cruise.com")); - } - - @Test - @DisplayName("GET /api/auth/users/{username} returns 404 Not Found when user does not exist") - void shouldReturnNotFoundWhenUserDoesNotExist() throws Exception { - when(userService.getUserByUsername("unknown.user")).thenReturn(Optional.empty()); - - mockMvc.perform(get("/api/auth/users/unknown.user").accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isNotFound()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("User not found: unknown.user")); - } - - @Test - @DisplayName("Direct test for handleIllegalArgument exception handler") - void shouldHandleIllegalArgumentDirectly() { - UserController controller = new UserController(userService); - org.springframework.http.ResponseEntity> response = - controller.handleIllegalArgument(new IllegalArgumentException("Custom bad request message")); - org.junit.jupiter.api.Assertions.assertEquals( - org.springframework.http.HttpStatus.BAD_REQUEST, response.getStatusCode()); - org.junit.jupiter.api.Assertions.assertEquals( - "Custom bad request message", response.getBody().getMessage()); - } - - @Test - @DisplayName("DELETE /api/auth/users/{username} returns 401 Unauthorized when Authorization header is missing") - void shouldReturnUnauthorizedWhenDeleteUserWithoutToken() throws Exception { - mockMvc.perform(delete("/api/auth/users/testuser")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Missing or invalid Authorization header")); - } - - @Test - @DisplayName("DELETE /api/auth/users/{username} returns 401 Unauthorized when token is invalid") - void shouldReturnUnauthorizedWhenDeleteUserWithInvalidToken() throws Exception { - when(jwtService.validateToken("bad-token")).thenReturn(false); - - mockMvc.perform(delete("/api/auth/users/testuser") - .header("Authorization", "Bearer bad-token")) - .andExpect(status().isUnauthorized()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Invalid or expired authentication token")); - org.mockito.Mockito.verify(userService, org.mockito.Mockito.never()).deleteUserByUsername("testuser"); - } - - @Test - @DisplayName("DELETE /api/auth/users/{username} returns 403 Forbidden when caller is not an administrator") - void shouldReturnForbiddenWhenDeleteUserNonAdmin() throws Exception { - when(jwtService.validateToken("staff-token")).thenReturn(true); - when(jwtService.extractRole("staff-token")).thenReturn("STAFF"); - - mockMvc.perform(delete("/api/auth/users/testuser") - .header("Authorization", "Bearer staff-token")) - .andExpect(status().isForbidden()) - .andExpect(jsonPath("$.success").value(false)) - .andExpect(jsonPath("$.message").value("Access denied: Administrator privileges required")); - org.mockito.Mockito.verify(userService, org.mockito.Mockito.never()).deleteUserByUsername("testuser"); - } - - @Test - @DisplayName("DELETE /api/auth/users/{username} returns 200 OK when caller is ADMIN") - void shouldDeleteUserSuccessfullyWhenAdmin() throws Exception { - when(jwtService.validateToken("admin-token")).thenReturn(true); - when(jwtService.extractRole("admin-token")).thenReturn("ADMIN"); - - mockMvc.perform(delete("/api/auth/users/testuser") - .header("Authorization", "Bearer admin-token")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.success").value(true)) - .andExpect(jsonPath("$.message").value("User deleted successfully")); - org.mockito.Mockito.verify(userService).deleteUserByUsername("testuser"); - } -} +package com.cruise.auth.controller; + +import com.cruise.auth.entity.User; +import com.cruise.auth.service.UserService; +import com.cruise.common.enums.Role; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@WebMvcTest(UserController.class) +@DisplayName("UserController MockMvc Web Layer Tests") +class UserControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockitoBean + private UserService userService; + + @MockitoBean + private com.cruise.auth.service.JwtService jwtService; + + @Test + @DisplayName("POST /api/auth/users creates user and returns 201 Created") + void shouldCreateUserSuccessfully() throws Exception { + User createdUser = User.builder() + .username("nam.le") + .fullName("Lê Hoàng Nam") + .email("nam.le@cruise.com") + .role(Role.PASSENGER) + .cabinNumber("Cabin 505") + .rfidTag("RFID-88102") + .active(true) + .build(); + createdUser.setId(1L); + + when(userService.registerUser(any(User.class))).thenReturn(createdUser); + + String jsonPayload = """ + { + "username": "nam.le", + "fullName": "Lê Hoàng Nam", + "email": "nam.le@cruise.com", + "role": "PASSENGER", + "cabinNumber": "Cabin 505", + "rfidTag": "RFID-88102" + } + """; + + mockMvc.perform(post("/api/auth/users") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonPayload)) + .andDo(org.springframework.test.web.servlet.result.MockMvcResultHandlers.print()) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.message").value("User created successfully")) + .andExpect(jsonPath("$.data.username").value("nam.le")) + .andExpect(jsonPath("$.data.fullName").value("Lê Hoàng Nam")) + .andExpect(jsonPath("$.data.role").value("PASSENGER")); + } + + @Test + @DisplayName("POST /api/auth/users returns 400 Bad Request when username exists") + void shouldReturnBadRequestWhenUsernameExists() throws Exception { + when(userService.registerUser(any(User.class))) + .thenThrow(new IllegalArgumentException("Username already exists: nam.le")); + + String jsonPayload = """ + { + "username": "nam.le", + "fullName": "Lê Hoàng Nam", + "email": "nam.le@cruise.com", + "role": "PASSENGER" + } + """; + + mockMvc.perform(post("/api/auth/users") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonPayload)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Username already exists: nam.le")); + } + + @Test + @DisplayName("GET /api/auth/users/{username} returns 200 OK when user exists") + void shouldGetUserByUsername() throws Exception { + User user = User.builder() + .username("nam.le") + .fullName("Lê Hoàng Nam") + .email("nam.le@cruise.com") + .role(Role.PASSENGER) + .build(); + user.setId(1L); + + when(userService.getUserByUsername("nam.le")).thenReturn(Optional.of(user)); + + mockMvc.perform(get("/api/auth/users/nam.le").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.data.username").value("nam.le")) + .andExpect(jsonPath("$.data.email").value("nam.le@cruise.com")); + } + + @Test + @DisplayName("GET /api/auth/users/{username} returns 404 Not Found when user does not exist") + void shouldReturnNotFoundWhenUserDoesNotExist() throws Exception { + when(userService.getUserByUsername("unknown.user")).thenReturn(Optional.empty()); + + mockMvc.perform(get("/api/auth/users/unknown.user").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("User not found: unknown.user")); + } + + @Test + @DisplayName("Direct test for handleIllegalArgument exception handler") + void shouldHandleIllegalArgumentDirectly() { + UserController controller = new UserController(userService); + org.springframework.http.ResponseEntity> response = + controller.handleIllegalArgument(new IllegalArgumentException("Custom bad request message")); + org.junit.jupiter.api.Assertions.assertEquals( + org.springframework.http.HttpStatus.BAD_REQUEST, response.getStatusCode()); + org.junit.jupiter.api.Assertions.assertEquals( + "Custom bad request message", response.getBody().getMessage()); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 401 Unauthorized when Authorization header is missing") + void shouldReturnUnauthorizedWhenDeleteUserWithoutToken() throws Exception { + mockMvc.perform(delete("/api/auth/users/testuser")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Missing or invalid Authorization header")); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 401 Unauthorized when token is invalid") + void shouldReturnUnauthorizedWhenDeleteUserWithInvalidToken() throws Exception { + when(jwtService.validateToken("bad-token")).thenReturn(false); + + mockMvc.perform(delete("/api/auth/users/testuser") + .header("Authorization", "Bearer bad-token")) + .andExpect(status().isUnauthorized()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Invalid or expired authentication token")); + org.mockito.Mockito.verify(userService, org.mockito.Mockito.never()).deleteUserByUsername("testuser"); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 403 Forbidden when caller is not an administrator") + void shouldReturnForbiddenWhenDeleteUserNonAdmin() throws Exception { + when(jwtService.validateToken("staff-token")).thenReturn(true); + when(jwtService.extractRole("staff-token")).thenReturn("STAFF"); + + mockMvc.perform(delete("/api/auth/users/testuser") + .header("Authorization", "Bearer staff-token")) + .andExpect(status().isForbidden()) + .andExpect(jsonPath("$.success").value(false)) + .andExpect(jsonPath("$.message").value("Access denied: Administrator privileges required")); + org.mockito.Mockito.verify(userService, org.mockito.Mockito.never()).deleteUserByUsername("testuser"); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 200 OK when caller is ADMIN") + void shouldDeleteUserSuccessfullyWhenAdmin() throws Exception { + when(jwtService.validateToken("admin-token")).thenReturn(true); + when(jwtService.extractRole("admin-token")).thenReturn("ADMIN"); + + mockMvc.perform(delete("/api/auth/users/testuser") + .header("Authorization", "Bearer admin-token")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").value(true)) + .andExpect(jsonPath("$.message").value("User deleted successfully")); + org.mockito.Mockito.verify(userService).deleteUserByUsername("testuser"); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 200 OK when caller has ROLE_ prefix or other admin roles") + void shouldDeleteUserSuccessfullyWithRolePrefixAndSystemAdmin() throws Exception { + when(jwtService.validateToken("role-admin-token")).thenReturn(true); + when(jwtService.extractRole("role-admin-token")).thenReturn("ROLE_ADMIN"); + + mockMvc.perform(delete("/api/auth/users/testuser1") + .header("Authorization", "Bearer role-admin-token")) + .andExpect(status().isOk()); + + when(jwtService.validateToken("sysadmin-token")).thenReturn(true); + when(jwtService.extractRole("sysadmin-token")).thenReturn("SYSTEM_ADMIN"); + + mockMvc.perform(delete("/api/auth/users/testuser2") + .header("Authorization", "Bearer sysadmin-token")) + .andExpect(status().isOk()); + + when(jwtService.validateToken("ops-token")).thenReturn(true); + when(jwtService.extractRole("ops-token")).thenReturn("OPERATIONS_MANAGER"); + + mockMvc.perform(delete("/api/auth/users/testuser3") + .header("Authorization", "Bearer ops-token")) + .andExpect(status().isOk()); + } + + @Test + @DisplayName("DELETE /api/auth/users/{username} returns 403 Forbidden when extracted role is null") + void shouldReturnForbiddenWhenRoleIsNull() throws Exception { + when(jwtService.validateToken("null-role-token")).thenReturn(true); + when(jwtService.extractRole("null-role-token")).thenReturn(null); + + mockMvc.perform(delete("/api/auth/users/testuser") + .header("Authorization", "Bearer null-role-token")) + .andExpect(status().isForbidden()); + } +} diff --git a/cruise-auth-service/src/test/java/com/cruise/auth/dto/VerifyPasswordRequestTest.java b/cruise-auth-service/src/test/java/com/cruise/auth/dto/VerifyPasswordRequestTest.java new file mode 100644 index 00000000..eb229fdc --- /dev/null +++ b/cruise-auth-service/src/test/java/com/cruise/auth/dto/VerifyPasswordRequestTest.java @@ -0,0 +1,33 @@ +package com.cruise.auth.dto; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@DisplayName("VerifyPasswordRequest DTO Unit Tests") +class VerifyPasswordRequestTest { + + @Test + @DisplayName("VerifyPasswordRequest getters, setters, builder, and constructors") + void testDtoMethods() { + VerifyPasswordRequest request = VerifyPasswordRequest.builder() + .usernameOrEmail("admin") + .password("Password123@") + .build(); + + assertEquals("admin", request.getUsernameOrEmail()); + assertEquals("Password123@", request.getPassword()); + + VerifyPasswordRequest noArg = new VerifyPasswordRequest(); + noArg.setUsernameOrEmail("user@cruise.com"); + noArg.setPassword("Secret123"); + + assertEquals("user@cruise.com", noArg.getUsernameOrEmail()); + assertEquals("Secret123", noArg.getPassword()); + + VerifyPasswordRequest allArg = new VerifyPasswordRequest("testuser", "Pass456"); + assertEquals("testuser", allArg.getUsernameOrEmail()); + assertEquals("Pass456", allArg.getPassword()); + } +} From e9f2e51f8c1ef6e1709da3e03188bcff4ba960ed Mon Sep 17 00:00:00 2001 From: huytran2005 Date: Mon, 2 Nov 2026 21:46:24 +0700 Subject: [PATCH 3/3] [KAN-701] fix(auth,pos): add alias tests and synchronize open shift transaction completion --- .../auth/controller/AuthControllerTest.java | 28 +++++++++ .../cruise/pos/service/PosShiftService.java | 61 ++++++++++++------- 2 files changed, 68 insertions(+), 21 deletions(-) diff --git a/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java b/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java index 43cde223..11cae216 100644 --- a/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java +++ b/cruise-auth-service/src/test/java/com/cruise/auth/controller/AuthControllerTest.java @@ -273,6 +273,34 @@ void testVerifyPasswordEndpoint_WithAliasFields() throws Exception { .andExpect(jsonPath("$.data.valid").value(true)); } + @Test + @DisplayName("POST /api/auth/verify-password with email alias returns 200 OK") + void testVerifyPasswordEndpoint_WithEmailAlias() throws Exception { + when(authService.verifyPassword(any(VerifyPasswordRequest.class))).thenReturn(true); + + String jsonBody = "{\"email\":\"admin@cruise.com\",\"password\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/verify-password") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)); + } + + @Test + @DisplayName("POST /api/auth/verify-password with rawPassword alias returns 200 OK") + void testVerifyPasswordEndpoint_WithRawPasswordAlias() throws Exception { + when(authService.verifyPassword(any(VerifyPasswordRequest.class))).thenReturn(true); + + String jsonBody = "{\"usernameOrEmail\":\"admin\",\"rawPassword\":\"Admin@1234\"}"; + + mockMvc.perform(post("/api/auth/verify-password") + .contentType(MediaType.APPLICATION_JSON) + .content(jsonBody)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.valid").value(true)); + } + @Test @DisplayName("POST /api/auth/token/pair returns 200 OK with new TokenPair for authenticated user") void testIssueTokenPairEndpoint() throws Exception { diff --git a/cruise-pos-service/src/main/java/com/cruise/pos/service/PosShiftService.java b/cruise-pos-service/src/main/java/com/cruise/pos/service/PosShiftService.java index e843144b..31022ee5 100644 --- a/cruise-pos-service/src/main/java/com/cruise/pos/service/PosShiftService.java +++ b/cruise-pos-service/src/main/java/com/cruise/pos/service/PosShiftService.java @@ -15,6 +15,8 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionSynchronization; import java.math.BigDecimal; import java.time.Instant; @@ -24,6 +26,7 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.ReentrantLock; import org.springframework.dao.DataIntegrityViolationException; @Service @@ -33,9 +36,10 @@ public class PosShiftService { private final PosShiftRepository shiftRepository; private final PosTransactionRepository transactionRepository; - private final ConcurrentMap stationLocks = new ConcurrentHashMap<>(); + private final ConcurrentMap stationLocks = new ConcurrentHashMap<>(); @Transactional + @SuppressWarnings("java:S2222") public PosShift openShift(String stationId, String cashierId, BigDecimal startingCash) { if (stationId == null || stationId.isBlank()) { throw new BusinessRuleException("stationId không được để trống khi mở ca làm việc"); @@ -46,31 +50,46 @@ public PosShift openShift(String stationId, String cashierId, BigDecimal startin return existing.get(); } - Object lock = stationLocks.computeIfAbsent(stationId, k -> new Object()); - synchronized (lock) { + ReentrantLock lock = stationLocks.computeIfAbsent(stationId, k -> new ReentrantLock()); + boolean locked = true; + lock.lock(); + + try { existing = shiftRepository.findByStationIdAndStatus(stationId, ShiftStatus.OPEN); if (existing.isPresent()) { + lock.unlock(); + locked = false; return existing.get(); } - try { - PosShift shift = PosShift.builder() - .stationId(stationId) - .cashierId(cashierId) - .startingCash(startingCash != null ? startingCash : BigDecimal.ZERO) - .status(ShiftStatus.OPEN) - .openedAt(Instant.now()) - .totalSales(BigDecimal.ZERO) - .totalRefunds(BigDecimal.ZERO) - .netRevenue(BigDecimal.ZERO) - .transactionCount(0) - .build(); - - return shiftRepository.save(shift); - } catch (DataIntegrityViolationException dive) { - log.warn("Concurrent shift creation detected for station {}: {}", stationId, dive.getMessage()); - return shiftRepository.findByStationIdAndStatus(stationId, ShiftStatus.OPEN) - .orElseThrow(() -> new BusinessRuleException("Không thể tạo ca làm việc do xung đột trạm POS: " + stationId)); + PosShift shift = PosShift.builder() + .stationId(stationId) + .cashierId(cashierId) + .startingCash(startingCash != null ? startingCash : BigDecimal.ZERO) + .status(ShiftStatus.OPEN) + .openedAt(Instant.now()) + .totalSales(BigDecimal.ZERO) + .totalRefunds(BigDecimal.ZERO) + .netRevenue(BigDecimal.ZERO) + .transactionCount(0) + .build(); + + shift = shiftRepository.save(shift); + + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { + @Override + public void afterCompletion(int status) { + lock.unlock(); + } + }); + locked = false; + } + + return shift; + } finally { + if (locked) { + lock.unlock(); } } }