From f5d1b6d032753e3badb54eb1cc069db747eb64f3 Mon Sep 17 00:00:00 2001 From: ngqile Date: Thu, 26 Nov 2026 20:26:33 +0800 Subject: [PATCH] feat(mobile-api): admin users API (list, create, edit, deactivate, reset password) New users get a temporary password by email and the creating admin's company. Self-deactivation and super-admin changes by non-super admins are refused. services-system: saving a user no longer cascades into role rows. Local seed: dev admin on the GLOBAL branch (id 0 does not exist). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/seed/03-colite.sql | 2 +- .../add-admin-auth-users-roles/tasks.md | 2 +- .../java/com/solvway/core/model/User.java | 1 + .../api/RestApiSystemServiceConstants.java | 7 + .../controller/admin/AdminUserController.java | 63 ++ .../mobile/api/dto/admin/AdminRoleRef.java | 6 + .../api/dto/admin/AdminUserRequest.java | 10 + .../mobile/api/service/AdminUserService.java | 277 +++++++++ .../admin/AdminUserControllerTest.java | 108 ++++ .../api/service/AdminUserServiceTest.java | 563 ++++++++++++++++++ .../solvway/services/system/model/User.java | 2 +- 11 files changed, 1038 insertions(+), 3 deletions(-) create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java create mode 100644 solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java create mode 100644 solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index d25b23e..400988b 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -22,6 +22,6 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic -- Dev admin: super admin, company 1, password already set (login 'Y', no first-login change). INSERT INTO `user` (`id`, `email`, `enabled`, `name`, `password`, `username`, `groupid`, `branchid`, `login`, `status`, `type`, `create_by`, `create_date`, `done_by`, `company_id`) -VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 0, +VALUES (1, 'admin@co-lite.local', b'1', 'Admin', '$2a$10$RakIbSfLlImTHUz1d5ROceRxnQsVb3K3UoKu2FCk7LccN/kBsw88S', 'admin', 5, 1, 'Y', 'Y', 'A', 'seed', NOW(), 'seed', 1); INSERT INTO `users_roles` (`user_id`, `role_id`) VALUES (1, 1); diff --git a/openspec/changes/add-admin-auth-users-roles/tasks.md b/openspec/changes/add-admin-auth-users-roles/tasks.md index b8cbc9d..4ac3be7 100644 --- a/openspec/changes/add-admin-auth-users-roles/tasks.md +++ b/openspec/changes/add-admin-auth-users-roles/tasks.md @@ -24,7 +24,7 @@ Babyboo source: `~/Projects/babyboo` (read only). All tasks run serially; most t ## 5. mobile-api users and roles -- [ ] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. +- [x] 5.1 Port `AdminUserController` and `AdminUserService`: admin-only list with search, filter and sort; create with temporary password, email and company from the logged-in admin; edit; deactivate with self-deactivation refused; admin-triggered reset via `/user/resetAdminPassword`. Tests first for each `admin-users` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 - [ ] 5.2 Port `AdminRoleController`, `AdminRoleService` and `AdminAclService` (role list hiding `ROLE_MEMBER`, create and rename with unique names, `GET/PUT /roles/{id}/modules` replacing grants, self lock-out refused, super admin grants not editable). Tests first for each `admin-roles` scenario. Verify: `mvn -T 1C -pl solvway-mobile-api -am verify`. - Scope: as 4.1 diff --git a/solvway-core-libs/src/main/java/com/solvway/core/model/User.java b/solvway-core-libs/src/main/java/com/solvway/core/model/User.java index f58257d..4799c87 100644 --- a/solvway-core-libs/src/main/java/com/solvway/core/model/User.java +++ b/solvway-core-libs/src/main/java/com/solvway/core/model/User.java @@ -88,6 +88,7 @@ public class User implements Serializable{ private FlagYesNo fromEmrm = FlagYesNo.N; private String aclHtml; private String uuid; + private Long companyId; public User() { } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index efca2a0..f01e012 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -5,6 +5,13 @@ public class RestApiSystemServiceConstants { private RestApiSystemServiceConstants() {} public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}"; + 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_PROPERTY_AND_PAGEABLE = "/user/findByPropertyAndPageable"; + public static final String API_REST_SYSTEM_ROLE_FIND_ALL = "/role/findAll"; + 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}"; public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME_WITH_PASSWORD = "/user/findByUsernameWithPassword/{username}"; public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PHONE_VERIFIED = "/user/updatePhoneVerified"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java new file mode 100644 index 0000000..b975191 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminUserController.java @@ -0,0 +1,63 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.core.annotation.AppAuth; +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.service.AdminUserService; +import com.solvway.mobile.api.useraccess.AdminModule; +import lombok.RequiredArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.Map; + +/** Admin user CRUD for the portal. Must stay under {@code controller..} for AppAccessAspect. */ +@RestController +@RequestMapping("/api/admin") +@RequiredArgsConstructor +@AdminModule("BO_USERS") +public class AdminUserController { + private final AdminUserService adminUserService; + + @AppAuth + @GetMapping("/users") + public ResponseEntity> list( + @RequestParam(required = false) String q, + @RequestParam(required = false) String searchKey, + @RequestParam(required = false) String enabled, + @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)); + } + + @AppAuth + @GetMapping("/users/{id}") + public ResponseEntity> getById(@PathVariable Long id) { + return ResponseEntity.ok(adminUserService.findById(id)); + } + + @AppAuth + @PostMapping("/users") + public ResponseEntity> create(@RequestBody AdminUserRequest request) { + return ResponseEntity.ok(adminUserService.create(request)); + } + + @AppAuth + @PutMapping("/users/{id}") + public ResponseEntity> update(@PathVariable Long id, @RequestBody AdminUserRequest request) { + return ResponseEntity.ok(adminUserService.update(id, request)); + } + + @AppAuth + @PostMapping("/users/{id}/changePassword") + public ResponseEntity> changePassword(@PathVariable Long id, @RequestBody Map body) { + return ResponseEntity.ok(Map.of("updated", adminUserService.changePassword(id, body.get("password")))); + } + + @AppAuth + @PostMapping("/users/{id}/resetPassword") + public ResponseEntity> resetPassword(@PathVariable Long id) { + return ResponseEntity.ok(Map.of("updated", adminUserService.resetPassword(id))); + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java new file mode 100644 index 0000000..0b0ec10 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminRoleRef.java @@ -0,0 +1,6 @@ +package com.solvway.mobile.api.dto.admin; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminRoleRef(Long id, String name) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java new file mode 100644 index 0000000..e7bcfaf --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/dto/admin/AdminUserRequest.java @@ -0,0 +1,10 @@ +package com.solvway.mobile.api.dto.admin; + +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. */ +@JsonIgnoreProperties(ignoreUnknown = true) +public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, + List roles) {} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java new file mode 100644 index 0000000..0475865 --- /dev/null +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminUserService.java @@ -0,0 +1,277 @@ +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.AdminRoleRef; +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 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.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 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. + */ +@Service +@RequiredArgsConstructor +public class AdminUserService { + private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference>> MAP_LIST = new ParameterizedTypeReference<>() {}; + private static final long SUPER_ADMIN_ROLE_ID = 1L; + private static final List SECRETS = List.of("password", "passwordSecondary", "passwordEmrm"); + private static final List SAVE_FIELDS = List.of("id", "name", "surname", "email", "username", "enabled", "status", + "login", "type", "companyId", "emailVerified", "phoneVerified", "fromEmrm", "master", "lastModifiedPwd", + "createBy", "doneBy", "createDate"); + private static final Map>> SORTS = Map.of( + "name", by("name"), "username", by("username"), "email", by("email"), + "enabled", by("enabled"), + "roles", Comparator.comparing(m -> roleNames(m).toLowerCase())); + + private final RestTemplateCustomUtil restTemplateUtil; + private final AdminAuthenticationService adminAuthenticationService; + + /** + * 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. + */ + public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir) { + Map request = Map.of("property", Map.of("type", "A"), + "pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id")))); + ResponseEntity> ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request); + List> all = ent.getBody() == null ? List.of() : (List>) ent.getBody().get("content"); + resolveRoleRefs(all); + String needle = q == null ? "" : q.trim().toLowerCase(); + Comparator> order = SORTS.getOrDefault(sortBy == null ? "name" : sortBy, SORTS.get("name")); + if ("desc".equalsIgnoreCase(sortDir)) order = order.reversed(); + List> filtered = all.stream() + .filter(m -> needle.isEmpty() || contains(m, "name", needle) || contains(m, "username", needle) || contains(m, "email", needle)) + .filter(m -> !"true".equalsIgnoreCase(enabled) && !"false".equalsIgnoreCase(enabled) + || String.valueOf(m.get("enabled")).equalsIgnoreCase(enabled)) + .sorted(order).toList(); + int s = Math.max(size, 1); + int from = (int) Math.min((long) Math.max(page, 0) * s, filtered.size()); + List> content = filtered.subList(from, Math.min(from + s, filtered.size())).stream() + .map(AdminUserService::clean).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 findById(Long id) { + return clean(load(id)); + } + + public Map create(AdminUserRequest r) { + if (!StringUtils.hasText(r.name()) || !StringUtils.hasText(r.username()) || !StringUtils.hasText(r.email()) + || r.roles() == null || r.roles().isEmpty()) { + throw error(HttpStatus.BAD_REQUEST, "Name, username, email and at least one role are required", "REQUIRED_FIELD"); + } + User caller = caller(); + requireSuperToGrant(caller, r.roles()); + if (caller.getBranch() == null || caller.getBranch().getId() == null) { + throw error(HttpStatus.BAD_REQUEST, "Your account has no branch to assign", "BRANCH_REQUIRED"); + } + // 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) { + throw error(HttpStatus.CONFLICT, "Username is already taken", "USERNAME_TAKEN"); + } + if (get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL, r.email()) != null) { + throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN"); + } + Map user = new HashMap<>(); + user.put("name", r.name()); + user.put("surname", r.surname()); + user.put("username", r.username()); + 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("branch", Map.of("id", caller.getBranch().getId())); + user.put("createBy", caller.getUsername()); + user.put("doneBy", caller.getUsername()); + user.put("createDate", System.currentTimeMillis()); + Map 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"); + } + return clean(saved); + } + + public Map update(Long id, AdminUserRequest r) { + User caller = caller(); + Map user = loadManaged(id, caller); + requireSuperToGrant(caller, r.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) { + throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN"); + } + if (r.roles() != null && r.roles().isEmpty()) { + throw error(HttpStatus.BAD_REQUEST, "At least one role is required", "REQUIRED_FIELD"); + } + if (StringUtils.hasText(r.name())) user.put("name", r.name()); + if (r.surname() != null) user.put("surname", r.surname()); + if (StringUtils.hasText(r.email())) user.put("email", r.email()); + if (r.roles() != null) user.put("roles", roles(r.roles())); + if (r.enabled() != null) { + user.put("enabled", r.enabled()); + user.put("status", r.enabled() ? "Y" : "N"); + } + user.put("doneBy", caller.getUsername()); + return clean(save(user)); + } + + public int resetPassword(Long id) { + Map user = loadManaged(id, caller()); + return adminAuthenticationService.resetAdminPassword((String) user.get("username"), (String) user.get("email")); + } + + public int changePassword(Long id, String password) { + loadManaged(id, caller()); + ResponseEntity ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_UPDATE_USER_PASSWORD), Integer.class, + Map.of("userId", id, "password", password == null ? "" : password)); + int updated = ent.getBody() == null ? 0 : ent.getBody(); + if (updated == 0) throw error(HttpStatus.BAD_REQUEST, "Password does not meet the password rules", "PASSWORD_RULES"); + return updated; + } + + private Map load(Long id) { + Map 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"); + return user; + } + + /** The target admin; a non-super caller may not manage a super admin. */ + private Map loadManaged(Long id, User caller) { + Map user = load(id); + if (!isSuper(caller) && user.get("roles") instanceof List l && l.stream().anyMatch( + x -> x instanceof Map m && m.get("id") instanceof Number n && n.longValue() == SUPER_ADMIN_ROLE_ID)) { + 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 requested) { + if (!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"); + } + } + + private static CodedResponseStatusException superRequired(String reason) { + return error(HttpStatus.FORBIDDEN, reason, "SUPER_ADMIN_REQUIRED"); + } + + /** services-system's /user/save merges roles, so an id-only role would blank the stored row: send the stored ones. */ + private List> roles(List refs) { + List> stored = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_ROLE_FIND_ALL), MAP_LIST).getBody(); + List> out = new ArrayList<>(); + for (AdminRoleRef ref : refs) { + out.add((stored == null ? List.>of() : stored).stream() + .filter(m -> m.get("id") instanceof Number n && ref.id() != null && n.longValue() == ref.id()) + .findFirst().orElseThrow(() -> error(HttpStatus.BAD_REQUEST, "Unknown role " + ref.id(), "UNKNOWN_ROLE"))); + } + return out; + } + + /** services-system serialises a repeated role as a bare id; swap each for the first full occurrence in the list. */ + private static void resolveRoleRefs(List> users) { + Map byId = new HashMap<>(); + for (Map u : users) { + if (u.get("roles") instanceof List l) { + for (Object r : l) if (r instanceof Map m && m.get("id") instanceof Number n) byId.putIfAbsent(n.longValue(), m); + } + } + for (Map u : users) { + if (u.get("roles") instanceof List l) { + u.put("roles", l.stream().map(r -> r instanceof Number n ? byId.get(n.longValue()) : r).filter(java.util.Objects::nonNull).toList()); + } + } + } + + /** + * services-system /user/save writes the whole entity and cannot bind what findById returns (masked passwords, + * nested role/branch trees, transients), so send only the persistent columns, with roles/branch/group as refs. + */ + private static Map slim(Map user) { + Map out = new HashMap<>(); + for (String k : SAVE_FIELDS) if (user.containsKey(k)) out.put(k, user.get(k)); + for (String k : List.of("branch", "userGroup")) { + if (user.get(k) instanceof Map m && m.get("id") != null) out.put(k, Map.of("id", m.get("id"))); + } + if (user.get("roles") instanceof List l) { + out.put("roles", l.stream().map(r -> (Map) r) + .map(r -> Map.of("id", r.get("id"), "name", String.valueOf(r.get("name")))).toList()); + } + return out; + } + + private Map save(Map user) { + ResponseEntity> ent = restTemplateUtil.postForEntity( + url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_SAVE), MAP, slim(user)); + // 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, "User could not be saved", "SAVE_FAILED"); + } + return ent.getBody(); + } + + private Map get(String api, Object... vars) { + return restTemplateUtil.getForEntity(url(api), MAP, vars).getBody(); + } + + private String url(String api) { + return restTemplateUtil.getURLforApiService(api); + } + + private User caller() { + User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken()); + if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED"); + return caller; + } + + private static Map clean(Map user) { + Map out = new HashMap<>(user); + SECRETS.forEach(out::remove); + return out; + } + + private static boolean contains(Map m, String key, String needle) { + return m.get(key) != null && m.get(key).toString().toLowerCase().contains(needle); + } + + private static Comparator> by(String key) { + return Comparator.comparing(m -> String.valueOf(m.get(key)).toLowerCase()); + } + + private static String roleNames(Map m) { + Object roles = m.get("roles"); + if (!(roles instanceof List l)) return ""; + return String.join(",", l.stream().map(r -> r instanceof Map rm ? String.valueOf(rm.get("name")) : "").toList()); + } + + private static CodedResponseStatusException error(HttpStatus status, String reason, String code) { + return new CodedResponseStatusException(status, reason, code); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java new file mode 100644 index 0000000..976b6c0 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminUserControllerTest.java @@ -0,0 +1,108 @@ +package com.solvway.mobile.api.controller.admin; + +import com.solvway.mobile.api.dto.admin.AdminUserRequest; +import com.solvway.mobile.api.service.AdminUserService; +import com.solvway.mobile.api.useraccess.AdminModule; +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.junit.jupiter.MockitoExtension; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +class AdminUserControllerTest { + + @Mock private AdminUserService users; + @InjectMocks private AdminUserController controller; + private MockMvc mvc; + + @BeforeEach + void setUp() { + mvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void guardedByBackOfficeUsersModule() { + assertThat(AdminUserController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_USERS"); + } + + @Test + void list_passesParamsAndReturnsPageShape() throws Exception { + when(users.list("ali", "true", 1, 5, "name", "desc")) + .thenReturn(Map.of("content", List.of(Map.of("id", 1)), "totalElements", 6L)); + mvc.perform(get("/api/admin/users").param("q", "ali").param("enabled", "true").param("page", "1") + .param("size", "5").param("sortBy", "name").param("sortDir", "desc")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].id").value(1)) + .andExpect(jsonPath("$.totalElements").value(6)); + } + + @Test + void list_legacySearchKeyActsAsQ() throws Exception { + when(users.list("bob", null, 0, 20, null, null)).thenReturn(Map.of("content", List.of())); + mvc.perform(get("/api/admin/users").param("searchKey", "bob")).andExpect(status().isOk()); + verify(users).list("bob", null, 0, 20, null, null); + } + + @Test + void getById_returnsUser() throws Exception { + when(users.findById(5L)).thenReturn(Map.of("id", 5, "username", "a")); + mvc.perform(get("/api/admin/users/5")).andExpect(status().isOk()).andExpect(jsonPath("$.username").value("a")); + } + + @Test + void create_ignoresPortalExtrasAndPassesRequest() throws Exception { + when(users.create(any())).thenReturn(Map.of("id", 9)); + mvc.perform(post("/api/admin/users").contentType(MediaType.APPLICATION_JSON) + .content("{\"name\":\"N\",\"username\":\"u\",\"email\":\"e@x.com\",\"password\":\"x\",\"companyId\":99," + + "\"roles\":[{\"id\":4,\"name\":\"R\"}]}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9)); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminUserRequest.class); + verify(users).create(c.capture()); + assertThat(c.getValue().username()).isEqualTo("u"); + assertThat(c.getValue().roles().get(0).id()).isEqualTo(4L); + } + + @Test + void update_passesIdAndRequest() throws Exception { + when(users.update(any(), any())).thenReturn(Map.of("id", 5)); + mvc.perform(put("/api/admin/users/5").contentType(MediaType.APPLICATION_JSON).content("{\"enabled\":false}")) + .andExpect(status().isOk()); + ArgumentCaptor c = ArgumentCaptor.forClass(AdminUserRequest.class); + verify(users).update(org.mockito.ArgumentMatchers.eq(5L), c.capture()); + assertThat(c.getValue().enabled()).isFalse(); + } + + @Test + void resetPassword_returnsUpdated() throws Exception { + when(users.resetPassword(5L)).thenReturn(1); + mvc.perform(post("/api/admin/users/5/resetPassword")).andExpect(status().isOk()) + .andExpect(jsonPath("$.updated").value(1)); + } + + @Test + void changePassword_returnsUpdated() throws Exception { + when(users.changePassword(5L, "Str0ng#Pass")).thenReturn(1); + mvc.perform(post("/api/admin/users/5/changePassword").contentType(MediaType.APPLICATION_JSON) + .content("{\"password\":\"Str0ng#Pass\"}")) + .andExpect(status().isOk()).andExpect(jsonPath("$.updated").value(1)); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java new file mode 100644 index 0000000..a5b0b86 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceTest.java @@ -0,0 +1,563 @@ +package com.solvway.mobile.api.service; + +import com.solvway.core.model.LocationHierarchy; +import com.solvway.core.model.Role; +import com.solvway.core.model.User; +import com.solvway.core.utils.HttpReqRespUtils; +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.util.RestTemplateCustomUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminUserServiceTest { + + private static final String FIND_BY_ID = "/user/findById/{id}"; + private static final String SAVE = "/user/save"; + private static final String PAGE = "/user/findByPropertyAndPageable"; + private static final String BY_USERNAME = "/user/findByUsername/{username}"; + private static final String BY_EMAIL = "/user/findByEmail/{email}"; + private static final String BY_EMAIL_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; + private static final String UPDATE_PWD = "/user/updateUserPassword"; + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private AdminUserService service; + private MockedStatic http; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + service = new AdminUserService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + User caller = new User(); + caller.setId(1L); + caller.setUsername("boss"); + caller.setCompanyId(7L); + LocationHierarchy branch = new LocationHierarchy(); + branch.setId(3L); + caller.setBranch(branch); + when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok(List.of(fullRole(1, "ROLE_SUPER_ADMIN"), fullRole(4, "ROLE_SALES"), fullRole(5, "ROLE_OPS")))); + } + + private static Map fullRole(long id, String name) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("level", 2); + m.put("tracekey", "tk" + id); + m.put("createBy", "sys"); + return m; + } + + private void callerIsSuper() { + Role r = new Role(); + r.setId(1L); + when(auth.loadUserByToken("tok")).thenAnswer(i -> { + User u = new User(); + u.setId(1L); + u.setUsername("boss"); + u.setCompanyId(7L); + LocationHierarchy b = new LocationHierarchy(); + b.setId(3L); + u.setBranch(b); + u.setRoles(List.of(r)); + return u; + }); + } + + private Map superAdminRow(long id) { + Map m = row(id, "Root", "root", "r@x.com", true); + m.put("roles", List.of(fullRole(1, "ROLE_SUPER_ADMIN"))); + return m; + } + + @AfterEach + void close() { http.close(); } + + private Map row(long id, String name, String username, String email, boolean enabled, String... roles) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + m.put("username", username); + m.put("email", email); + m.put("enabled", enabled); + m.put("type", "A"); + m.put("password", "$2a$secret"); + m.put("passwordSecondary", "$2a$secret2"); + m.put("passwordEmrm", "$2a$secret3"); + List> rs = new ArrayList<>(); + for (String r : roles) rs.add(new HashMap<>(Map.of("id", 10L, "name", r))); + m.put("roles", rs); + return m; + } + + private void stubPage(Map... rows) { + when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(Map.of("content", List.of(rows)))); + } + + private void stubFind(long id, Map row) { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(id))) + .thenReturn(ResponseEntity.ok(row)); + } + + private void stubSave(Map saved) { + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok(saved)); + } + + private void stubNoDuplicates() { + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any())) + .thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any())) + .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); + } + + private AdminUserRequest req(String name, String username, String email, List roles) { + return new AdminUserRequest(name, null, username, email, null, roles); + } + + private static final List ROLES = List.of(new AdminRoleRef(4L, "ROLE_SALES")); + + private static void assertCoded(Runnable r, HttpStatus status, String code) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getCode()).isEqualTo(code); + }); + } + + // ---- list ---- + + @Test + void list_asksDownstreamForAdminsOnly() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + service.list(null, null, 0, 20, null, null); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + Map sent = (Map) body.getValue(); + assertThat((Map) sent.get("property")).containsEntry("type", "A"); + } + + @Test + void list_searchesNameUsernameEmailCaseInsensitive() { + stubPage(row(1, "Alice Tan", "alice", "a@x.com", true, "R"), + row(2, "Bob", "bobby", "b@x.com", true, "R"), + row(3, "Cy", "cy", "CARL@x.com", true, "R")); + assertThat(names(service.list("ALI", null, 0, 20, null, null))).containsExactly("Alice Tan"); + assertThat(names(service.list("bobb", null, 0, 20, null, null))).containsExactly("Bob"); + assertThat(names(service.list("carl", null, 0, 20, null, null))).containsExactly("Cy"); + } + + @Test + void list_filtersByEnabled() { + stubPage(row(1, "On", "on", "o@x.com", true, "R"), row(2, "Off", "off", "f@x.com", false, "R")); + assertThat(names(service.list(null, "false", 0, 20, null, null))).containsExactly("Off"); + assertThat(names(service.list(null, "true", 0, 20, null, null))).containsExactly("On"); + assertThat(names(service.list(null, null, 0, 20, null, null))).hasSize(2); + } + + @Test + void list_sortsAndPagesOnTheServer() { + stubPage(row(1, "Cc", "c", "c@x.com", true, "R"), row(2, "Aa", "a", "a@x.com", true, "R"), + row(3, "Bb", "b", "b@x.com", true, "R")); + Map p0 = service.list(null, null, 0, 2, "name", "asc"); + assertThat(names(p0)).containsExactly("Aa", "Bb"); + assertThat(p0).containsEntry("totalElements", 3L).containsEntry("totalPages", 2) + .containsEntry("number", 0).containsEntry("size", 2); + assertThat(names(service.list(null, null, 1, 2, "name", "asc"))).containsExactly("Cc"); + assertThat(names(service.list(null, null, 0, 3, "username", "desc"))).containsExactly("Cc", "Bb", "Aa"); + } + + @Test + void list_neverReturnsPasswordHashes() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + Map first = ((List>) service.list(null, null, 0, 20, null, null).get("content")).get(0); + assertThat(first).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + private List names(Map page) { + return ((List>) page.get("content")).stream().map(m -> (String) m.get("name")).toList(); + } + + // ---- get ---- + + @Test + void findById_returnsAdminWithoutPasswords() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + assertThat(service.findById(5L)).containsEntry("username", "a") + .doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + @Test + void findById_unknownOrNonAdmin_is404() { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L))) + .thenReturn(ResponseEntity.ok().build()); + assertCoded(() -> service.findById(8L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + Map member = row(9, "M", "m", "m@x.com", true, "R"); + member.put("type", "M"); + stubFind(9, member); + assertCoded(() -> service.findById(9L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + // ---- create ---- + + @Test + void create_savesActiveAdminWithCallerCompanyThenSendsTemporaryPassword() { + stubNoDuplicates(); + stubSave(row(20, "New", "newbie", "n@x.com", true, "ROLE_SALES")); + AdminUserRequest r = new AdminUserRequest("New", "Guy", "newbie", "n@x.com", false, ROLES); + + Map out = service.create(r); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).containsEntry("username", "newbie").containsEntry("email", "n@x.com") + .containsEntry("name", "New").containsEntry("enabled", true).containsEntry("status", "Y") + .containsEntry("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L) + .containsEntry("createBy", "boss").containsEntry("doneBy", "boss"); + assertThat(saved).doesNotContainKey("id").doesNotContainKey("password"); + assertThat((Map) saved.get("branch")).containsEntry("id", 3L); + assertThat(((List>) saved.get("roles")).get(0)).containsEntry("id", 4L); + verify(auth).resetAdminPassword("newbie", "n@x.com"); + assertThat(out).containsEntry("id", 20L).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm"); + } + + @Test + void create_duplicateUsername_is409UsernameTaken() { + stubNoDuplicates(); + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup"))) + .thenReturn(ResponseEntity.ok(row(2, "X", "dup", "x@x.com", true, "R"))); + 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()); + } + + @Test + void create_duplicateEmail_is409EmailTaken() { + stubNoDuplicates(); + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com"))) + .thenReturn(ResponseEntity.ok(row(2, "X", "x", "dup@x.com", true, "R"))); + assertCoded(() -> service.create(req("N", "n", "dup@x.com", ROLES)), HttpStatus.CONFLICT, "EMAIL_TAKEN"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_missingRequiredFields_is400() { + assertCoded(() -> service.create(req("", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", " ", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", null, ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", "e@x.com", List.of())), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + assertCoded(() -> service.create(req("N", "u", "e@x.com", null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_callerWithoutBranch_is400BranchRequired() { + stubNoDuplicates(); + User noBranch = new User(); + noBranch.setCompanyId(7L); + when(auth.loadUserByToken("tok")).thenReturn(noBranch); + assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "BRANCH_REQUIRED"); + } + + @Test + void create_tempPasswordNotSent_is502AfterUserCreated() { + 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"); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_saveReturnsNoId_isServerError() { + stubNoDuplicates(); + stubSave(new HashMap<>()); + assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED"); + verify(auth, never()).resetAdminPassword(anyString(), anyString()); + } + + // ---- update ---- + + @Test + void update_changesOnlyNameEmailRolesEnabled() { + stubNoDuplicates(); + Map stored = row(5, "Old", "keep", "old@x.com", true, "R"); + stored.put("companyId", 7L); + stored.put("login", "Y"); + stubFind(5, stored); + stubSave(row(5, "New", "keep", "new@x.com", true, "ROLE_SALES")); + AdminUserRequest r = new AdminUserRequest("New", null, "hacker", "new@x.com", true, ROLES); + + service.update(5L, r); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).containsEntry("id", 5L).containsEntry("name", "New").containsEntry("email", "new@x.com") + .containsEntry("username", "keep").containsEntry("type", "A").containsEntry("companyId", 7L) + .containsEntry("login", "Y").containsEntry("enabled", true).containsEntry("status", "Y"); + assertThat(((List>) saved.get("roles")).get(0)).containsEntry("id", 4L); + } + + @Test + void update_deactivate_setsEnabledFalseAndStatusN() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", false, "R")); + service.update(5L, new AdminUserRequest(null, null, null, null, false, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("enabled", false).containsEntry("status", "N"); + } + + @Test + void update_selfDeactivation_is400() { + stubFind(1, row(1, "Boss", "boss", "b@x.com", true, "R")); + assertCoded(() -> service.update(1L, new AdminUserRequest(null, null, null, null, false, null)), + HttpStatus.BAD_REQUEST, "SELF_DEACTIVATION"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_emailUsedByAnotherUser_is409() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L))) + .thenReturn(ResponseEntity.ok(row(2, "X", "x", "taken@x.com", true, "R"))); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, "taken@x.com", null, null)), + HttpStatus.CONFLICT, "EMAIL_TAKEN"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void update_unknownUser_is404() { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L))) + .thenReturn(ResponseEntity.ok().build()); + assertCoded(() -> service.update(8L, req("N", null, "e@x.com", ROLES)), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + @Test + void update_blankEmail_skipsDuplicateCheckAndKeepsStoredEmail() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + service.update(5L, new AdminUserRequest(null, null, null, "", null, null)); + verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any()); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("email", "a@x.com"); + } + + @Test + void update_loadsCallerOnce() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", false, "R")); + service.update(5L, new AdminUserRequest("B", null, null, null, false, null)); + verify(auth, times(1)).loadUserByToken("tok"); + } + + // ---- roles are sent as {id, name} from the stored role ---- + + @Test + void create_sendsStoredRoleIdAndNameOnly() { + stubNoDuplicates(); + stubSave(row(20, "N", "u", "e@x.com", true, "R")); + service.create(req("N", "u", "e@x.com", List.of(new AdminRoleRef(4L, "whatever")))); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((List>) ((Map) body.getValue()).get("roles")).get(0)) + .containsOnlyKeys("id", "name").containsEntry("id", 4L).containsEntry("name", "ROLE_SALES"); + } + + @Test + void update_sendsStoredRoleIdAndNameOnly() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + service.update(5L, new AdminUserRequest(null, null, null, null, null, ROLES)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + assertThat(((List>) ((Map) body.getValue()).get("roles")).get(0)) + .containsOnlyKeys("id", "name").containsEntry("name", "ROLE_SALES"); + } + + @Test + void update_savesOnlyWhitelistedUserFields() { + stubNoDuplicates(); + Map stored = row(5, "A", "a", "a@x.com", true, "R"); + stored.put("status", "Y"); + stored.put("companyId", 7L); + stored.put("emailVerified", "Y"); + stored.put("showPassword", false); + stored.put("linkedAccounts", List.of()); + stored.put("token", "t"); + stored.put("memberCode", "m"); + stored.put("branch", new HashMap<>(Map.of("id", 3L, "code", "G", "children", List.of()))); + stored.put("userGroup", new HashMap<>(Map.of("id", 9L, "name", "grp"))); + stubFind(5, stored); + stubSave(row(5, "A", "a", "a@x.com", true, "R")); + + service.update(5L, new AdminUserRequest(null, null, null, null, null, null)); + + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + Map saved = (Map) body.getValue(); + assertThat(saved).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm", "showPassword", + "linkedAccounts", "token", "memberCode"); + assertThat(saved).containsEntry("emailVerified", "Y").containsEntry("companyId", 7L); + assertThat((Map) saved.get("branch")).containsOnlyKeys("id"); + assertThat((Map) saved.get("userGroup")).containsOnlyKeys("id"); + } + + @Test + void list_sendsASortSoServicesSystemCanPage() { + stubPage(row(1, "A", "a", "a@x.com", true, "R")); + service.list(null, null, 0, 20, null, null); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + Map pageable = (Map) ((Map) body.getValue()).get("pageableRest"); + assertThat((List>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "id")); + } + + @Test + void unknownRole_is400UnknownRole_onCreateAndUpdate() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + List bad = List.of(new AdminRoleRef(99L, "NOPE")); + assertCoded(() -> service.create(req("N", "u", "e@x.com", bad)), HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE"); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, bad)), + HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + // ---- super admin guard ---- + + private static final List SUPER = List.of(new AdminRoleRef(1L, "ROLE_SUPER_ADMIN")); + + @Test + void nonSuperCaller_cannotGrantSuperAdmin() { + stubNoDuplicates(); + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + assertCoded(() -> service.create(req("N", "u", "e@x.com", SUPER)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, SUPER)), + HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void superCaller_canGrantSuperAdmin() { + stubNoDuplicates(); + callerIsSuper(); + stubSave(row(20, "N", "u", "e@x.com", true, "R")); + service.create(req("N", "u", "e@x.com", SUPER)); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void nonSuperCaller_cannotManageSuperAdminTarget() { + stubNoDuplicates(); + stubFind(6, superAdminRow(6)); + assertCoded(() -> service.update(6L, new AdminUserRequest("X", null, null, null, null, null)), + HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.resetPassword(6L), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + assertCoded(() -> service.changePassword(6L, "Str0ng#Pass"), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + verify(rest, never()).postForEntity(eq(UPDATE_PWD), eq(Integer.class), any()); + verify(auth, never()).resetAdminPassword(anyString(), anyString()); + } + + @Test + void superCaller_canManageSuperAdminTarget() { + callerIsSuper(); + stubFind(6, superAdminRow(6)); + when(auth.resetAdminPassword("root", "r@x.com")).thenReturn(1); + assertThat(service.resetPassword(6L)).isEqualTo(1); + } + + // ---- shared roles in list (services-system sends repeats as bare ids) ---- + + private Map userWithRoles(long id, String name, Object... roles) { + Map m = row(id, name, name.toLowerCase(), name + "@x.com", true); + m.put("roles", new ArrayList<>(List.of(roles))); + return m; + } + + @Test + void list_sharedRoleSentAsBareId_sortByRolesDoesNotThrow() { + stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L)); + assertThat(names(service.list(null, null, 0, 20, "roles", "asc"))).containsExactly("Aa", "Bb"); + } + + @Test + void list_bareRoleIdResolvedEvenWhenFullRoleIsOnAnotherPage() { + stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L)); + Map page1 = service.list(null, null, 1, 1, "name", "asc"); + Map u = ((List>) page1.get("content")).get(0); + assertThat(u).containsEntry("name", "Bb"); + assertThat(((List>) u.get("roles")).get(0)).containsEntry("name", "ROLE_SALES").containsEntry("tracekey", "tk4"); + } + + // ---- passwords ---- + + @Test + void resetPassword_usesStoredUsernameAndEmail() { + stubFind(5, row(5, "A", "stored", "stored@x.com", true, "R")); + when(auth.resetAdminPassword("stored", "stored@x.com")).thenReturn(1); + assertThat(service.resetPassword(5L)).isEqualTo(1); + verify(auth).resetAdminPassword("stored", "stored@x.com"); + } + + @Test + void changePassword_rulesRejected_is400() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(0)); + assertCoded(() -> service.changePassword(5L, "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_RULES"); + } + + @Test + void changePassword_ok_returnsRowsUpdated() { + stubFind(5, row(5, "A", "a", "a@x.com", true, "R")); + when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(1)); + assertThat(service.changePassword(5L, "Str0ng#Pass")).isEqualTo(1); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(UPDATE_PWD), eq(Integer.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("userId", 5L).containsEntry("password", "Str0ng#Pass"); + } +} diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java b/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java index 9fc02c2..9ab4b9a 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/model/User.java @@ -69,7 +69,7 @@ public class User { @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Long.class) - @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.MERGE) + @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = {@JoinColumn(name = "user_id")}, inverseJoinColumns = {@JoinColumn(name = "role_id")})