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
+1
@@ -7,6 +7,7 @@ public class RestApiAuthServiceConstants {
|
||||
public static final String API_REST_AUTHENTICATION= "/auth/webMemberAuthenticate";
|
||||
public static final String API_REST_AUTHENTICATION_AUTO_LOGIN_UPDATE= "/auth/memberAutoLoginUpdate";
|
||||
public static final String API_REST_AUTHENTICATION_FINGER_PRINT_LOGIN= "/auth/fingerPrintLoginWithToken/{token}/{memberCode}";
|
||||
public static final String API_REST_ADMIN_AUTHENTICATE = "/auth/authenticate";
|
||||
public static final String API_REST_REFRESH_TOKEN = "/auth/refreshToken/{token}";
|
||||
public static final String API_REST_SYSTEM_GET_USER_BYTOKEN = "/auth/findUserByToken/{area}/{token}";
|
||||
public static final String API_REST_LOGOUT_TOKEN= "/auth/logoutToken/{token}";
|
||||
|
||||
+2
@@ -11,6 +11,8 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PASSWORD = "/user/updateMemberPassword";
|
||||
public static final String API_REST_SYSTEM_USER_GET_ENCRYPTED_STRING="/user/getEncryptedStringForPassword";
|
||||
public static final String API_REST_SYSTEM_USER_CHECK_ENCRYPTED_STRING_MATCHED="/user/checkEncryptedStringMatched";
|
||||
public static final String API_REST_SYSTEM_ADMIN_FIRST_TIME_LOGIN = "/user/firstTimeLogin";
|
||||
public static final String API_REST_SYSTEM_ADMIN_RESET_PASSWORD = "/user/resetAdminPassword";
|
||||
public static final String API_REST_SYSTEM_USER_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin";
|
||||
public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember";
|
||||
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminFirstLoginRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLoginResponse;
|
||||
import com.solvway.mobile.api.dto.admin.AdminMeResponse;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Admin login, first-login, forgot-password, logout, refresh and me. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuthController {
|
||||
private static final Map<String, String> BAD_LOGIN =
|
||||
Map.of("result", "false", "message", "Invalid username or password");
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/auth/login")
|
||||
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
|
||||
// Blank fields never reach services-auth: it fails differently for known and unknown usernames.
|
||||
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
|
||||
}
|
||||
String token;
|
||||
User u;
|
||||
try {
|
||||
token = adminAuthenticationService.getToken(request);
|
||||
// services-auth authenticates type A only, so a member account also lands here with no token.
|
||||
u = StringUtils.hasLength(token) ? adminAuthenticationService.loadUserByToken(token) : null;
|
||||
if (u != null && !u.isEnabled()) {
|
||||
// services-auth issues tokens to disabled admins; revoke the one we refuse.
|
||||
authenticationService.logoutToken(token);
|
||||
u = null;
|
||||
}
|
||||
} catch (RestClientException ex) {
|
||||
u = null; // any upstream failure is a refused login; never echo why
|
||||
token = null;
|
||||
}
|
||||
if (u == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
|
||||
}
|
||||
return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(),
|
||||
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false"));
|
||||
}
|
||||
|
||||
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
|
||||
@AppAuth
|
||||
@PostMapping("/auth/first-login")
|
||||
public ResponseEntity<Map<String, String>> firstLogin(@RequestBody AdminFirstLoginRequest request) {
|
||||
User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (u == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
// Only a pending-change user may use this: it sets a password with no current password.
|
||||
if (!GeneralEnum.LoginStatus.N.equals(u.getLogin())) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of("message", "First sign-in is already complete."));
|
||||
}
|
||||
if (!StringUtils.hasLength(request.newPassword())) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", "New password is required."));
|
||||
}
|
||||
if (!adminAuthenticationService.firstTimeLogin(u.getId(), request.newPassword())) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", "New password does not meet the password policy."));
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
/** Always 200 with the same body: the answer must not reveal whether username and email matched. */
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/auth/forgot-password")
|
||||
public ResponseEntity<Map<String, String>> forgotPassword(@RequestBody AdminForgotPasswordRequest request) {
|
||||
try {
|
||||
if (StringUtils.hasText(request.username()) && StringUtils.hasText(request.email())) {
|
||||
adminAuthenticationService.resetAdminPassword(request.username().trim(), request.email().trim());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Admin forgot-password failed downstream: {}", e.getClass().getSimpleName());
|
||||
}
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
|
||||
@AppAuth
|
||||
@PostMapping("/auth/logout")
|
||||
public ResponseEntity<Map<String, String>> logout() {
|
||||
authenticationService.logoutToken(HttpReqRespUtils.getJwtToken());
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
/** Re-issues the caller's token via services-auth; {@code token} is null when upstream declines. */
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@AppAuth
|
||||
@PostMapping("/auth/refresh")
|
||||
public ResponseEntity<Map<String, String>> refresh() {
|
||||
String newToken = authenticationService.refreshToken(HttpReqRespUtils.getJwtToken());
|
||||
return ResponseEntity.ok(newToken == null ? Map.of() : Map.of("token", newToken));
|
||||
}
|
||||
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@AppAuth
|
||||
@GetMapping("/me")
|
||||
public ResponseEntity<AdminMeResponse> me() {
|
||||
User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (u == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(new AdminMeResponse(u.getName(), u.getRoles(), u.getAclMenu()));
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Body of {@code POST /api/admin/auth/first-login}. */
|
||||
public record AdminFirstLoginRequest(String newPassword) {
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
/** Body of {@code POST /api/admin/auth/forgot-password}. */
|
||||
public record AdminForgotPasswordRequest(String username, String email) {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import com.solvway.core.model.Module;
|
||||
import com.solvway.core.model.Role;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Body of {@code POST /api/admin/auth/login}. Declares no password field on purpose: the upstream user carries hashes. */
|
||||
public record AdminLoginResponse(String token, String name, List<Role> roles, Module aclMenu, String resetPasswordRequired) {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import com.solvway.core.model.Module;
|
||||
import com.solvway.core.model.Role;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Body of {@code GET /api/admin/me}. No token or password fields. */
|
||||
public record AdminMeResponse(String name, List<Role> roles, Module aclMenu) {
|
||||
}
|
||||
+28
@@ -2,12 +2,16 @@ package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminAuthenticationService {
|
||||
@@ -20,4 +24,28 @@ public class AdminAuthenticationService {
|
||||
User.class, "BO", token);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
/** Token for a type A (admin) user, or null/empty when services-auth rejects the credentials. */
|
||||
public String getToken(AuthRequest authRequest) {
|
||||
ResponseEntity<String> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_ADMIN_AUTHENTICATE),
|
||||
String.class, authRequest);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
/** Sets the first-login password via services-system; false when it breaks the admin password rules. */
|
||||
public boolean firstTimeLogin(Long userId, String newPassword) {
|
||||
ResponseEntity<Boolean> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_FIRST_TIME_LOGIN),
|
||||
Boolean.class, Map.of("userId", userId, "newPassword", newPassword, "repeatPassword", newPassword));
|
||||
return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody());
|
||||
}
|
||||
|
||||
/** Emails a temporary password when username and email match an admin; returns rows updated (0 = no match). */
|
||||
public int resetAdminPassword(String username, String email) {
|
||||
ResponseEntity<Integer> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_RESET_PASSWORD),
|
||||
Integer.class, Map.of("username", username, "email", email));
|
||||
return ent.getBody() == null ? 0 : ent.getBody();
|
||||
}
|
||||
}
|
||||
+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