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 f65dc5d..7f943aa 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 @@ -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"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java index 3d86cf3..cc057cc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityController.java @@ -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>> locked() { - return ResponseEntity.ok(loginSecurity.locked()); + public ResponseEntity>> 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 unlock(@PathVariable String username) { - loginSecurity.unlock(username); + public ResponseEntity unlock(@PathVariable String username, @RequestParam(required = false) Long companyId) { + loginSecurity.unlock(username, companyId); return ResponseEntity.noContent().build(); } 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 index acfcbb4..ec7bbc4 100644 --- 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 @@ -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 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 index f8eaea1..dd31a8d 100644 --- 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 @@ -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 roles, String password, String confirmPassword) { + List roles, String password, String confirmPassword, + Long companyId, Boolean superAdmin) { + + public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, + List 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 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. */ diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java index 360f98d..13935fd 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminAclService.java @@ -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> modules = modules(); Set known = new HashSet<>(); diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java index 898dcdc..76962ce 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminInterestService.java @@ -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> list() { - return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList(); + caller(); + return load().stream().map(AdminInterestService::row).toList(); } public Map create(AdminInterestRequest r) { - User caller = caller(); + scope.requireSuper(caller()); Map 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 update(long id, AdminInterestRequest r) { - User caller = caller(); - Map stored = load(caller.getCompanyId()).stream() + scope.requireSuper(caller()); + Map 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 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> load(long companyId) { + // ponytail: the counter ignores the company id (one shared list); 0 is a placeholder for its path variable. + private List> load() { List> 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; } diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLoginSecurityService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLoginSecurityService.java index 24e12a1..6424328 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLoginSecurityService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminLoginSecurityService.java @@ -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 audit(String username, String event, String from, String to, int page, int size) { + return audit(username, event, from, to, page, size, null); + } + + public Map audit(String username, String event, String from, String to, int page, int size, Long companyId) { + Long company = scope.scope(caller(), companyId); Map 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> locked() { - return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody(); + return locked(null); + } + + public List> 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 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 saveConfig(Map config) { + scope.requireSuper(caller()); Map before = readOrNull(this::config); Map saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config); if (before != null && saved != null) { @@ -78,6 +110,7 @@ public class AdminLoginSecurityService { } public List> savePasswordRules(List> rules) { + scope.requireSuper(caller()); List> before = readOrNull(this::passwordRules); List> 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) { diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java index b1cd4ba..7410dcc 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/AdminRoleService.java @@ -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> list() { return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList(); @@ -54,6 +56,7 @@ public class AdminRoleService { public Map create(AdminRoleRequest r) { String name = requireName(r); User caller = caller(); + scope.requireSuper(caller); requireFree(name, null); Map role = new HashMap<>(); role.put("name", name); @@ -67,6 +70,7 @@ public class AdminRoleService { public Map update(Long id, AdminRoleRequest r) { User caller = caller(); + scope.requireSuper(caller); Map stored = find(id); if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE"); String name = requireName(r); 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 index d278c30..27783a5 100644 --- 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 @@ -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 list(String q, String enabled, int page, int size, String sortBy, String sortDir) { - Map request = Map.of("property", Map.of("type", "A"), + return list(q, enabled, page, size, sortBy, sortDir, null); + } + + public Map list(String q, String enabled, int page, int size, String sortBy, String sortDir, Long companyId) { + Long company = scope.scope(caller(), companyId); + Map property = new HashMap<>(); + property.put("type", "A"); + if (company != null) property.put("companyId", company); + Map request = Map.of("property", property, "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); @@ -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> 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 findById(Long id) { - return clean(load(id)); + return present(clean(load(id, caller()))); } public Map 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 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 update(Long id, AdminUserRequest r) { @@ -126,10 +150,13 @@ public class AdminUserService { Map 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 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 load(Long id) { + /** Another company's user is a 404 for staff; a super admin may open any. */ + private Map load(Long id, User caller) { 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"); + 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 loadManaged(Long id, User caller) { - Map user = load(id); + Map 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 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 stored, List 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 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 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 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 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 present(Map 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"); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityControllerTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityControllerTest.java index a61c0e1..90eda64 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityControllerTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/controller/admin/AdminLoginSecurityControllerTest.java @@ -43,7 +43,7 @@ class AdminLoginSecurityControllerTest { @Test void audit_passesFiltersAndPaging() throws Exception { - when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5)) + when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5, null)) .thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6)); mvc.perform(get("/api/admin/login-security/audit").param("username", "sales1").param("event", "LOCKED") .param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5")) @@ -53,21 +53,21 @@ class AdminLoginSecurityControllerTest { @Test void audit_defaultsToFirstPageOfTwenty() throws Exception { - when(security.audit(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of())); + when(security.audit(null, null, null, null, 0, 20, null)).thenReturn(Map.of("content", List.of())); mvc.perform(get("/api/admin/login-security/audit")).andExpect(status().isOk()); - verify(security).audit(null, null, null, null, 0, 20); + verify(security).audit(null, null, null, null, 0, 20, null); } @Test void locked_returnsList() throws Exception { - when(security.locked()).thenReturn(List.of(Map.of("username", "sales1", "failures", 5))); + when(security.locked(null)).thenReturn(List.of(Map.of("username", "sales1", "failures", 5))); mvc.perform(get("/api/admin/login-security/locked")).andExpect(status().isOk()).andExpect(jsonPath("$[0].username").value("sales1")); } @Test void unlock_returns204() throws Exception { mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent()); - verify(security).unlock("sales1"); + verify(security).unlock("sales1", null); } @Test 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 index d159188..9b7b083 100644 --- 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 @@ -46,7 +46,7 @@ class AdminUserControllerTest { @Test void list_passesParamsAndReturnsPageShape() throws Exception { - when(users.list("ali", "true", 1, 5, "name", "desc")) + when(users.list("ali", "true", 1, 5, "name", "desc", null)) .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")) @@ -57,9 +57,9 @@ class AdminUserControllerTest { @Test void list_legacySearchKeyActsAsQ() throws Exception { - when(users.list("bob", null, 0, 20, null, null)).thenReturn(Map.of("content", List.of())); + when(users.list("bob", null, 0, 20, null, 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); + verify(users).list("bob", null, 0, 20, null, null, null); } @Test diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java index 6ad4b04..f74c883 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminAclServiceTest.java @@ -64,7 +64,7 @@ class AdminAclServiceTest { module(ROOT, "BO_ROOT", null, 1), module(USERS, "BO_USERS", ROOT, 1, 4), module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5)); - caller(5); + caller(1, 5); } @AfterEach @@ -198,20 +198,21 @@ class AdminAclServiceTest { @Test void update_nonSuperCallerEditingARoleTheyHoldIsRefused() { caller(5, 2); // role 2 is attached to every admin and is ignored - assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "OWN_ROLE"); + assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); verifyNothingChanged(); } @Test void update_ownRoleIsRefusedEvenWhenAnotherCallerRoleGrantsBoRoles() { caller(5, 6, 2); - assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "OWN_ROLE"); + assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); verifyNothingChanged(); } @Test void update_ownRoleIsRefusedEvenWhenTheChangeKeepsBoRoles() { - assertCoded(() -> service.updateGrants(5L, List.of(ROLES, USERS)), HttpStatus.FORBIDDEN, "OWN_ROLE"); + caller(5); + assertCoded(() -> service.updateGrants(5L, List.of(ROLES, USERS)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); verifyNothingChanged(); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java index d9d37cc..ec1e3dc 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminInterestServiceTest.java @@ -49,7 +49,8 @@ class AdminInterestServiceTest { http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); User caller = new User(); caller.setUsername("boss"); - caller.setCompanyId(5L); + caller.setCompanyId(null); + { com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); } when(auth.loadUserByToken("tok")).thenReturn(caller); when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) .thenAnswer(i -> ResponseEntity.ok(i.getArgument(2))); @@ -69,7 +70,7 @@ class AdminInterestServiceTest { } private void stubList(Map... rows) { - when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(5L))).thenReturn(ResponseEntity.ok(List.of(rows))); + when(rest.getForEntity(eq(LIST), any(ParameterizedTypeReference.class), eq(0L))).thenReturn(ResponseEntity.ok(List.of(rows))); } private Map saved() { @@ -95,10 +96,10 @@ class AdminInterestServiceTest { } @Test - void createSendsTrimmedActiveInterestForTheCallersCompany() { + void createSendsTrimmedActiveInterest() { service.create(new AdminInterestRequest(" Kitchen appliances ", null, null)); - assertThat(saved()).containsEntry("companyId", 5L).containsEntry("name", "Kitchen appliances") + assertThat(saved()).doesNotContainKey("companyId").containsEntry("name", "Kitchen appliances") .containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id"); } @@ -128,7 +129,7 @@ class AdminInterestServiceTest { service.update(2L, new AdminInterestRequest(null, false, null)); - assertThat(saved()).containsEntry("id", 2L).containsEntry("companyId", 5L).containsEntry("name", "Cookware") + assertThat(saved()).containsEntry("id", 2L).doesNotContainKey("companyId").containsEntry("name", "Cookware") .containsEntry("active", false).containsEntry("sortOrder", 3); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceAuditChangesTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceAuditChangesTest.java index cb654ea..efda8a3 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceAuditChangesTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceAuditChangesTest.java @@ -42,6 +42,7 @@ class AdminLoginSecurityServiceAuditChangesTest { http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); User caller = new User(); caller.setUsername("boss"); + { com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); } when(auth.loadUserByToken("tok")).thenReturn(caller); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceTest.java index 7b23438..b656cf6 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminLoginSecurityServiceTest.java @@ -54,6 +54,7 @@ class AdminLoginSecurityServiceTest { http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); User caller = new User(); caller.setUsername("boss"); + { com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); } when(auth.loadUserByToken("tok")).thenReturn(caller); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java index 5d37194..1180b56 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminRoleServiceTest.java @@ -50,6 +50,7 @@ class AdminRoleServiceTest { http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); User caller = new User(); caller.setUsername("boss"); + { com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); } when(auth.loadUserByToken("tok")).thenReturn(caller); stubRoles(stored()); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminSuperOnlyAndLoginScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminSuperOnlyAndLoginScopeTest.java new file mode 100644 index 0000000..62f0808 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminSuperOnlyAndLoginScopeTest.java @@ -0,0 +1,236 @@ +package com.solvway.mobile.api.service; + +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.AdminInterestRequest; +import com.solvway.mobile.api.dto.admin.AdminRoleRequest; +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.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.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** Roles, interests, grants and login-security settings are super-admin only; locked list, history and unlock are company scoped. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminSuperOnlyAndLoginScopeTest { + + private RestTemplateCustomUtil rest; + private AdminAuthenticationService auth; + private MockedStatic http; + private AdminRoleService roles; + private AdminInterestService interests; + private AdminAclService acl; + private AdminLoginSecurityService security; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + auth = mock(AdminAuthenticationService.class); + roles = new AdminRoleService(rest, auth); + interests = new AdminInterestService(rest, auth); + acl = new AdminAclService(rest, auth, roles); + security = new AdminLoginSecurityService(rest, auth); + when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0)); + http = mockStatic(HttpReqRespUtils.class); + http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok"); + when(rest.postForEntity(any(String.class), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(i.getArgument(2) instanceof Map ? (Object) new HashMap<>((Map) i.getArgument(2)) : i.getArgument(2))); + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(List.of())); + when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok(List.of())); + staff(7L); + } + + @AfterEach + void close() { http.close(); } + + private void staff(Long companyId) { caller(companyId, 4L); } + + private void superAdmin() { caller(null, 1L); } + + private void caller(Long companyId, long roleId) { + User u = new User(); + u.setId(1L); + u.setUsername("boss"); + u.setCompanyId(companyId); + Role r = new Role(); + r.setId(roleId); + u.setRoles(List.of(r)); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private static void assertSuperOnly(Runnable r) { + assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + assertThat(e.getCode()).isEqualTo("SUPER_ADMIN_REQUIRED"); + }); + } + + private void nothingWritten() { + verify(rest, never()).postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()); + } + + // ---- 403 for staff ---- + + @Test + void roleCreateAndRename_403ForStaff() { + assertSuperOnly(() -> roles.create(new AdminRoleRequest("New"))); + assertSuperOnly(() -> roles.update(5L, new AdminRoleRequest("New"))); + nothingWritten(); + } + + @Test + void roleCreate_worksForSuperAdmin() { + superAdmin(); + Map saved = Map.of("id", 99L, "name", "New"); + when(rest.postForEntity(eq("/role/save"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(saved)); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(List.of())); + assertThat(roles.create(new AdminRoleRequest("New"))).containsEntry("name", "New"); + } + + @Test + void roleList_stillOpenToStaff() { + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(List.of(Map.of("id", 5L, "name", "ROLE_OPS")))); + assertThat(roles.list()).hasSize(1); + } + + @Test + void moduleGrants_403ForStaff() { + when(rest.getForEntity(eq("/module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of())); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(List.of(Map.of("id", 5L, "name", "ROLE_OPS")))); + assertSuperOnly(() -> acl.updateGrants(5L, List.of())); + } + + @Test + void interestWrites_403ForStaff() { + assertSuperOnly(() -> interests.create(new AdminInterestRequest("Golf", true, 1))); + assertSuperOnly(() -> interests.update(3L, new AdminInterestRequest("Golf", true, 1))); + nothingWritten(); + } + + @Test + void interestCreate_worksForSuperAdminWithNoCompany() { + superAdmin(); + interests.create(new AdminInterestRequest("Golf", true, 1)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/counter/interest/save"), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).doesNotContainKey("companyId").containsEntry("name", "Golf"); + } + + @Test + void interestList_openToStaff() { + interests.list(); + verify(rest).getForEntity(eq("/counter/interest/findByCompany/{companyId}"), any(ParameterizedTypeReference.class), any(Object[].class)); + } + + @Test + void lockoutAndPasswordRuleChanges_403ForStaffAndWorkForSuper() { + assertSuperOnly(() -> security.saveConfig(Map.of("enabled", true))); + assertSuperOnly(() -> security.savePasswordRules(List.of())); + nothingWritten(); + superAdmin(); + security.saveConfig(Map.of("enabled", true)); + security.savePasswordRules(List.of()); + } + + @Test + void lockoutAndPasswordRuleReads_openToStaff() { + when(rest.getForEntity(eq("/loginSecurity/config"), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(Map.of("enabled", true))); + assertThat(security.config()).containsEntry("enabled", true); + assertThat(security.passwordRules()).isEmpty(); + } + + // ---- scoped login security ---- + + private Map postedAuditBody() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/loginSecurity/audit"), any(ParameterizedTypeReference.class), body.capture()); + return (Map) body.getValue(); + } + + @Test + void history_staffGetsOwnCompanyWhateverWasRequested() { + security.audit(null, null, null, null, 0, 20, 9L); + assertThat(postedAuditBody()).containsEntry("companyId", 7L); + } + + @Test + void history_superFiltersOrSeesAll() { + superAdmin(); + security.audit(null, null, null, null, 0, 20, 9L); + assertThat(postedAuditBody()).containsEntry("companyId", 9L); + } + + @Test + void history_superWithNoCompanySeesAll() { + superAdmin(); + security.audit(null, null, null, null, 0, 20, null); + assertThat(postedAuditBody()).doesNotContainKey("companyId"); + } + + @Test + void locked_staffScopedToOwnCompany() { + security.locked(9L); + verify(rest).getForEntity(eq("/loginSecurity/locked?companyId={companyId}"), any(ParameterizedTypeReference.class), eq(7L)); + } + + @Test + void locked_superWithNoCompanyIsUnfiltered() { + superAdmin(); + security.locked(null); + verify(rest).getForEntity(eq("/loginSecurity/locked"), any(ParameterizedTypeReference.class)); + } + + @Test + void unlock_staffPassesOwnCompany() { + security.unlock("ann@ins", 9L); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/loginSecurity/unlock"), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).containsEntry("companyId", 7L).containsEntry("username", "ann@ins"); + } + + @Test + void unlock_superWithNoCompanySendsNone() { + superAdmin(); + security.unlock("ann@ins", null); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/loginSecurity/unlock"), any(ParameterizedTypeReference.class), body.capture()); + assertThat((Map) body.getValue()).doesNotContainKey("companyId"); + } + + @Test + void unlock_anotherCompanysUserAnswers404() { + when(rest.postForEntity(eq("/loginSecurity/unlock"), any(ParameterizedTypeReference.class), any())) + .thenThrow(org.springframework.web.client.HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, new byte[0], null)); + assertThatThrownBy(() -> security.unlock("ann@cv", null)).isInstanceOfSatisfying(CodedResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + } + + @Test + void saveConfig_upstream404KeepsItsOwnMappingNotUserNotFound() { + superAdmin(); + when(rest.postForEntity(eq("/loginSecurity/config"), any(ParameterizedTypeReference.class), any())) + .thenThrow(org.springframework.web.client.HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, new byte[0], null)); + assertThatThrownBy(() -> security.saveConfig(new HashMap<>(Map.of("maxAttempts", 5)))) + .isInstanceOf(org.springframework.web.client.HttpClientErrorException.NotFound.class); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceAuditChangesTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceAuditChangesTest.java index 7090cbf..f4a8ebc 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceAuditChangesTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceAuditChangesTest.java @@ -53,11 +53,12 @@ class AdminUserServiceAuditChangesTest { when(auth.loadUserByToken("tok")).thenReturn(caller); when(auth.passesAdminPasswordRules(anyString())).thenReturn(true); when(auth.setAdminPassword(any(), anyString())).thenReturn(1); + when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins"))); when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))) .thenReturn(ResponseEntity.ok(List.of(role(4, "ROLE_SALES"), role(5, "ROLE_OPS"), role(6, "ROLE_ACCOUNTS")))); when(rest.getForEntity(eq("/user/findByUsername/{username}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build()); - when(rest.getForEntity(eq("/user/findByEmail/{email}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build()); - when(rest.getForEntity(eq("/user/findByEmailAndIdNot/{email}/{id}"), any(ParameterizedTypeReference.class), any(), any())).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq("/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any())) .thenAnswer(i -> { Map saved = new HashMap<>((Map) i.getArgument(2)); @@ -87,6 +88,7 @@ class AdminUserServiceAuditChangesTest { u.put("email", "sam@x.com"); u.put("enabled", enabled); u.put("type", "A"); + u.put("companyId", 7L); u.put("roles", List.of(roles)); when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u)); } diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceCompanyScopeTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceCompanyScopeTest.java new file mode 100644 index 0000000..7be6c18 --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/AdminUserServiceCompanyScopeTest.java @@ -0,0 +1,345 @@ +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** Company scoping of admin users: list, detail, create, edit. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class AdminUserServiceCompanyScopeTest { + + 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/findByEmailAndCompanyId/{email}"; + private static final String BY_EMAIL_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}"; + private static final String COMPANY = "/company/findById/{id}"; + private static final String PW = "Good#Pass1"; + private static final List SALES = List.of(new AdminRoleRef(4L, "ROLE_SALES")); + private static final List SUPER = List.of(new AdminRoleRef(1L, "ROLE_SUPER_ADMIN")); + + 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"); + when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class))) + .thenReturn(ResponseEntity.ok(List.of(fullRole(1, "ROLE_SUPER_ADMIN"), fullRole(4, "ROLE_SALES")))); + when(rest.getForEntity(eq(COMPANY), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins"))); + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL + "?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL_NOT + "?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build()); + when(auth.passesAdminPasswordRules(anyString())).thenReturn(true); + when(auth.setAdminPassword(any(), anyString())).thenReturn(1); + when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> { Map m = new HashMap<>((Map) i.getArgument(2)); m.putIfAbsent("id", 99L); return ResponseEntity.ok(m); }); + staff(7L); + } + + @AfterEach + void close() { http.close(); } + + private static Map fullRole(long id, String name) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", name); + return m; + } + + /** Company staff (no role 1) of the given company. */ + private void staff(Long companyId) { caller(companyId); } + + private void superAdmin() { caller(null, 1L); } + + private void caller(Long companyId, Long... roleIds) { + User u = new User(); + u.setId(1L); + u.setUsername("boss"); + u.setCompanyId(companyId); + LocationHierarchy b = new LocationHierarchy(); + b.setId(3L); + u.setBranch(b); + List rs = new ArrayList<>(); + for (Long id : roleIds) { Role r = new Role(); r.setId(id); rs.add(r); } + u.setRoles(rs); + when(auth.loadUserByToken("tok")).thenReturn(u); + } + + private static Map row(long id, String username, Long companyId) { + Map m = new HashMap<>(); + m.put("id", id); + m.put("name", "N" + id); + m.put("username", username); + m.put("email", "u" + id + "@x.com"); + m.put("enabled", true); + m.put("type", "A"); + m.put("companyId", companyId); + m.put("companyCode", companyId == null ? null : "ins"); + m.put("roles", List.of(new HashMap<>(Map.of("id", 4L, "name", "ROLE_SALES")))); + 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(Map row) { + when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(row.get("id")))).thenReturn(ResponseEntity.ok(row)); + } + + private Map sentProperty() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture()); + return (Map) ((Map) body.getValue()).get("property"); + } + + private Map savedBody() { + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture()); + return (Map) body.getValue(); + } + + private static AdminUserRequest create(String username, List roles, Long companyId, Boolean superAdmin) { + return new AdminUserRequest("Ann", null, username, "ann@x.com", null, roles, PW, PW, companyId, superAdmin); + } + + 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_staffAskedForOwnCompanyWhateverWasRequested() { + stubPage(row(1, "ann@ins", 7L)); + service.list(null, null, 0, 20, null, null, 9L); + assertThat(sentProperty()).containsEntry("companyId", 7L).containsEntry("type", "A"); + } + + @Test + void list_superSeesAllWhenNoCompanyChosen() { + superAdmin(); + stubPage(row(1, "ann@ins", 7L)); + service.list(null, null, 0, 20, null, null, null); + assertThat(sentProperty()).doesNotContainKey("companyId"); + } + + @Test + void list_superFiltersByChosenCompany() { + superAdmin(); + stubPage(row(1, "ann@ins", 9L)); + service.list(null, null, 0, 20, null, null, 9L); + assertThat(sentProperty()).containsEntry("companyId", 9L); + } + + @Test + void list_rowsShowLocalUsernameLoginNameAndCompany() { + superAdmin(); + stubPage(row(1, "ann@ins", 7L), row(2, "root", null)); + List> rows = (List>) service.list(null, null, 0, 20, "name", "asc", null).get("content"); + assertThat(rows.get(0)).containsEntry("username", "ann").containsEntry("loginName", "ann@ins") + .containsEntry("companyId", 7L).containsEntry("companyCode", "ins"); + assertThat(rows.get(1)).containsEntry("username", "root").containsEntry("loginName", "root"); + } + + @Test + void list_searchMatchesTheLoginName() { + stubPage(row(1, "ann@ins", 7L), row(2, "bob@ins", 7L)); + assertThat(((List) service.list("ann@", null, 0, 20, null, null, null).get("content"))).hasSize(1); + } + + // ---- detail and edits within scope ---- + + @Test + void detail_ownCompanyShowsLocalPartAndLoginName() { + stubFind(row(5, "ann@ins", 7L)); + assertThat(service.findById(5L)).containsEntry("username", "ann").containsEntry("loginName", "ann@ins"); + } + + @Test + void detail_otherCompanyIs404ForStaff() { + stubFind(row(5, "ann@cv", 8L)); + assertCoded(() -> service.findById(5L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + @Test + void detail_superAdminRowIs404ForStaff() { + stubFind(row(5, "root", null)); + assertCoded(() -> service.findById(5L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + @Test + void detail_superMayOpenAnyCompany() { + superAdmin(); + stubFind(row(5, "ann@cv", 8L)); + assertThat(service.findById(5L)).containsEntry("companyId", 8L); + } + + @Test + void update_otherCompanyIs404AndNothingIsSaved() { + stubFind(row(5, "ann@cv", 8L)); + assertCoded(() -> service.update(5L, new AdminUserRequest("New", null, null, null, null, null)), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void resetPasswordAndTemporaryPassword_otherCompanyIs404() { + stubFind(row(5, "ann@cv", 8L)); + assertCoded(() -> service.resetPassword(5L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + assertCoded(() -> service.setTemporaryPassword(5L, PW, PW), HttpStatus.NOT_FOUND, "USER_NOT_FOUND"); + } + + @Test + void update_neverChangesTheCompanyOrLoginName() { + stubFind(row(5, "ann@ins", 7L)); + service.update(5L, create("evil@cv", null, 8L, null)); + assertThat(savedBody()).containsEntry("companyId", 7L).containsEntry("username", "ann@ins"); + } + + @Test + void update_emailUniquenessIsPerCompanyOfTheStoredUser() { + stubFind(row(5, "ann@ins", 7L)); + service.update(5L, new AdminUserRequest(null, null, null, "new@x.com", null, null)); + verify(rest).getForEntity(eq(BY_EMAIL_NOT + "?companyId={companyId}"), any(ParameterizedTypeReference.class), eq("new@x.com"), eq(5L), eq(7L)); + } + + // ---- create ---- + + @Test + void create_staffStoresLocalAtCompanyCodeInOwnCompany() { + Map out = service.create(create("ann", SALES, 9L, null)); + assertThat(savedBody()).containsEntry("username", "ann@ins").containsEntry("companyId", 7L); + assertThat(out).containsEntry("username", "ann").containsEntry("loginName", "ann@ins"); + verify(rest).getForEntity(eq(BY_EMAIL + "?companyId={companyId}"), any(ParameterizedTypeReference.class), eq("ann@x.com"), eq(7L)); + verify(rest).getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("ann@ins")); + } + + @Test + void update_emailCheckWorksWhenUpstreamSendsCompanyIdAsInteger() { + Map r = row(5, "ann@ins", 7L); + r.put("companyId", 7); // untyped JSON gives Integer for small numbers + stubFind(r); + service.update(5L, new AdminUserRequest(null, null, null, "new@x.com", null, null)); + verify(rest).getForEntity(eq(BY_EMAIL_NOT + "?companyId={companyId}"), any(ParameterizedTypeReference.class), eq("new@x.com"), eq(5L), eq(7L)); + } + + @Test + void create_unknownCompanyIs400CompanyNotFound() { + superAdmin(); + when(rest.getForEntity(eq(COMPANY), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build()); + assertCoded(() -> service.create(create("ann", SALES, 404L, null)), HttpStatus.BAD_REQUEST, "COMPANY_NOT_FOUND"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_usernameWithAtIsRefusedWithAFieldMessage() { + assertThatThrownBy(() -> service.create(create("ann@cv", SALES, null, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "username")); + }); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_superMustChooseACompany() { + superAdmin(); + assertCoded(() -> service.create(create("ann", SALES, null, null)), HttpStatus.BAD_REQUEST, "COMPANY_REQUIRED"); + } + + @Test + void create_superInChosenCompany() { + superAdmin(); + service.create(create("ann", SALES, 9L, null)); + assertThat(savedBody()).containsEntry("companyId", 9L).containsEntry("username", "ann@ins"); + } + + @Test + void create_superAdminTrueHasNoCompanyAndAPlainUsername() { + superAdmin(); + service.create(create("root2", SUPER, null, true)); + assertThat(savedBody()).containsEntry("username", "root2").containsEntry("companyId", null); + verify(rest).getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("ann@x.com")); + verify(rest, never()).getForEntity(eq(COMPANY), any(ParameterizedTypeReference.class), any()); + } + + @Test + void create_superAdminTrueNeedsRole1() { + superAdmin(); + assertThatThrownBy(() -> service.create(create("root2", SALES, null, true))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "roles")); + }); + } + + @Test + void create_staffCannotCreateASuperAdmin() { + assertCoded(() -> service.create(create("root2", SUPER, null, true)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED"); + } + + @Test + void create_role1IsRefusedForACompanyUserBeforeAnyServiceCall() { + superAdmin(); + assertThatThrownBy(() -> service.create(create("ann", SUPER, 9L, null))) + .isInstanceOfSatisfying(CodedResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "roles")); + }); + verifyNoInteractions(rest); + } + + @Test + void update_role1IsRefusedForACompanyUser() { + superAdmin(); + stubFind(row(5, "ann@ins", 7L)); + assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, SUPER)), HttpStatus.BAD_REQUEST, "INVALID_ROLE"); + verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); + } +} 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 index 4046cbe..c3dbcba 100644 --- 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 @@ -41,8 +41,8 @@ class AdminUserServiceTest { 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 BY_EMAIL = "/user/findByEmailAndCompanyId/{email}?companyId={companyId}"; + private static final String BY_EMAIL_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}"; private RestTemplateCustomUtil rest; private AdminAuthenticationService auth; @@ -65,6 +65,8 @@ class AdminUserServiceTest { branch.setId(3L); caller.setBranch(branch); when(auth.loadUserByToken("tok")).thenReturn(caller); + when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any())) + .thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins"))); 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")))); } @@ -86,7 +88,7 @@ class AdminUserServiceTest { User u = new User(); u.setId(1L); u.setUsername("boss"); - u.setCompanyId(7L); + u.setCompanyId(null); LocationHierarchy b = new LocationHierarchy(); b.setId(3L); u.setBranch(b); @@ -112,6 +114,7 @@ class AdminUserServiceTest { m.put("email", email); m.put("enabled", enabled); m.put("type", "A"); + m.put("companyId", 7L); m.put("password", "$2a$secret"); m.put("passwordSecondary", "$2a$secret2"); m.put("passwordEmrm", "$2a$secret3"); @@ -139,9 +142,9 @@ class AdminUserServiceTest { 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())) + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any(Object[].class))) .thenReturn(ResponseEntity.ok().build()); - when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any())) + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(Object[].class))) .thenReturn(ResponseEntity.ok().build()); when(auth.passesAdminPasswordRules(anyString())).thenReturn(true); when(auth.setAdminPassword(any(), anyString())).thenReturn(1); @@ -248,7 +251,7 @@ class AdminUserServiceTest { 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") + assertThat(saved).containsEntry("username", "newbie@ins").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"); @@ -263,7 +266,7 @@ class AdminUserServiceTest { @Test void create_duplicateUsername_is409UsernameTaken() { stubNoDuplicates(); - when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup"))) + when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup@ins"))) .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()); @@ -274,7 +277,7 @@ class AdminUserServiceTest { @Test void create_duplicateEmail_is409EmailTaken() { stubNoDuplicates(); - when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com"))) + when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com"), eq(7L))) .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()); @@ -379,7 +382,7 @@ class AdminUserServiceTest { 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))) + when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L), eq(7L))) .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"); @@ -399,7 +402,7 @@ class AdminUserServiceTest { 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()); + verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(Object[].class)); 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"); @@ -506,8 +509,10 @@ class AdminUserServiceTest { void superCaller_canGrantSuperAdmin() { stubNoDuplicates(); callerIsSuper(); + when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}"), any(ParameterizedTypeReference.class), any(Object[].class))) + .thenReturn(ResponseEntity.ok().build()); stubSave(row(20, "N", "u", "e@x.com", true, "R")); - service.create(req("N", "u", "e@x.com", SUPER)); + service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, SUPER, PW, PW, null, true)); verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()); }