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:
1 parent
1bfc1c73c6
commit
9f22837a00
14 files changed
+567
-2
No files matched your search
+253
@@ -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("{}"));
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
import org.springframework.test.web.client.MockRestServiceServer;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.http.HttpMethod.POST;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
|
||||
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
|
||||
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
|
||||
|
||||
class AdminAuthenticationServiceWireTest {
|
||||
|
||||
private MockRestServiceServer server;
|
||||
private AdminAuthenticationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
server = MockRestServiceServer.bindTo(restTemplate).build();
|
||||
RestTemplateCustomUtil util = new RestTemplateCustomUtil(restTemplate);
|
||||
ReflectionTestUtils.setField(util, "apiUrl", "http://gw");
|
||||
ReflectionTestUtils.setField(util, "apiKey", "k");
|
||||
service = new AdminAuthenticationService(util);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getToken_postsToAdminAuthenticate_emptyBodyIsNull() {
|
||||
server.expect(requestTo("http://gw/auth/authenticate")).andExpect(method(POST))
|
||||
.andExpect(content().json("{\"username\":\"admin\",\"password\":\"pw\"}"))
|
||||
.andRespond(withSuccess("", MediaType.TEXT_PLAIN));
|
||||
AuthRequest r = new AuthRequest();
|
||||
r.setUsername("admin");
|
||||
r.setPassword("pw");
|
||||
|
||||
assertThat(service.getToken(r)).isNullOrEmpty();
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstTimeLogin_postsUserIdAndBothPasswordsToAdminEndpoint() {
|
||||
server.expect(requestTo("http://gw/user/firstTimeLogin")).andExpect(method(POST))
|
||||
.andExpect(content().json("{\"userId\":9,\"newPassword\":\"New#Pass1\",\"repeatPassword\":\"New#Pass1\"}"))
|
||||
.andRespond(withSuccess("true", MediaType.APPLICATION_JSON));
|
||||
|
||||
assertThat(service.firstTimeLogin(9L, "New#Pass1")).isTrue();
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resetAdminPassword_postsUsernameAndEmail() {
|
||||
server.expect(requestTo("http://gw/user/resetAdminPassword")).andExpect(method(POST))
|
||||
.andExpect(content().json("{\"username\":\"sales1\",\"email\":\"a@b.c\"}"))
|
||||
.andRespond(withSuccess("1", MediaType.APPLICATION_JSON));
|
||||
|
||||
assertThat(service.resetAdminPassword("sales1", "a@b.c")).isEqualTo(1);
|
||||
server.verify();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user