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

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