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:
ngqileandClaude Opus 5.5 committed 2026-11-30 11:19:10 +08:00
1 parent b49c9f1bc3
commit 2c0a847b68
12 files changed
+386 -15

No files matched your search

@@ -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();
}
}
@@ -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));
}
}