feat: company-scoped users and login security, super-admin-only roles, interests and settings

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 20:29:34 +08:00
1 parent 00ce47bc49
commit de2ae63cea
20 files changed
+795 -82

No files matched your search

@@ -8,6 +8,8 @@ public class RestApiSystemServiceConstants {
public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY_AND_ID_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}";
public static final String API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable";
public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll";
public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save";
@@ -35,21 +35,22 @@ public class AdminLoginSecurityController {
@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size));
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size, companyId));
}
@AppAuth
@GetMapping("/locked")
public ResponseEntity<List<Map<String, Object>>> locked() {
return ResponseEntity.ok(loginSecurity.locked());
public ResponseEntity<List<Map<String, Object>>> locked(@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(loginSecurity.locked(companyId));
}
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
@AppAuth
@PostMapping("/locked/{username}/unlock")
public ResponseEntity<Void> unlock(@PathVariable String username) {
loginSecurity.unlock(username);
public ResponseEntity<Void> unlock(@PathVariable String username, @RequestParam(required = false) Long companyId) {
loginSecurity.unlock(username, companyId);
return ResponseEntity.noContent().build();
}
@@ -28,8 +28,9 @@ public class AdminUserController {
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String sortBy,
@RequestParam(required = false) String sortDir) {
return ResponseEntity.ok(adminUserService.list(q != null ? q : searchKey, enabled, page, size, sortBy, sortDir));
@RequestParam(required = false) String sortDir,
@RequestParam(required = false) Long companyId) {
return ResponseEntity.ok(adminUserService.list(q != null ? q : searchKey, enabled, page, size, sortBy, sortDir, companyId));
}
@AppAuth
@@ -5,16 +5,23 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/**
* 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.
* Fields an admin may set. Type is deliberately absent: the portal's extra fields are ignored.
* The password pair, companyId (a super admin's chosen company) and superAdmin (create a company-less super admin)
* are read on create only; updates never change a password or the company.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
List<AdminRoleRef> roles, String password, String confirmPassword) {
List<AdminRoleRef> roles, String password, String confirmPassword,
Long companyId, Boolean superAdmin) {
public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
List<AdminRoleRef> roles, String password, String confirmPassword) {
this(name, surname, username, email, enabled, roles, password, confirmPassword, null, null);
}
/** 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);
this(name, surname, username, email, enabled, roles, null, null, null, null);
}
/** Never print the password pair. */
@@ -45,11 +45,7 @@ public class AdminAclService {
if (moduleIds == null) throw error(HttpStatus.BAD_REQUEST, "moduleIds is required", "REQUIRED_FIELD");
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
boolean isSuper = AdminCompanyScope.isSuper(caller);
if (!isSuper && caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() != ROLE_ADMIN_ID && r.getId().equals(roleId))) {
throw error(HttpStatus.FORBIDDEN, "You cannot change the access of a role you hold", "OWN_ROLE");
}
new AdminCompanyScope().requireSuper(caller);
List<Map<String, Object>> modules = modules();
Set<Long> known = new HashSet<>();
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
@@ -16,7 +17,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/** The company's interest list (tags for leads). Company comes from the logged-in admin, never the request. */
/** The shared interest list (tags for leads): anyone with the module reads it, only a super admin changes it. */
@Service
@RequiredArgsConstructor
public class AdminInterestService {
@@ -26,15 +27,17 @@ public class AdminInterestService {
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
// a field initializer, so Lombok leaves it out of the constructor (the scope holds no state)
private final AdminCompanyScope scope = new AdminCompanyScope();
public List<Map<String, Object>> list() {
return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList();
caller();
return load().stream().map(AdminInterestService::row).toList();
}
public Map<String, Object> create(AdminInterestRequest r) {
User caller = caller();
scope.requireSuper(caller());
Map<String, Object> body = new LinkedHashMap<>();
body.put("companyId", caller.getCompanyId());
body.put("name", checkedName(r.name()));
body.put("active", r.active() == null || r.active());
body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder());
@@ -42,13 +45,12 @@ public class AdminInterestService {
}
public Map<String, Object> update(long id, AdminInterestRequest r) {
User caller = caller();
Map<String, Object> stored = load(caller.getCompanyId()).stream()
scope.requireSuper(caller());
Map<String, Object> stored = load().stream()
.filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst()
.orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null));
Map<String, Object> body = new LinkedHashMap<>();
body.put("id", id);
body.put("companyId", caller.getCompanyId());
body.put("name", r.name() == null ? stored.get("name") : checkedName(r.name()));
body.put("active", r.active() == null ? stored.get("active") : r.active());
body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder());
@@ -63,9 +65,10 @@ public class AdminInterestService {
}
}
private List<Map<String, Object>> load(long companyId) {
// ponytail: the counter ignores the company id (one shared list); 0 is a placeholder for its path variable.
private List<Map<String, Object>> load() {
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, companyId).getBody();
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, 0L).getBody();
return rows == null ? List.of() : rows;
}
@@ -6,6 +6,7 @@ import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AuditChanges;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -35,25 +36,55 @@ public class AdminLoginSecurityService {
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
// a field initializer, so Lombok leaves it out of the constructor (the scope holds no state)
private final AdminCompanyScope scope = new AdminCompanyScope();
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size) {
return audit(username, event, from, to, page, size, null);
}
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size, Long companyId) {
Long company = scope.scope(caller(), companyId);
Map<String, Object> body = new LinkedHashMap<>();
if (StringUtils.hasText(username)) body.put("username", username.trim());
if (StringUtils.hasText(event)) body.put("event", event.trim());
if (StringUtils.hasText(from)) body.put("from", from.trim());
if (StringUtils.hasText(to)) body.put("to", to.trim());
if (company != null) body.put("companyId", company);
body.put("page", page);
body.put("size", size);
return post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_AUDIT, MAP, body);
}
public List<Map<String, Object>> locked() {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
return locked(null);
}
public List<Map<String, Object>> locked(Long companyId) {
Long company = scope.scope(caller(), companyId);
if (company == null) {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
}
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED + "?companyId={companyId}"), LIST, company).getBody();
}
public void unlock(String username) {
String by = callerName();
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, Map.of("username", username, "by", by));
unlock(username, null);
}
public void unlock(String username, Long companyId) {
User caller = caller();
Long company = scope.scope(caller, companyId);
String by = caller.getUsername();
Map<String, Object> body = new LinkedHashMap<>();
body.put("username", username);
body.put("by", by);
if (company != null) body.put("companyId", company);
try {
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, body);
} catch (HttpClientErrorException.NotFound e) {
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
}
log.info("login lock for {} cleared by {}", username, by);
}
@@ -62,6 +93,7 @@ public class AdminLoginSecurityService {
}
public Map<String, Object> saveConfig(Map<String, Object> config) {
scope.requireSuper(caller());
Map<String, Object> before = readOrNull(this::config);
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
if (before != null && saved != null) {
@@ -78,6 +110,7 @@ public class AdminLoginSecurityService {
}
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
scope.requireSuper(caller());
List<Map<String, Object>> before = readOrNull(this::passwordRules);
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
if (before != null && saved != null) {
@@ -132,10 +165,14 @@ public class AdminLoginSecurityService {
return "Invalid request";
}
private String callerName() {
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
return caller.getUsername();
return caller;
}
private String callerName() {
return caller().getUsername();
}
private String url(String api) {
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
@@ -35,6 +36,7 @@ public class AdminRoleService {
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminCompanyScope scope = new AdminCompanyScope();
public List<Map<String, Object>> list() {
return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList();
@@ -54,6 +56,7 @@ public class AdminRoleService {
public Map<String, Object> create(AdminRoleRequest r) {
String name = requireName(r);
User caller = caller();
scope.requireSuper(caller);
requireFree(name, null);
Map<String, Object> role = new HashMap<>();
role.put("name", name);
@@ -67,6 +70,7 @@ public class AdminRoleService {
public Map<String, Object> update(Long id, AdminRoleRequest r) {
User caller = caller();
scope.requireSuper(caller);
Map<String, Object> stored = find(id);
if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE");
String name = requireName(r);
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AuditChanges;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -46,14 +47,24 @@ public class AdminUserService {
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
// a field initializer, so Lombok leaves it out of the constructor (the scope holds no state)
private final AdminCompanyScope scope = new AdminCompanyScope();
/**
* ponytail: services-system findByPropertyAndPageable ignores q, enabled and sorts, so this loads all
* admins (staff-sized) and filters, sorts and pages here. Upgrade: extend that downstream query.
* It is not company-scoped: that must be added before multi-company.
* The company filter is passed down: staff see their own company, a super admin the chosen one or all.
*/
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
Map<String, Object> request = Map.of("property", Map.of("type", "A"),
return list(q, enabled, page, size, sortBy, sortDir, null);
}
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir, Long companyId) {
Long company = scope.scope(caller(), companyId);
Map<String, Object> property = new HashMap<>();
property.put("type", "A");
if (company != null) property.put("companyId", company);
Map<String, Object> request = Map.of("property", property,
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(
url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request);
@@ -70,13 +81,13 @@ public class AdminUserService {
int s = Math.max(size, 1);
int from = (int) Math.min((long) Math.max(page, 0) * s, filtered.size());
List<Map<String, Object>> content = filtered.subList(from, Math.min(from + s, filtered.size())).stream()
.map(AdminUserService::clean).toList();
.map(m -> present(clean(m))).toList();
return Map.of("content", content, "totalElements", (long) filtered.size(),
"totalPages", (filtered.size() + s - 1) / s, "number", Math.max(page, 0), "size", s);
}
public Map<String, Object> findById(Long id) {
return clean(load(id));
return present(clean(load(id, caller())));
}
public Map<String, Object> create(AdminUserRequest r) {
@@ -87,27 +98,40 @@ public class AdminUserService {
requireValidPassword(r.password(), r.confirmPassword());
User caller = caller();
requireSuperToGrant(caller, r.roles());
if (r.username().contains("@")) throw field("Username cannot contain '@'", "INVALID_USERNAME", "username");
boolean hasSuperRole = r.roles().stream().anyMatch(x -> x.id() != null && x.id() == SUPER_ADMIN_ROLE_ID);
Long company;
// Creating users in an inactive company is allowed on purpose: a super admin may prepare users before activating it.
if (Boolean.TRUE.equals(r.superAdmin())) {
scope.requireSuper(caller);
if (!hasSuperRole) throw field("A super admin needs the super admin role", "INVALID_ROLE", "roles");
company = null;
} else {
company = scope.requireCompanyForCreate(caller, r.companyId());
if (hasSuperRole) throw field("The super admin role is only for super admins", "INVALID_ROLE", "roles");
}
if (caller.getBranch() == null || caller.getBranch().getId() == null) {
throw error(HttpStatus.BAD_REQUEST, "Your account has no branch to assign", "BRANCH_REQUIRED");
}
String loginName = company == null ? r.username() : r.username() + "@" + companyCode(company);
// ponytail: check-then-save is not atomic; the DB unique key on username is the backstop.
if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_USERNAME, r.username()) != null) {
if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_USERNAME, loginName) != null) {
throw error(HttpStatus.CONFLICT, "Username is already taken", "USERNAME_TAKEN");
}
if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL, r.email()) != null) {
if (byEmail(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY, company, r.email()) != null) {
throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN");
}
Map<String, Object> user = new HashMap<>();
user.put("name", r.name());
user.put("surname", r.surname());
user.put("username", r.username());
user.put("username", loginName);
user.put("email", r.email());
user.put("roles", roles(r.roles()));
user.put("enabled", true);
user.put("status", "Y");
user.put("type", "A");
user.put("login", "N");
user.put("companyId", caller.getCompanyId());
user.put("companyId", company);
user.put("branch", Map.of("id", caller.getBranch().getId()));
user.put("createBy", caller.getUsername());
user.put("doneBy", caller.getUsername());
@@ -118,7 +142,7 @@ public class AdminUserService {
}
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
AuditChanges.put("enabled", null, true);
return clean(saved);
return present(clean(saved));
}
public Map<String, Object> update(Long id, AdminUserRequest r) {
@@ -126,10 +150,13 @@ public class AdminUserService {
Map<String, Object> user = loadManaged(id, caller);
requireSuperToGrant(caller, r.roles());
requireOwnRolesUnchanged(caller, id, user, r.roles());
if (user.get("companyId") != null && hasSuperRole(r.roles())) {
throw field("The super admin role is only for super admins", "INVALID_ROLE", "roles");
}
if (r.enabled() != null && !r.enabled() && caller.getId() != null && caller.getId().equals(id)) {
throw error(HttpStatus.BAD_REQUEST, "You cannot deactivate your own account", "SELF_DEACTIVATION");
}
if (StringUtils.hasText(r.email()) && get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT, r.email(), id) != null) {
if (StringUtils.hasText(r.email()) && byEmail(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY_AND_ID_NOT, user.get("companyId") instanceof Number n ? Long.valueOf(n.longValue()) : null, r.email(), id) != null) {
throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN");
}
if (r.roles() != null && r.roles().isEmpty()) {
@@ -151,7 +178,7 @@ public class AdminUserService {
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
return clean(saved);
return present(clean(saved));
}
public int resetPassword(Long id) {
@@ -159,9 +186,14 @@ public class AdminUserService {
return adminAuthenticationService.resetAdminPassword((String) user.get("username"), (String) user.get("email"));
}
private Map<String, Object> load(Long id) {
/** Another company's user is a 404 for staff; a super admin may open any. */
private Map<String, Object> load(Long id, User caller) {
Map<String, Object> user = get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID, id);
if (user == null || !"A".equals(user.get("type"))) throw error(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
Long visible = scope.scope(caller, null);
if (user == null || !"A".equals(user.get("type"))
|| visible != null && !visible.equals(user.get("companyId") instanceof Number n ? Long.valueOf(n.longValue()) : null)) {
throw error(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
}
return user;
}
@@ -192,28 +224,24 @@ public class AdminUserService {
/** 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);
Map<String, Object> user = load(id, caller);
// idOf also reads a role services-system sent as a bare id
if (!isSuper(caller) && user.get("roles") instanceof List<?> l && l.stream().anyMatch(
if (!AdminCompanyScope.isSuper(caller) && user.get("roles") instanceof List<?> l && l.stream().anyMatch(
x -> Long.valueOf(SUPER_ADMIN_ROLE_ID).equals(AdminRoleService.idOf(x)))) {
throw superRequired("Only a super admin can manage a super admin");
}
return user;
}
private static boolean isSuper(User caller) {
return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
}
private static void requireSuperToGrant(User caller, List<AdminRoleRef> requested) {
if (!isSuper(caller) && requested != null && requested.stream().anyMatch(r -> r.id() != null && r.id() == SUPER_ADMIN_ROLE_ID)) {
if (!AdminCompanyScope.isSuper(caller) && requested != null && requested.stream().anyMatch(r -> r.id() != null && r.id() == SUPER_ADMIN_ROLE_ID)) {
throw superRequired("Only a super admin can grant the super admin role");
}
}
/** A non-super admin may not change their own roles; hidden roles are not part of what they could change. */
private static void requireOwnRolesUnchanged(User caller, Long id, Map<String, Object> stored, List<AdminRoleRef> requested) {
if (requested == null || isSuper(caller) || caller.getId() == null || !caller.getId().equals(id)) return;
if (requested == null || AdminCompanyScope.isSuper(caller) || caller.getId() == null || !caller.getId().equals(id)) return;
Set<Long> current = new HashSet<>();
if (stored.get("roles") instanceof List<?> l) {
for (Object o : l) {
@@ -225,6 +253,47 @@ public class AdminUserService {
if (!wanted.equals(current)) throw error(HttpStatus.FORBIDDEN, "You cannot change your own roles", "OWN_ROLES");
}
private static boolean hasSuperRole(List<AdminRoleRef> roles) {
return roles != null && roles.stream().anyMatch(x -> x.id() != null && x.id() == SUPER_ADMIN_ROLE_ID);
}
/** services-system finds the user by email within one company (null company = super admins); null when free. */
private Map<String, Object> byEmail(String api, Long companyId, Object... vars) {
if (companyId == null) return get(api, vars);
Object[] all = java.util.Arrays.copyOf(vars, vars.length + 1);
all[vars.length] = companyId;
return get(api + "?companyId={companyId}", all);
}
private String companyCode(Long companyId) {
Map<String, Object> company;
try {
company = get(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID, companyId);
} catch (org.springframework.web.client.HttpClientErrorException.NotFound e) {
company = null;
}
if (company == null || !(company.get("code") instanceof String code) || code.isBlank()) {
throw error(HttpStatus.BAD_REQUEST, "Company not found", "COMPANY_NOT_FOUND");
}
return code;
}
/** The screens show the local part as username and the full sign-in name as loginName. */
private static Map<String, Object> present(Map<String, Object> user) {
if (user.get("username") instanceof String login) {
user.put("loginName", login);
int at = login.indexOf('@');
user.put("username", at < 0 ? login : login.substring(0, at));
}
return user;
}
private static CodedResponseStatusException field(String reason, String code, String field) {
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, reason, code);
e.getBody().setProperty("details", Map.of("field", field));
return e;
}
private static CodedResponseStatusException superRequired(String reason) {
return error(HttpStatus.FORBIDDEN, reason, "SUPER_ADMIN_REQUIRED");
}