feat(mobile-api): admin roles API (list, create, rename, module grants)

Member and ROLE_ADMIN roles are hidden; super admin grants are not editable;
removing your own last BO_ROLES grant is refused. Renaming keeps child roles intact.

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-26 20:48:05 +08:00
1 parent 4d261d20d5
commit a8cdf33a24
11 files changed
+964 -1

No files matched your search

@@ -10,6 +10,10 @@ public class RestApiSystemServiceConstants {
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_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";
public static final String API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA = "/module/findAllByArea/{area}";
public static final String API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE = "/module/addModuleRole/{moduleId}/{roleId}";
public static final String API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE = "/module/deleteModuleRole/{moduleId}/{roleId}";
public static final String API_REST_SYSTEM_USER_SAVE = "/user/save";
public static final String API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD = "/user/updateUserPassword";
public static final String API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME = "/user/findExistByUsername/{username}";
@@ -0,0 +1,61 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.dto.admin.AdminGrantsRequest;
import com.solvway.mobile.api.dto.admin.AdminModuleGrant;
import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
import com.solvway.mobile.api.service.AdminAclService;
import com.solvway.mobile.api.service.AdminRoleService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/** Admin roles and their back-office module grants. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminRoleController {
private final AdminRoleService adminRoleService;
private final AdminAclService adminAclService;
@AppAuth
@AdminModule({"BO_ROLES", "BO_USERS"})
@GetMapping("/roles")
public ResponseEntity<List<Map<String, Object>>> list() {
return ResponseEntity.ok(adminRoleService.list());
}
@AppAuth
@AdminModule({"BO_ROLES", "BO_USERS"})
@GetMapping("/roles/{id}")
public ResponseEntity<Map<String, Object>> getById(@PathVariable Long id) {
return ResponseEntity.ok(adminRoleService.get(id));
}
@AppAuth
@AdminModule("BO_ROLES")
@PostMapping("/roles")
public ResponseEntity<Map<String, Object>> create(@RequestBody AdminRoleRequest request) {
return ResponseEntity.ok(adminRoleService.create(request));
}
@AppAuth
@AdminModule("BO_ROLES")
@PutMapping("/roles/{id}")
public ResponseEntity<Map<String, Object>> update(@PathVariable Long id, @RequestBody AdminRoleRequest request) {
return ResponseEntity.ok(adminRoleService.update(id, request));
}
@AppAuth
@AdminModule("BO_ROLES")
@GetMapping("/roles/{id}/modules")
public ResponseEntity<List<AdminModuleGrant>> getModules(@PathVariable Long id) {
return ResponseEntity.ok(adminAclService.getGrantTree(id));
}
@AppAuth
@AdminModule("BO_ROLES")
@PutMapping("/roles/{id}/modules")
public ResponseEntity<List<AdminModuleGrant>> putModules(@PathVariable Long id, @RequestBody AdminGrantsRequest request) {
return ResponseEntity.ok(adminAclService.updateGrants(id, request.moduleIds()));
}
}
@@ -0,0 +1,8 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminGrantsRequest(List<Long> moduleIds) {}
@@ -0,0 +1,4 @@
package com.solvway.mobile.api.dto.admin;
/** One BO module row of a role's grant tree; the portal builds the checkbox tree from parentId. */
public record AdminModuleGrant(Long id, String name, Long parentId, boolean granted) {}
@@ -0,0 +1,7 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/** Create/rename body. The portal may also send level and parent; the parent is always ROLE_SUPER_ADMIN, so they are ignored. */
@JsonIgnoreProperties(ignoreUnknown = true)
public record AdminRoleRequest(String name) {}
@@ -0,0 +1,106 @@
package com.solvway.mobile.api.service;
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.dto.admin.AdminModuleGrant;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Back-office module grants per role. Reads and writes the BO module tree through services-system. */
@Service
@RequiredArgsConstructor
public class AdminAclService {
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private static final String AREA = "BO";
private static final String ROLES_MODULE = "BO_ROLES";
private static final long SUPER_ADMIN_ROLE_ID = 1L;
private static final long ROLE_ADMIN_ID = 2L;
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminRoleService adminRoleService;
public List<AdminModuleGrant> getGrantTree(Long roleId) {
requireVisibleRole(roleId);
return modules().stream().filter(AdminAclService::isGrantable).map(m -> new AdminModuleGrant(AdminRoleService.idOf(m), (String) m.get("name"),
AdminRoleService.idOf(m.get("parent")), grantedTo(m, roleId))).toList();
}
public List<AdminModuleGrant> updateGrants(Long roleId, List<Long> moduleIds) {
requireVisibleRole(roleId);
if (roleId == SUPER_ADMIN_ROLE_ID || roleId == ROLE_ADMIN_ID) {
throw error(HttpStatus.BAD_REQUEST, "This role's grants cannot be edited", "ROLE_NOT_EDITABLE");
}
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");
List<Map<String, Object>> modules = modules();
Set<Long> known = new HashSet<>();
Set<Long> current = new HashSet<>();
for (Map<String, Object> m : modules) {
if (isGrantable(m)) known.add(AdminRoleService.idOf(m));
if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m));
}
Set<Long> wanted = new HashSet<>(moduleIds);
if (!known.containsAll(wanted)) throw error(HttpStatus.BAD_REQUEST, "Unknown back-office module", "UNKNOWN_MODULE");
requireNoLockout(caller, roleId, wanted, modules);
// ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction.
for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId);
for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId);
return getGrantTree(roleId);
}
/** A non-super caller must still reach BO_ROLES through one of their roles (role 2 is on every admin and grants nothing). */
private static void requireNoLockout(User caller, Long roleId, Set<Long> wanted, List<Map<String, Object>> modules) {
if (caller.getRoles() == null || caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID)) return;
Set<Long> held = new HashSet<>();
caller.getRoles().stream().map(r -> r.getId()).filter(i -> i != null && i != ROLE_ADMIN_ID).forEach(held::add);
if (!held.contains(roleId)) return;
Map<String, Object> rolesModule = modules.stream().filter(m -> ROLES_MODULE.equals(m.get("name"))).findFirst().orElse(null);
if (rolesModule == null) return;
boolean stillGranted = held.stream().anyMatch(r -> r.equals(roleId) ? wanted.contains(AdminRoleService.idOf(rolesModule)) : grantedTo(rolesModule, r));
if (!stillGranted) throw error(HttpStatus.BAD_REQUEST, "This change would remove your own access to role management", "ACL_LOCKOUT");
}
/** Hidden roles (ROLE_MEMBER, ROLE_ADMIN) look absent, as in the role list. */
private void requireVisibleRole(Long roleId) {
if (AdminRoleService.isHidden(adminRoleService.find(roleId))) {
throw error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND");
}
}
/** Only leaf modules (type M) are granted; the type R root is just a container. */
private static boolean isGrantable(Map<String, Object> module) {
return "M".equals(module.get("type"));
}
private static boolean grantedTo(Map<String, Object> module, Long roleId) {
return module.get("roles") instanceof List<?> l && l.stream().anyMatch(r -> roleId.equals(AdminRoleService.idOf(r)));
}
private List<Map<String, Object>> modules() {
List<Map<String, Object>> body = restTemplateUtil.getForEntity(
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_FIND_ALL_BY_AREA), MAP_LIST, AREA).getBody();
return body == null ? List.of() : body;
}
private void call(String api, Long moduleId, Long roleId) {
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(api), Integer.class, moduleId, roleId);
}
private static CodedResponseStatusException error(HttpStatus status, String reason, String code) {
return new CodedResponseStatusException(status, reason, code);
}
}
@@ -0,0 +1,161 @@
package com.solvway.mobile.api.service;
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.dto.admin.AdminRoleRequest;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Admin roles for the portal. Roles travel as maps. services-system's /role/save swallows errors and recomputes
* level and tracekey from the parent, and /role/findById throws on a missing id, so this reads with findAll and
* verifies a rename by re-reading.
*/
@Service
@RequiredArgsConstructor
public class AdminRoleService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
private static final long SUPER_ADMIN_ROLE_ID = 1L;
private static final List<String> HIDDEN = List.of("ROLE_MEMBER", "ROLE_ADMIN");
private static final List<String> PROTECTED = List.of("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_MEMBER");
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
public List<Map<String, Object>> list() {
return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList();
}
public Map<String, Object> get(Long id) {
Map<String, Object> role = find(id);
if (isHidden(role)) throw notFound();
return clean(role);
}
/** Any stored role, hidden ones included; 404 when absent. */
public Map<String, Object> find(Long id) {
return all().stream().filter(r -> id != null && id.equals(idOf(r))).findFirst().orElseThrow(AdminRoleService::notFound);
}
public Map<String, Object> create(AdminRoleRequest r) {
String name = requireName(r);
User caller = caller();
requireFree(name, null);
Map<String, Object> role = new HashMap<>();
role.put("name", name);
role.put("parent", Map.of("id", SUPER_ADMIN_ROLE_ID));
role.put("children", List.of());
role.put("createBy", caller.getUsername());
role.put("doneBy", caller.getUsername());
role.put("createDate", System.currentTimeMillis());
return clean(save(role));
}
public Map<String, Object> update(Long id, AdminRoleRequest r) {
User caller = 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);
requireFree(name, id);
// Send every persisted field back: /role/save recomputes level and tracekey from the parent, and a merge
// without the children would orphan them.
Map<String, Object> role = new HashMap<>();
for (String k : List.of("id", "level", "tracekey", "createBy", "createDate")) role.put(k, stored.get(k));
role.put("id", id);
role.put("name", name);
Long parent = idOf(stored.get("parent"));
if (parent != null) role.put("parent", Map.of("id", parent));
// children go back exactly as stored: services-system re-saves each one from this payload, and a changed list would null their parentid
role.put("children", stored.get("children") instanceof List<?> l ? l : List.of());
role.put("doneBy", caller.getUsername());
save(role);
// ponytail: ignore-case match, so a case-only rename failure goes unnoticed; /role/save gives no error signal.
Map<String, Object> reread = find(id);
if (!name.equalsIgnoreCase(String.valueOf(reread.get("name")))) {
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED");
}
return clean(reread);
}
public static boolean isProtected(Map<String, Object> role) {
return PROTECTED.contains(role.get("name"));
}
static Long idOf(Object ref) {
if (ref instanceof Number n) return n.longValue();
if (ref instanceof Map<?, ?> m && m.get("id") instanceof Number n) return n.longValue();
return null;
}
static boolean isHidden(Map<String, Object> role) {
return HIDDEN.contains(role.get("name"));
}
private String requireName(AdminRoleRequest r) {
if (r == null || !StringUtils.hasText(r.name())) throw error(HttpStatus.BAD_REQUEST, "Role name is required", "REQUIRED_FIELD");
return r.name().trim();
}
/** ponytail: check-then-save is not atomic; the DB unique key on name is the backstop. */
private void requireFree(String name, Long ownId) {
if (all().stream().anyMatch(x -> name.equalsIgnoreCase(String.valueOf(x.get("name"))) && !(ownId != null && ownId.equals(idOf(x))))) {
throw error(HttpStatus.CONFLICT, "Role name is already taken", "ROLE_NAME_TAKEN");
}
}
private List<Map<String, Object>> all() {
List<Map<String, Object>> body = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_FIND_ALL), MAP_LIST).getBody();
return body == null ? List.of() : body;
}
private Map<String, Object> save(Map<String, Object> role) {
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_SAVE), MAP, role);
// services-system swallows save errors and returns the unsaved entity, so a missing id means it failed.
if (ent.getBody() == null || ent.getBody().get("id") == null) {
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "Role could not be saved", "SAVE_FAILED");
}
return ent.getBody();
}
private static Map<String, Object> clean(Map<String, Object> role) {
Map<String, Object> out = new LinkedHashMap<>();
out.put("id", idOf(role.get("id")));
out.put("name", role.get("name"));
out.put("level", role.get("level"));
Long parent = idOf(role.get("parent"));
out.put("parent", parent == null ? null : Map.of("id", parent));
return out;
}
private User caller() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
return caller;
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
private static CodedResponseStatusException notFound() {
return error(HttpStatus.NOT_FOUND, "Role not found", "ROLE_NOT_FOUND");
}
private static CodedResponseStatusException error(HttpStatus status, String reason, String code) {
return new CodedResponseStatusException(status, reason, code);
}
}