feat: admin change-password endpoint with lockout on wrong current password
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
39708224ad
commit
6c6734baa3
7 files changed
+277
-1
No files matched your search
@@ -60,7 +60,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, a new login-audit client, constants, tests)
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
|
||||
- [ ] 3.2 `POST /api/admin/auth/change-password` (design decision 7).
|
||||
- [x] 3.2 `POST /api/admin/auth/change-password` (design decision 7).
|
||||
- **Tests first:**
|
||||
- each 400 code;
|
||||
- `CURRENT_PASSWORD_WRONG` records `LOGIN_FAIL`;
|
||||
|
||||
+1
@@ -25,6 +25,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_ADMIN_RESET_PASSWORD = "/user/resetAdminPassword";
|
||||
public static final String API_REST_SYSTEM_ADMIN_VALIDATE_PASSWORD_RULES = "/user/validatePasswordFromRulesForAdmin";
|
||||
public static final String API_REST_SYSTEM_ADMIN_SET_PASSWORD = "/user/setAdminPassword";
|
||||
public static final String API_REST_SYSTEM_ADMIN_CHANGE_PASSWORD = "/user/changeAdminPassword";
|
||||
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";
|
||||
|
||||
|
||||
+42
@@ -4,10 +4,12 @@ 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.AdminChangePasswordRequest;
|
||||
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.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
@@ -96,6 +98,46 @@ public class AdminAuthController {
|
||||
return ResponseEntity.ok(Map.of("result", "true"));
|
||||
}
|
||||
|
||||
/** An admin changes their own password; refused while a first-login change is pending. The token stays valid. */
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@AppAuth
|
||||
@PostMapping("/auth/change-password")
|
||||
public ResponseEntity<Void> changePassword(@RequestBody AdminChangePasswordRequest request) {
|
||||
User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (u == null) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
if (!StringUtils.hasText(request.currentPassword()) || !StringUtils.hasText(request.newPassword())
|
||||
|| !StringUtils.hasText(request.confirmPassword())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Current password, new password and confirmation are required", "REQUIRED_FIELD");
|
||||
}
|
||||
if (!request.newPassword().equals(request.confirmPassword())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Passwords do not match", "PASSWORD_MISMATCH");
|
||||
}
|
||||
if (adminAuthenticationService.isLocked(u.getUsername())) {
|
||||
throw coded(HttpStatus.BAD_REQUEST,
|
||||
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.", "ACCOUNT_LOCKED");
|
||||
}
|
||||
String result = adminAuthenticationService.changeAdminPassword(u.getId(), request.currentPassword(), request.newPassword());
|
||||
switch (result) {
|
||||
case "OK" -> {
|
||||
adminAuthenticationService.record(u.getUsername(), "PASSWORD_CHANGED", null);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
case "CURRENT_PASSWORD_WRONG" -> {
|
||||
adminAuthenticationService.record(u.getUsername(), "LOGIN_FAIL", "change-password");
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Current password is incorrect", "CURRENT_PASSWORD_WRONG");
|
||||
}
|
||||
case "PASSWORD_SAME" -> throw coded(HttpStatus.BAD_REQUEST, "The new password must differ from the current one", "PASSWORD_SAME");
|
||||
case "PASSWORD_POLICY" -> throw coded(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
|
||||
default -> throw coded(HttpStatus.INTERNAL_SERVER_ERROR, "The password was not changed", "SAVE_FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException coded(HttpStatus status, String message, String code) {
|
||||
return new CodedResponseStatusException(status, message, code);
|
||||
}
|
||||
|
||||
/** Always 200 with the same body: the answer must not reveal whether username and email matched. */
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/auth/forgot-password")
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.solvway.mobile.api.dto.admin;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AdminChangePasswordRequest(String currentPassword, String newPassword, String confirmPassword) {
|
||||
|
||||
/** Never print the passwords. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AdminChangePasswordRequest[]";
|
||||
}
|
||||
}
|
||||
+8
@@ -64,6 +64,14 @@ public class AdminAuthenticationService {
|
||||
return ent.getBody() == null ? 0 : ent.getBody();
|
||||
}
|
||||
|
||||
/** Changes an admin's own password; returns OK, NOT_FOUND, CURRENT_PASSWORD_WRONG, PASSWORD_SAME or PASSWORD_POLICY. */
|
||||
public String changeAdminPassword(Long id, String currentPassword, String newPassword) {
|
||||
ResponseEntity<String> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_CHANGE_PASSWORD),
|
||||
String.class, Map.of("id", id, "currentPassword", currentPassword, "newPassword", newPassword));
|
||||
return ent.getBody() == null ? "NOT_FOUND" : 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(
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminChangePasswordRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminAuthControllerChangePasswordTest {
|
||||
|
||||
@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 void caller() {
|
||||
User u = new User();
|
||||
u.setId(9L);
|
||||
u.setUsername("admin.user");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
private ResultActions change(String current, String next, String confirm) throws Exception {
|
||||
String body = "{\"currentPassword\":" + q(current) + ",\"newPassword\":" + q(next)
|
||||
+ ",\"confirmPassword\":" + q(confirm) + "}";
|
||||
return mvc.perform(post("/api/admin/auth/change-password").contentType(MediaType.APPLICATION_JSON).content(body));
|
||||
}
|
||||
|
||||
private static String q(String s) { return s == null ? "null" : "\"" + s + "\""; }
|
||||
|
||||
private void assertCoded(ResultActions r, HttpStatus status, String code, String message) {
|
||||
Exception ex = r.andReturn().getResolvedException();
|
||||
assertThat(ex).isInstanceOf(CodedResponseStatusException.class);
|
||||
CodedResponseStatusException c = (CodedResponseStatusException) ex;
|
||||
assertThat(c.getStatusCode()).isEqualTo(status);
|
||||
assertThat(c.getCode()).isEqualTo(code);
|
||||
assertThat(c.getReason()).isEqualTo(message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullCaller_is401() throws Exception {
|
||||
when(auth.loadUserByToken("tok")).thenReturn(null);
|
||||
change("old", "new", "new").andExpect(status().isUnauthorized());
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankField_is400RequiredField() throws Exception {
|
||||
caller();
|
||||
assertCoded(change("old", " ", "new"), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD",
|
||||
"Current password, new password and confirmation are required");
|
||||
assertCoded(change(null, "new", "new"), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD",
|
||||
"Current password, new password and confirmation are required");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mismatch_is400PasswordMismatch() throws Exception {
|
||||
caller();
|
||||
assertCoded(change("old", "new", "other"), HttpStatus.BAD_REQUEST, "PASSWORD_MISMATCH", "Passwords do not match");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void locked_is400AndServicesSystemNotCalled() throws Exception {
|
||||
caller();
|
||||
when(auth.isLocked("admin.user")).thenReturn(true);
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.BAD_REQUEST, "ACCOUNT_LOCKED",
|
||||
"Too many failed sign-ins. Try again later or ask an administrator to unlock your account.");
|
||||
verify(auth, never()).changeAdminPassword(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void currentPasswordWrong_recordsLoginFailAnd400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("CURRENT_PASSWORD_WRONG");
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.BAD_REQUEST, "CURRENT_PASSWORD_WRONG",
|
||||
"Current password is incorrect");
|
||||
verify(auth).record("admin.user", "LOGIN_FAIL", "change-password");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordSame_is400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "old")).thenReturn("PASSWORD_SAME");
|
||||
assertCoded(change("old", "old", "old"), HttpStatus.BAD_REQUEST, "PASSWORD_SAME",
|
||||
"The new password must differ from the current one");
|
||||
}
|
||||
|
||||
@Test
|
||||
void passwordPolicy_is400() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "weak")).thenReturn("PASSWORD_POLICY");
|
||||
assertCoded(change("old", "weak", "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_POLICY",
|
||||
"Password does not meet the password policy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void notFoundOrUnknown_is500SaveFailed() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("NOT_FOUND");
|
||||
assertCoded(change("old", "new", "new"), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED",
|
||||
"The password was not changed");
|
||||
when(auth.changeAdminPassword(9L, "old", "new2")).thenReturn("???");
|
||||
assertCoded(change("old", "new2", "new2"), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED",
|
||||
"The password was not changed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ok_recordsPasswordChanged_204_andKeepsSession() throws Exception {
|
||||
caller();
|
||||
when(auth.changeAdminPassword(9L, "old", "new")).thenReturn("OK");
|
||||
change("old", "new", "new").andExpect(status().isNoContent());
|
||||
verify(auth).record("admin.user", "PASSWORD_CHANGED", null);
|
||||
verifyNoInteractions(authenticationService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestToString_hidesPasswords() {
|
||||
String s = new AdminChangePasswordRequest("curSecret1", "newSecret2", "confSecret3").toString();
|
||||
assertThat(s).doesNotContain("curSecret1").doesNotContain("newSecret2").doesNotContain("confSecret3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void handler_refusesPendingFirstLogin() throws Exception {
|
||||
AdminModule m = AdminAuthController.class
|
||||
.getMethod("changePassword", AdminChangePasswordRequest.class).getAnnotation(AdminModule.class);
|
||||
assertThat(m.value()).containsExactly(AdminModule.ANY_ADMIN);
|
||||
assertThat(m.allowPendingReset()).isFalse();
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AdminAuthenticationServiceChangePasswordTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
service = new AdminAuthenticationService(rest);
|
||||
when(rest.getURLforApiService("/user/changeAdminPassword")).thenReturn("http://sys/user/changeAdminPassword");
|
||||
}
|
||||
|
||||
@Test
|
||||
void postsIdCurrentAndNewPassword_returnsBody() {
|
||||
Map<String, Object> body = Map.of("id", 9L, "currentPassword", "old", "newPassword", "new");
|
||||
when(rest.postForEntity(eq("http://sys/user/changeAdminPassword"), eq(String.class), eq(body)))
|
||||
.thenReturn(ResponseEntity.ok("OK"));
|
||||
assertThat(service.changeAdminPassword(9L, "old", "new")).isEqualTo("OK");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullBody_isNotFound() {
|
||||
when(rest.postForEntity(any(String.class), eq(String.class), any(Object.class)))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.OK));
|
||||
assertThat(service.changeAdminPassword(9L, "old", "new")).isEqualTo("NOT_FOUND");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user