feat(mobile-api): admin login, first-login, forgot password, logout, refresh and me

Wrong, blank or failed logins all answer the same 401. A deactivated admin is
refused and the token services-auth issued is revoked. resetAdminPassword now
refuses deactivated users and users without an email.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-26 19:55:58 +08:00
1 parent 1bfc1c73c6
commit 9f22837a00
14 files changed
+567 -2

No files matched your search

@@ -0,0 +1,253 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AuthenticationService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class AdminAuthControllerTest {
private static final String LOGIN = "{\"username\":\"admin\",\"password\":\"pw\"}";
private static final String FORGOT = "{\"username\":\"sales1\",\"email\":\"sales1@example.com\"}";
private static final String FORGOT_BODY = "{\"result\":\"true\"}";
@Mock private AdminAuthenticationService auth;
@Mock private AuthenticationService authenticationService;
@InjectMocks private AdminAuthController controller;
private MockMvc mvc;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
}
@AfterEach
void close() { http.close(); }
private User user(boolean enabled, GeneralEnum.LoginStatus login) {
User u = new User();
u.setId(9L);
u.setName("Admin User");
u.setEnabled(enabled);
u.setLogin(login);
u.setRoles(List.of(new Role("ROLE_ADMIN")));
u.setPassword("$2a$secret");
return u;
}
private org.springframework.test.web.servlet.ResultActions login() throws Exception {
return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON).content(LOGIN));
}
@Test
void login_correctCredentials_returnsTokenNameRolesAndResetFlag() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N));
login().andExpect(status().isOk())
.andExpect(jsonPath("$.token").value("tok"))
.andExpect(jsonPath("$.name").value("Admin User"))
.andExpect(jsonPath("$.roles[0].name").value("ROLE_ADMIN"))
.andExpect(jsonPath("$.resetPasswordRequired").value("true"))
.andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("secret"))));
}
@Test
void login_wrongPassword_emptyToken_is401FixedMessage() throws Exception {
when(auth.getToken(any())).thenReturn("");
login().andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Invalid username or password"));
verify(auth, never()).loadUserByToken(anyString());
}
@Test
void login_deactivatedUser_is401SameMessage() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(false, GeneralEnum.LoginStatus.Y));
login().andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Invalid username or password"))
.andExpect(jsonPath("$.token").doesNotExist());
}
@Test
void login_memberAccount_servicesAuthGivesNoToken_is401() throws Exception {
// /auth/authenticate only authenticates type A users; a member gets a 200 with an empty body (null here).
when(auth.getToken(any())).thenReturn(null);
login().andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Invalid username or password"));
}
@Test
void firstLogin_success_setsPasswordForCaller() throws Exception {
when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N));
when(auth.firstTimeLogin(9L, "New#Pass1")).thenReturn(true);
mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON)
.content("{\"newPassword\":\"New#Pass1\"}"))
.andExpect(status().isOk())
.andExpect(content().json("{\"result\":\"true\"}"));
}
@Test
void firstLogin_ruleFailure_is400WithMessage() throws Exception {
when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.N));
when(auth.firstTimeLogin(9L, "weak")).thenReturn(false);
mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON)
.content("{\"newPassword\":\"weak\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message").value("New password does not meet the password policy."));
}
@Test
void firstLogin_alreadyCompleted_is403() throws Exception {
when(auth.loadUserByToken("tok")).thenReturn(user(true, GeneralEnum.LoginStatus.Y));
mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON)
.content("{\"newPassword\":\"New#Pass1\"}"))
.andExpect(status().isForbidden());
verify(auth, never()).firstTimeLogin(any(), any());
}
private org.springframework.test.web.servlet.ResultActions forgot() throws Exception {
return mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON).content(FORGOT));
}
@Test
void forgotPassword_match_is200AndResetCalled() throws Exception {
when(auth.resetAdminPassword("sales1", "sales1@example.com")).thenReturn(1);
forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY));
verify(auth).resetAdminPassword("sales1", "sales1@example.com");
}
@Test
void forgotPassword_noMatch_sameBody() throws Exception {
when(auth.resetAdminPassword(anyString(), anyString())).thenReturn(0);
forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY));
}
@Test
void forgotPassword_downstreamException_sameBody() throws Exception {
when(auth.resetAdminPassword(anyString(), anyString())).thenThrow(new IllegalStateException("npe downstream"));
forgot().andExpect(status().isOk()).andExpect(content().json(FORGOT_BODY));
}
@Test
void logout_callsLogoutToken() throws Exception {
mvc.perform(post("/api/admin/auth/logout")).andExpect(status().isOk());
verify(authenticationService).logoutToken("tok");
}
@Test
void refresh_returnsNewToken() throws Exception {
when(authenticationService.refreshToken("tok")).thenReturn("tok2");
mvc.perform(post("/api/admin/auth/refresh")).andExpect(status().isOk())
.andExpect(jsonPath("$.token").value("tok2"));
}
@Test
void me_returnsNameRolesAndAclMenu() throws Exception {
User u = user(true, GeneralEnum.LoginStatus.Y);
u.setAclMenu(new com.solvway.core.model.Module());
when(auth.loadUserByToken("tok")).thenReturn(u);
mvc.perform(get("/api/admin/me")).andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Admin User"))
.andExpect(jsonPath("$.roles[0].name").value("ROLE_ADMIN"))
.andExpect(jsonPath("$.aclMenu").exists())
.andExpect(jsonPath("$.password").doesNotExist());
}
@Test
void login_blankPassword_is401WithoutCallingUpstream() throws Exception {
mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\"admin\",\"password\":\"\"}"))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Invalid username or password"));
verify(auth, never()).getToken(any());
}
@Test
void login_missingUsername_is401WithoutCallingUpstream() throws Exception {
mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON)
.content("{\"password\":\"pw\"}"))
.andExpect(status().isUnauthorized());
verify(auth, never()).getToken(any());
}
@Test
void login_upstreamServerError_is401SameMessage() throws Exception {
when(auth.getToken(any())).thenThrow(new org.springframework.web.client.HttpServerErrorException(
org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR));
login().andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.message").value("Invalid username or password"));
}
@Test
void login_deactivatedUser_tokenIsLoggedOut() throws Exception {
when(auth.getToken(any())).thenReturn("newtok");
when(auth.loadUserByToken("newtok")).thenReturn(user(false, GeneralEnum.LoginStatus.Y));
login().andExpect(status().isUnauthorized());
verify(authenticationService).logoutToken("newtok");
}
@Test
void firstLogin_unknownToken_is401() throws Exception {
when(auth.loadUserByToken("tok")).thenReturn(null);
mvc.perform(post("/api/admin/auth/first-login").contentType(MediaType.APPLICATION_JSON)
.content("{\"newPassword\":\"N3w-pass!\"}"))
.andExpect(status().isUnauthorized());
verify(auth, never()).firstTimeLogin(any(), any());
}
@Test
void refresh_upstreamDeclines_returnsEmptyObject() throws Exception {
when(authenticationService.refreshToken("tok")).thenReturn(null);
mvc.perform(post("/api/admin/auth/refresh"))
.andExpect(status().isOk())
.andExpect(content().json("{}"));
}
}