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

@@ -290,13 +290,12 @@ public class ValidateUtil {
* Random Password String
* Excluded 1 (one), l (lion) O (capital O), o (small letter O), 0 (zero), I (Ice cream), i ( small letter i) , q (small letter Q) and Q (capital letter Q)
* **/
private static final java.security.SecureRandom PASSWORD_RANDOM = new java.security.SecureRandom();
public String getRandomPasswordString(int length) {
String SALTCHARS = "ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnpqrstuvwyz23456789";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < length) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
salt.append(SALTCHARS.charAt(PASSWORD_RANDOM.nextInt(SALTCHARS.length())));
}
return salt.toString();
}
@@ -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";
@@ -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();
}
}
@@ -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 + "]";
}
}
@@ -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(
@@ -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);
@@ -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");
}
}
@@ -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));
}
}
@@ -380,6 +380,27 @@ public class UserController {
return list.stream().filter(pass -> (pass.validatePasswordRoles(password) != null)).collect(Collectors.toList());
}
@RequestMapping("/validatePasswordFromRulesForAdmin")
public List<PasswordRuleProperty> validatePasswordFromRulesForAdmin(@RequestBody HashMap<String, Object> param) {
return adminPasswordRuleFailures(param.get("password").toString());
}
private List<PasswordRuleProperty> adminPasswordRuleFailures(String password) {
List<PasswordRuleProperty> list = passwordRuleRepository.findByType(SystemPropertyType.ADMIN_PWD_FORMAT.getName());
return list.stream().filter(pass -> (pass.validatePasswordRoles(password) != null)).collect(Collectors.toList());
}
/** Stores an admin-typed password for an enabled admin user with login = N; returns rows updated (0 = refused). Never emails or logs it. */
@RequestMapping("/setAdminPassword")
public int setAdminPassword(@RequestBody HashMap<String, Object> param) {
Long id = Long.parseLong(param.get("id").toString());
String password = param.get("password").toString();
User user = userService.findById(id).orElse(null);
if (user == null || user.getType() != UserType.A || !user.isEnabled()) return 0;
if (!adminPasswordRuleFailures(password).isEmpty()) return 0;
return userService.resetPassword(id, bCryptPasswordEncoder.encode(password), LoginStatus.N);
}
@RequestMapping("/validateSecondaryPasswordFromRulesForMember")
public List<PasswordRuleProperty> validateSecondaryPasswordFromRulesForMember(@RequestBody HashMap<String, Object> param) {
String password = param.get("secondPassword").toString();
@@ -0,0 +1,108 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.constant.SystemConstants.LoginStatus;
import com.solvway.core.enums.UserEnum.UserType;
import com.solvway.services.system.model.PasswordRuleProperty;
import com.solvway.services.system.model.User;
import com.solvway.services.system.repo.PasswordRuleRepository;
import com.solvway.services.system.service.EmailService;
import com.solvway.services.system.service.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** Admin-set passwords: validated against ADMIN_PWD_FORMAT, stored bcrypt-encoded with login = N, never emailed. */
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserControllerSetAdminPasswordTest {
@Mock private UserService userService;
@Mock private EmailService emailService;
@Mock private PasswordRuleRepository passwordRuleRepository;
@Spy private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(4);
@InjectMocks private UserController controller;
@BeforeEach
void minLengthEightRule() {
PasswordRuleProperty rule = new PasswordRuleProperty();
rule.setParam("INPUT_LENGTH_MIN");
rule.setValue("8");
rule.setStatus("Y");
when(passwordRuleRepository.findByType("ADMIN_PWD_FORMAT")).thenReturn(List.of(rule));
when(userService.resetPassword(anyLong(), anyString(), any())).thenReturn(1);
}
private User admin(boolean enabled, UserType type) {
User u = new User();
u.setId(5L);
u.setUsername("sales1");
u.setType(type);
u.setEnabled(enabled);
when(userService.findById(5L)).thenReturn(Optional.of(u));
return u;
}
private static HashMap<String, Object> body(Object id, String password) {
return new HashMap<>(Map.of("id", id, "password", password));
}
@Test
void validateReturnsFailingAdminRules() {
assertThat(controller.validatePasswordFromRulesForAdmin(new HashMap<>(Map.of("password", "short")))).hasSize(1);
assertThat(controller.validatePasswordFromRulesForAdmin(new HashMap<>(Map.of("password", "LongEnough1")))).isEmpty();
}
@Test
void storesBcryptHashWithLoginN() {
admin(true, UserType.A);
int updated = controller.setAdminPassword(body(5, "LongEnough1"));
assertThat(updated).isEqualTo(1);
ArgumentCaptor<String> hash = ArgumentCaptor.forClass(String.class);
verify(userService).resetPassword(eq(5L), hash.capture(), eq(LoginStatus.N));
assertThat(hash.getValue()).isNotEqualTo("LongEnough1");
assertThat(bCryptPasswordEncoder.matches("LongEnough1", hash.getValue())).isTrue();
verify(emailService, never()).send(any());
}
@Test
void refusesDisabledUnknownNonAdminAndWeakPasswords() {
admin(false, UserType.A);
assertThat(controller.setAdminPassword(body(5, "LongEnough1"))).isZero();
admin(true, UserType.M);
assertThat(controller.setAdminPassword(body(5, "LongEnough1"))).isZero();
admin(true, UserType.A);
assertThat(controller.setAdminPassword(body(5, "short"))).isZero();
when(userService.findById(9L)).thenReturn(Optional.empty());
assertThat(controller.setAdminPassword(body(9, "LongEnough1"))).isZero();
verify(userService, never()).resetPassword(anyLong(), anyString(), any());
verify(emailService, never()).send(any());
}
}
@@ -0,0 +1,40 @@
package com.solvway.services.system.util;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.solvway.core.utils.ValidateUtil;
/** The shared temporary-password generator (lives in solvway-core-libs, which has no test setup). */
class ValidateUtilPasswordTest {
private static final String ALPHABET = "ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnpqrstuvwyz23456789";
private final ValidateUtil util = new ValidateUtil();
@Test
void lengthMatchesArgumentAndCharactersComeFromTheAlphabet() {
for (int len : new int[] {1, 8, 12, 32}) {
String p = util.getRandomPasswordString(len);
assertThat(p).hasSize(len);
assertThat(p.chars()).allMatch(c -> ALPHABET.indexOf(c) >= 0);
}
}
@Test
void thousandPasswordsOfTwelveAreDistinct() {
Set<String> seen = new HashSet<>();
for (int i = 0; i < 1000; i++) seen.add(util.getRandomPasswordString(12));
assertThat(seen).hasSize(1000);
}
@Test
void generatorUsesSecureRandom() throws Exception {
// java.util.Random would also pass the tests above; this pins the secure source the spec requires.
var field = ValidateUtil.class.getDeclaredField("PASSWORD_RANDOM");
assertThat(field.getType()).isEqualTo(java.security.SecureRandom.class);
}
}