feat: admin-set passwords for staff, and a secure temporary-password generator
Creating a user takes the first password from the admin, and a new
POST /api/admin/users/{id}/password lets an admin set a temporary password
for another active user. Both store the bcrypt hash with login = N, so the
user must choose their own password at the next sign-in. No email is sent.
The password must match its confirmation and pass the admin password rules.
The emailed-password generator now draws from SecureRandom.
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
b49c9f1bc3
commit
2c0a847b68
12 files changed
+386
-15
No files matched your search
+2
@@ -23,6 +23,8 @@ public class RestApiSystemServiceConstants {
|
||||
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_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_USER_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin";
|
||||
public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember";
|
||||
|
||||
|
||||
+7
@@ -54,4 +54,11 @@ public class AdminUserController {
|
||||
public ResponseEntity<Map<String, Object>> resetPassword(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id)));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PostMapping("/users/{id}/password")
|
||||
public ResponseEntity<Void> setPassword(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
adminUserService.setTemporaryPassword(id, body.get("password"), body.get("confirmPassword"));
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -4,7 +4,22 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Fields an admin may set. Username, type, company and password are deliberately absent: the portal's extra fields are ignored. */
|
||||
/**
|
||||
* Fields an admin may set. Type and company are deliberately absent: the portal's extra fields are ignored.
|
||||
* The password pair is read on create only; updates never change a password.
|
||||
*/
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
|
||||
List<AdminRoleRef> roles) {}
|
||||
List<AdminRoleRef> roles, String password, String confirmPassword) {
|
||||
|
||||
/** An update request: no password. */
|
||||
public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, List<AdminRoleRef> roles) {
|
||||
this(name, surname, username, email, enabled, roles, null, null);
|
||||
}
|
||||
|
||||
/** Never print the password pair. */
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AdminUserRequest[username=" + username + ", email=" + email + ", enabled=" + enabled + ", roles=" + roles + "]";
|
||||
}
|
||||
}
|
||||
+17
@@ -10,6 +10,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@@ -41,6 +42,22 @@ public class AdminAuthenticationService {
|
||||
return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody());
|
||||
}
|
||||
|
||||
/** True when the password passes every admin password rule (services-system returns the failing rules). */
|
||||
public boolean passesAdminPasswordRules(String password) {
|
||||
ResponseEntity<List> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_VALIDATE_PASSWORD_RULES),
|
||||
List.class, Map.of("password", password));
|
||||
return ent.getBody() != null && ent.getBody().isEmpty();
|
||||
}
|
||||
|
||||
/** Stores an admin-typed password with a forced change at next login; returns rows updated (0 = refused). */
|
||||
public int setAdminPassword(Long id, String password) {
|
||||
ResponseEntity<Integer> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_ADMIN_SET_PASSWORD),
|
||||
Integer.class, Map.of("id", id, "password", password));
|
||||
return ent.getBody() == null ? 0 : 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(
|
||||
|
||||
+30
-2
@@ -8,6 +8,7 @@ import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -26,6 +27,7 @@ import java.util.Set;
|
||||
* Admin users for the portal. Users travel as maps so fields the core {@link User} lacks (status) survive
|
||||
* the round trip to services-system, whose /user/save is a full-entity save.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminUserService {
|
||||
@@ -81,6 +83,7 @@ public class AdminUserService {
|
||||
|| r.roles() == null || r.roles().isEmpty()) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Name, username, email and at least one role are required", "REQUIRED_FIELD");
|
||||
}
|
||||
requireValidPassword(r.password(), r.confirmPassword());
|
||||
User caller = caller();
|
||||
requireSuperToGrant(caller, r.roles());
|
||||
if (caller.getBranch() == null || caller.getBranch().getId() == null) {
|
||||
@@ -109,8 +112,8 @@ public class AdminUserService {
|
||||
user.put("doneBy", caller.getUsername());
|
||||
user.put("createDate", System.currentTimeMillis());
|
||||
Map<String, Object> saved = save(user);
|
||||
if (adminAuthenticationService.resetAdminPassword(r.username(), r.email()) == 0) {
|
||||
throw error(HttpStatus.BAD_GATEWAY, "User created but the temporary password email was not sent; retry the password reset", "TEMP_PASSWORD_NOT_SENT");
|
||||
if (adminAuthenticationService.setAdminPassword(((Number) saved.get("id")).longValue(), r.password()) == 0) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "User created but the password was not stored; set a temporary password", "SAVE_FAILED");
|
||||
}
|
||||
return clean(saved);
|
||||
}
|
||||
@@ -152,6 +155,31 @@ public class AdminUserService {
|
||||
return user;
|
||||
}
|
||||
|
||||
/** An admin-typed temporary password for another active user; the user must change it at next login. */
|
||||
public void setTemporaryPassword(Long id, String password, String confirmPassword) {
|
||||
User caller = caller();
|
||||
if (caller.getId() != null && caller.getId().equals(id)) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "You cannot set a temporary password for your own account", "SELF_NOT_ALLOWED");
|
||||
}
|
||||
Map<String, Object> user = loadManaged(id, caller);
|
||||
if (!Boolean.TRUE.equals(user.get("enabled"))) {
|
||||
throw error(HttpStatus.CONFLICT, "The user is deactivated", "USER_DISABLED");
|
||||
}
|
||||
requireValidPassword(password, confirmPassword);
|
||||
if (adminAuthenticationService.setAdminPassword(id, password) == 0) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "The password was not stored", "SAVE_FAILED");
|
||||
}
|
||||
log.info("temporary password set by {} for user {}", caller.getUsername(), id);
|
||||
}
|
||||
|
||||
private void requireValidPassword(String password, String confirmPassword) {
|
||||
if (!StringUtils.hasText(password)) throw error(HttpStatus.BAD_REQUEST, "Password is required", "REQUIRED_FIELD");
|
||||
if (!password.equals(confirmPassword)) throw error(HttpStatus.BAD_REQUEST, "Passwords do not match", "PASSWORD_MISMATCH");
|
||||
if (!adminAuthenticationService.passesAdminPasswordRules(password)) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "Password does not meet the password policy", "PASSWORD_POLICY");
|
||||
}
|
||||
}
|
||||
|
||||
/** The target admin; a non-super caller may not manage a super admin. */
|
||||
private Map<String, Object> loadManaged(Long id, User caller) {
|
||||
Map<String, Object> user = load(id);
|
||||
|
||||
+8
@@ -105,4 +105,12 @@ class AdminUserControllerTest {
|
||||
.andExpect(status().is4xxClientError());
|
||||
org.mockito.Mockito.verifyNoInteractions(users);
|
||||
}
|
||||
|
||||
@Test
|
||||
void setPassword_passesBothFieldsAndReturns204() throws Exception {
|
||||
mvc.perform(post("/api/admin/users/5/password").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"password\":\"Good#Pass1\",\"confirmPassword\":\"Good#Pass1\"}"))
|
||||
.andExpect(status().isNoContent());
|
||||
verify(users).setTemporaryPassword(5L, "Good#Pass1", "Good#Pass1");
|
||||
}
|
||||
}
|
||||
+23
@@ -64,4 +64,27 @@ class AdminAuthenticationServiceWireTest {
|
||||
assertThat(service.resetAdminPassword("sales1", "a@b.c")).isEqualTo(1);
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesAdminPasswordRules_trueOnlyWhenNoRuleFails() {
|
||||
server.expect(requestTo("http://gw/user/validatePasswordFromRulesForAdmin")).andExpect(method(POST))
|
||||
.andExpect(content().json("{\"password\":\"Good#Pass1\"}"))
|
||||
.andRespond(withSuccess("[]", MediaType.APPLICATION_JSON));
|
||||
server.expect(requestTo("http://gw/user/validatePasswordFromRulesForAdmin")).andExpect(method(POST))
|
||||
.andRespond(withSuccess("[{\"param\":\"INPUT_LENGTH_MIN\"}]", MediaType.APPLICATION_JSON));
|
||||
|
||||
assertThat(service.passesAdminPasswordRules("Good#Pass1")).isTrue();
|
||||
assertThat(service.passesAdminPasswordRules("short")).isFalse();
|
||||
server.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void setAdminPassword_postsIdAndPassword() {
|
||||
server.expect(requestTo("http://gw/user/setAdminPassword")).andExpect(method(POST))
|
||||
.andExpect(content().json("{\"id\":9,\"password\":\"Good#Pass1\"}"))
|
||||
.andRespond(withSuccess("1", MediaType.APPLICATION_JSON));
|
||||
|
||||
assertThat(service.setAdminPassword(9L, "Good#Pass1")).isEqualTo(1);
|
||||
server.verify();
|
||||
}
|
||||
}
|
||||
+111
-8
@@ -143,11 +143,14 @@ class AdminUserServiceTest {
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any()))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
when(auth.resetAdminPassword(anyString(), anyString())).thenReturn(1);
|
||||
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
||||
}
|
||||
|
||||
private static final String PW = "Good#Pass1";
|
||||
|
||||
private AdminUserRequest req(String name, String username, String email, List<AdminRoleRef> roles) {
|
||||
return new AdminUserRequest(name, null, username, email, null, roles);
|
||||
return new AdminUserRequest(name, null, username, email, null, roles, PW, PW);
|
||||
}
|
||||
|
||||
private static final List<AdminRoleRef> ROLES = List.of(new AdminRoleRef(4L, "ROLE_SALES"));
|
||||
@@ -235,10 +238,10 @@ class AdminUserServiceTest {
|
||||
// ---- create ----
|
||||
|
||||
@Test
|
||||
void create_savesActiveAdminWithCallerCompanyThenSendsTemporaryPassword() {
|
||||
void create_savesActiveAdminWithCallerCompanyThenSetsTheTypedPassword() {
|
||||
stubNoDuplicates();
|
||||
stubSave(row(20, "New", "newbie", "n@x.com", true, "ROLE_SALES"));
|
||||
AdminUserRequest r = new AdminUserRequest("New", "Guy", "newbie", "n@x.com", false, ROLES);
|
||||
AdminUserRequest r = new AdminUserRequest("New", "Guy", "newbie", "n@x.com", false, ROLES, PW, PW);
|
||||
|
||||
Map<String, Object> out = service.create(r);
|
||||
|
||||
@@ -252,7 +255,8 @@ class AdminUserServiceTest {
|
||||
assertThat(saved).doesNotContainKey("id").doesNotContainKey("password");
|
||||
assertThat((Map<String, Object>) saved.get("branch")).containsEntry("id", 3L);
|
||||
assertThat(((List<Map<String, Object>>) saved.get("roles")).get(0)).containsEntry("id", 4L);
|
||||
verify(auth).resetAdminPassword("newbie", "n@x.com");
|
||||
verify(auth).setAdminPassword(20L, PW);
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
assertThat(out).containsEntry("id", 20L).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm");
|
||||
}
|
||||
|
||||
@@ -264,6 +268,7 @@ class AdminUserServiceTest {
|
||||
assertCoded(() -> service.create(req("N", "dup", "n@x.com", ROLES)), HttpStatus.CONFLICT, "USERNAME_TAKEN");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -295,12 +300,29 @@ class AdminUserServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_tempPasswordNotSent_is502AfterUserCreated() {
|
||||
void create_passwordNotStored_isSaveFailedAfterUserCreated() {
|
||||
stubNoDuplicates();
|
||||
stubSave(row(20, "N", "u", "e@x.com", true, "R"));
|
||||
when(auth.resetAdminPassword("u", "e@x.com")).thenReturn(0);
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_GATEWAY, "TEMP_PASSWORD_NOT_SENT");
|
||||
when(auth.setAdminPassword(20L, PW)).thenReturn(0);
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED");
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_missingMismatchedOrWeakPassword_isRefusedBeforeSaving() {
|
||||
stubNoDuplicates();
|
||||
assertCoded(() -> service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, ROLES, null, null)),
|
||||
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, ROLES, " ", " ")),
|
||||
HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, ROLES, PW, PW + "x")),
|
||||
HttpStatus.BAD_REQUEST, "PASSWORD_MISMATCH");
|
||||
when(auth.passesAdminPasswordRules("weak")).thenReturn(false);
|
||||
assertCoded(() -> service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, ROLES, "weak", "weak")),
|
||||
HttpStatus.BAD_REQUEST, "PASSWORD_POLICY");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -625,4 +647,85 @@ class AdminUserServiceTest {
|
||||
}
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
// ---- admin-set temporary password ----
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_storesItForAnActiveUser() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "sales1", "a@x.com", true, "R"));
|
||||
service.setTemporaryPassword(5L, PW, PW);
|
||||
verify(auth).setAdminPassword(5L, PW);
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_ownAccount_is400() {
|
||||
stubNoDuplicates();
|
||||
stubFind(1, row(1, "Boss", "boss", "b@x.com", true, "R"));
|
||||
assertCoded(() -> service.setTemporaryPassword(1L, PW, PW), HttpStatus.BAD_REQUEST, "SELF_NOT_ALLOWED");
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_superAdminTargetByNonSuperCaller_is403() {
|
||||
stubNoDuplicates();
|
||||
stubFind(6, superAdminRow(6));
|
||||
assertCoded(() -> service.setTemporaryPassword(6L, PW, PW), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_disabledUser_is409() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "sales2", "a@x.com", false, "R"));
|
||||
assertCoded(() -> service.setTemporaryPassword(5L, PW, PW), HttpStatus.CONFLICT, "USER_DISABLED");
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_unknownUser_is404() {
|
||||
stubNoDuplicates();
|
||||
when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok().build());
|
||||
assertThatThrownBy(() -> service.setTemporaryPassword(9L, PW, PW)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_mismatchedOrWeak_isRefused() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "sales1", "a@x.com", true, "R"));
|
||||
assertCoded(() -> service.setTemporaryPassword(5L, PW, "other"), HttpStatus.BAD_REQUEST, "PASSWORD_MISMATCH");
|
||||
assertCoded(() -> service.setTemporaryPassword(5L, null, null), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
when(auth.passesAdminPasswordRules("weak")).thenReturn(false);
|
||||
assertCoded(() -> service.setTemporaryPassword(5L, "weak", "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_POLICY");
|
||||
verify(auth, never()).setAdminPassword(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_notStored_isSaveFailed() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "sales1", "a@x.com", true, "R"));
|
||||
when(auth.setAdminPassword(5L, PW)).thenReturn(0);
|
||||
assertCoded(() -> service.setTemporaryPassword(5L, PW, PW), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void setTemporaryPassword_auditLogNeverContainsThePassword() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "sales1", "a@x.com", true, "R"));
|
||||
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) org.slf4j.LoggerFactory.getLogger(AdminUserService.class);
|
||||
ch.qos.logback.core.read.ListAppender<ch.qos.logback.classic.spi.ILoggingEvent> appender = new ch.qos.logback.core.read.ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
service.setTemporaryPassword(5L, PW, PW);
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
}
|
||||
assertThat(appender.list).extracting(ch.qos.logback.classic.spi.ILoggingEvent::getFormattedMessage)
|
||||
.anySatisfy(m -> assertThat(m).contains("temporary password set by boss for user 5"))
|
||||
.allSatisfy(m -> assertThat(m).doesNotContain(PW));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user