feat: company-scoped users and login security, super-admin-only roles, interests and settings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
00ce47bc49
commit
de2ae63cea
20 files changed
+795
-82
No files matched your search
+2
@@ -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_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 = "/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_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_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_FIND_ALL = "/role/findAll";
|
||||||
public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save";
|
public static final String API_REST_SYSTEM_ROLE_SAVE = "/role/save";
|
||||||
|
|||||||
+7
-6
@@ -35,21 +35,22 @@ public class AdminLoginSecurityController {
|
|||||||
@RequestParam(required = false) String from,
|
@RequestParam(required = false) String from,
|
||||||
@RequestParam(required = false) String to,
|
@RequestParam(required = false) String to,
|
||||||
@RequestParam(defaultValue = "0") int page,
|
@RequestParam(defaultValue = "0") int page,
|
||||||
@RequestParam(defaultValue = "20") int size) {
|
@RequestParam(defaultValue = "20") int size,
|
||||||
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size));
|
@RequestParam(required = false) Long companyId) {
|
||||||
|
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size, companyId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@AppAuth
|
@AppAuth
|
||||||
@GetMapping("/locked")
|
@GetMapping("/locked")
|
||||||
public ResponseEntity<List<Map<String, Object>>> locked() {
|
public ResponseEntity<List<Map<String, Object>>> locked(@RequestParam(required = false) Long companyId) {
|
||||||
return ResponseEntity.ok(loginSecurity.locked());
|
return ResponseEntity.ok(loginSecurity.locked(companyId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
|
@Audited(target = false) // the username is whatever was typed at sign-in, possibly a password
|
||||||
@AppAuth
|
@AppAuth
|
||||||
@PostMapping("/locked/{username}/unlock")
|
@PostMapping("/locked/{username}/unlock")
|
||||||
public ResponseEntity<Void> unlock(@PathVariable String username) {
|
public ResponseEntity<Void> unlock(@PathVariable String username, @RequestParam(required = false) Long companyId) {
|
||||||
loginSecurity.unlock(username);
|
loginSecurity.unlock(username, companyId);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -28,8 +28,9 @@ public class AdminUserController {
|
|||||||
@RequestParam(defaultValue = "0") int page,
|
@RequestParam(defaultValue = "0") int page,
|
||||||
@RequestParam(defaultValue = "20") int size,
|
@RequestParam(defaultValue = "20") int size,
|
||||||
@RequestParam(required = false) String sortBy,
|
@RequestParam(required = false) String sortBy,
|
||||||
@RequestParam(required = false) String sortDir) {
|
@RequestParam(required = false) String sortDir,
|
||||||
return ResponseEntity.ok(adminUserService.list(q != null ? q : searchKey, enabled, page, size, sortBy, sortDir));
|
@RequestParam(required = false) Long companyId) {
|
||||||
|
return ResponseEntity.ok(adminUserService.list(q != null ? q : searchKey, enabled, page, size, sortBy, sortDir, companyId));
|
||||||
}
|
}
|
||||||
|
|
||||||
@AppAuth
|
@AppAuth
|
||||||
|
|||||||
+11
-4
@@ -5,16 +5,23 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fields an admin may set. Type and company are deliberately absent: the portal's extra fields are ignored.
|
* Fields an admin may set. Type is deliberately absent: the portal's extra fields are ignored.
|
||||||
* The password pair is read on create only; updates never change a password.
|
* 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)
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
|
public record AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
|
||||||
List<AdminRoleRef> roles, String password, String confirmPassword) {
|
List<AdminRoleRef> roles, String password, String confirmPassword,
|
||||||
|
Long companyId, Boolean superAdmin) {
|
||||||
|
|
||||||
|
public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled,
|
||||||
|
List<AdminRoleRef> roles, String password, String confirmPassword) {
|
||||||
|
this(name, surname, username, email, enabled, roles, password, confirmPassword, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
/** An update request: no password. */
|
/** An update request: no password. */
|
||||||
public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, List<AdminRoleRef> roles) {
|
public AdminUserRequest(String name, String surname, String username, String email, Boolean enabled, List<AdminRoleRef> roles) {
|
||||||
this(name, surname, username, email, enabled, roles, null, null);
|
this(name, surname, username, email, enabled, roles, null, null, null, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Never print the password pair. */
|
/** Never print the password pair. */
|
||||||
|
|||||||
+1
-5
@@ -45,11 +45,7 @@ public class AdminAclService {
|
|||||||
if (moduleIds == null) throw error(HttpStatus.BAD_REQUEST, "moduleIds is required", "REQUIRED_FIELD");
|
if (moduleIds == null) throw error(HttpStatus.BAD_REQUEST, "moduleIds is required", "REQUIRED_FIELD");
|
||||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||||
|
new AdminCompanyScope().requireSuper(caller);
|
||||||
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");
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Map<String, Object>> modules = modules();
|
List<Map<String, Object>> modules = modules();
|
||||||
Set<Long> known = new HashSet<>();
|
Set<Long> known = new HashSet<>();
|
||||||
|
|||||||
+12
-9
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
|||||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||||
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
import com.solvway.mobile.api.dto.admin.AdminInterestRequest;
|
||||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||||
|
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
import org.springframework.core.ParameterizedTypeReference;
|
||||||
@@ -16,7 +17,7 @@ import java.util.LinkedHashMap;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
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
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class AdminInterestService {
|
public class AdminInterestService {
|
||||||
@@ -26,15 +27,17 @@ public class AdminInterestService {
|
|||||||
|
|
||||||
private final RestTemplateCustomUtil restTemplateUtil;
|
private final RestTemplateCustomUtil restTemplateUtil;
|
||||||
private final AdminAuthenticationService adminAuthenticationService;
|
private final AdminAuthenticationService adminAuthenticationService;
|
||||||
|
// a field initializer, so Lombok leaves it out of the constructor (the scope holds no state)
|
||||||
|
private final AdminCompanyScope scope = new AdminCompanyScope();
|
||||||
|
|
||||||
public List<Map<String, Object>> list() {
|
public List<Map<String, Object>> list() {
|
||||||
return load(caller().getCompanyId()).stream().map(AdminInterestService::row).toList();
|
caller();
|
||||||
|
return load().stream().map(AdminInterestService::row).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> create(AdminInterestRequest r) {
|
public Map<String, Object> create(AdminInterestRequest r) {
|
||||||
User caller = caller();
|
scope.requireSuper(caller());
|
||||||
Map<String, Object> body = new LinkedHashMap<>();
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
body.put("companyId", caller.getCompanyId());
|
|
||||||
body.put("name", checkedName(r.name()));
|
body.put("name", checkedName(r.name()));
|
||||||
body.put("active", r.active() == null || r.active());
|
body.put("active", r.active() == null || r.active());
|
||||||
body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder());
|
body.put("sortOrder", r.sortOrder() == null ? 0 : r.sortOrder());
|
||||||
@@ -42,13 +45,12 @@ public class AdminInterestService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
public Map<String, Object> update(long id, AdminInterestRequest r) {
|
||||||
User caller = caller();
|
scope.requireSuper(caller());
|
||||||
Map<String, Object> stored = load(caller.getCompanyId()).stream()
|
Map<String, Object> stored = load().stream()
|
||||||
.filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst()
|
.filter(m -> m.get("id") instanceof Number n && n.longValue() == id).findFirst()
|
||||||
.orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null));
|
.orElseThrow(() -> error(HttpStatus.NOT_FOUND, "Interest not found", "INTEREST_NOT_FOUND", null));
|
||||||
Map<String, Object> body = new LinkedHashMap<>();
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
body.put("id", id);
|
body.put("id", id);
|
||||||
body.put("companyId", caller.getCompanyId());
|
|
||||||
body.put("name", r.name() == null ? stored.get("name") : checkedName(r.name()));
|
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("active", r.active() == null ? stored.get("active") : r.active());
|
||||||
body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder());
|
body.put("sortOrder", r.sortOrder() == null ? stored.get("sortOrder") : r.sortOrder());
|
||||||
@@ -63,9 +65,10 @@ public class AdminInterestService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Map<String, Object>> load(long companyId) {
|
// ponytail: the counter ignores the company id (one shared list); 0 is a placeholder for its path variable.
|
||||||
|
private List<Map<String, Object>> load() {
|
||||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, companyId).getBody();
|
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), LIST, 0L).getBody();
|
||||||
return rows == null ? List.of() : rows;
|
return rows == null ? List.of() : rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+42
-5
@@ -6,6 +6,7 @@ import com.solvway.core.model.User;
|
|||||||
import com.solvway.core.utils.HttpReqRespUtils;
|
import com.solvway.core.utils.HttpReqRespUtils;
|
||||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
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.useraccess.AuditChanges;
|
||||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -35,25 +36,55 @@ public class AdminLoginSecurityService {
|
|||||||
|
|
||||||
private final RestTemplateCustomUtil restTemplateUtil;
|
private final RestTemplateCustomUtil restTemplateUtil;
|
||||||
private final AdminAuthenticationService adminAuthenticationService;
|
private final AdminAuthenticationService adminAuthenticationService;
|
||||||
|
// a field initializer, so Lombok leaves it out of the constructor (the scope holds no state)
|
||||||
|
private final AdminCompanyScope scope = new AdminCompanyScope();
|
||||||
|
|
||||||
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size) {
|
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size) {
|
||||||
|
return audit(username, event, from, to, page, size, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size, Long companyId) {
|
||||||
|
Long company = scope.scope(caller(), companyId);
|
||||||
Map<String, Object> body = new LinkedHashMap<>();
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
if (StringUtils.hasText(username)) body.put("username", username.trim());
|
if (StringUtils.hasText(username)) body.put("username", username.trim());
|
||||||
if (StringUtils.hasText(event)) body.put("event", event.trim());
|
if (StringUtils.hasText(event)) body.put("event", event.trim());
|
||||||
if (StringUtils.hasText(from)) body.put("from", from.trim());
|
if (StringUtils.hasText(from)) body.put("from", from.trim());
|
||||||
if (StringUtils.hasText(to)) body.put("to", to.trim());
|
if (StringUtils.hasText(to)) body.put("to", to.trim());
|
||||||
|
if (company != null) body.put("companyId", company);
|
||||||
body.put("page", page);
|
body.put("page", page);
|
||||||
body.put("size", size);
|
body.put("size", size);
|
||||||
return post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_AUDIT, MAP, body);
|
return post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_AUDIT, MAP, body);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Map<String, Object>> locked() {
|
public List<Map<String, Object>> locked() {
|
||||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
|
return locked(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> locked(Long companyId) {
|
||||||
|
Long company = scope.scope(caller(), companyId);
|
||||||
|
if (company == null) {
|
||||||
|
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
|
||||||
|
}
|
||||||
|
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED + "?companyId={companyId}"), LIST, company).getBody();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void unlock(String username) {
|
public void unlock(String username) {
|
||||||
String by = callerName();
|
unlock(username, null);
|
||||||
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, Map.of("username", username, "by", by));
|
}
|
||||||
|
|
||||||
|
public void unlock(String username, Long companyId) {
|
||||||
|
User caller = caller();
|
||||||
|
Long company = scope.scope(caller, companyId);
|
||||||
|
String by = caller.getUsername();
|
||||||
|
Map<String, Object> body = new LinkedHashMap<>();
|
||||||
|
body.put("username", username);
|
||||||
|
body.put("by", by);
|
||||||
|
if (company != null) body.put("companyId", company);
|
||||||
|
try {
|
||||||
|
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, body);
|
||||||
|
} catch (HttpClientErrorException.NotFound e) {
|
||||||
|
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
|
||||||
|
}
|
||||||
log.info("login lock for {} cleared by {}", username, by);
|
log.info("login lock for {} cleared by {}", username, by);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,6 +93,7 @@ public class AdminLoginSecurityService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> saveConfig(Map<String, Object> config) {
|
public Map<String, Object> saveConfig(Map<String, Object> config) {
|
||||||
|
scope.requireSuper(caller());
|
||||||
Map<String, Object> before = readOrNull(this::config);
|
Map<String, Object> before = readOrNull(this::config);
|
||||||
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
|
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
|
||||||
if (before != null && saved != null) {
|
if (before != null && saved != null) {
|
||||||
@@ -78,6 +110,7 @@ public class AdminLoginSecurityService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
|
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
|
||||||
|
scope.requireSuper(caller());
|
||||||
List<Map<String, Object>> before = readOrNull(this::passwordRules);
|
List<Map<String, Object>> before = readOrNull(this::passwordRules);
|
||||||
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
|
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
|
||||||
if (before != null && saved != null) {
|
if (before != null && saved != null) {
|
||||||
@@ -132,10 +165,14 @@ public class AdminLoginSecurityService {
|
|||||||
return "Invalid request";
|
return "Invalid request";
|
||||||
}
|
}
|
||||||
|
|
||||||
private String callerName() {
|
private User caller() {
|
||||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
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) {
|
private String url(String api) {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
|||||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||||
import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
|
import com.solvway.mobile.api.dto.admin.AdminRoleRequest;
|
||||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||||
|
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.core.ParameterizedTypeReference;
|
import org.springframework.core.ParameterizedTypeReference;
|
||||||
@@ -35,6 +36,7 @@ public class AdminRoleService {
|
|||||||
|
|
||||||
private final RestTemplateCustomUtil restTemplateUtil;
|
private final RestTemplateCustomUtil restTemplateUtil;
|
||||||
private final AdminAuthenticationService adminAuthenticationService;
|
private final AdminAuthenticationService adminAuthenticationService;
|
||||||
|
private final AdminCompanyScope scope = new AdminCompanyScope();
|
||||||
|
|
||||||
public List<Map<String, Object>> list() {
|
public List<Map<String, Object>> list() {
|
||||||
return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList();
|
return all().stream().filter(r -> !isHidden(r)).map(AdminRoleService::clean).toList();
|
||||||
@@ -54,6 +56,7 @@ public class AdminRoleService {
|
|||||||
public Map<String, Object> create(AdminRoleRequest r) {
|
public Map<String, Object> create(AdminRoleRequest r) {
|
||||||
String name = requireName(r);
|
String name = requireName(r);
|
||||||
User caller = caller();
|
User caller = caller();
|
||||||
|
scope.requireSuper(caller);
|
||||||
requireFree(name, null);
|
requireFree(name, null);
|
||||||
Map<String, Object> role = new HashMap<>();
|
Map<String, Object> role = new HashMap<>();
|
||||||
role.put("name", name);
|
role.put("name", name);
|
||||||
@@ -67,6 +70,7 @@ public class AdminRoleService {
|
|||||||
|
|
||||||
public Map<String, Object> update(Long id, AdminRoleRequest r) {
|
public Map<String, Object> update(Long id, AdminRoleRequest r) {
|
||||||
User caller = caller();
|
User caller = caller();
|
||||||
|
scope.requireSuper(caller);
|
||||||
Map<String, Object> stored = find(id);
|
Map<String, Object> stored = find(id);
|
||||||
if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE");
|
if (isProtected(stored)) throw error(HttpStatus.BAD_REQUEST, "This role cannot be edited", "ROLE_NOT_EDITABLE");
|
||||||
String name = requireName(r);
|
String name = requireName(r);
|
||||||
|
|||||||
+90
-21
@@ -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.AdminRoleRef;
|
||||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
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.useraccess.AuditChanges;
|
||||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -46,14 +47,24 @@ public class AdminUserService {
|
|||||||
|
|
||||||
private final RestTemplateCustomUtil restTemplateUtil;
|
private final RestTemplateCustomUtil restTemplateUtil;
|
||||||
private final AdminAuthenticationService adminAuthenticationService;
|
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
|
* 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.
|
* admins (staff-sized) and filters, sorts and pages here. Upgrade: extend that downstream query.
|
||||||
* It is not company-scoped: that must be added before multi-company.
|
* The company filter is passed down: staff see their own company, a super admin the chosen one or all.
|
||||||
*/
|
*/
|
||||||
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
|
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir) {
|
||||||
Map<String, Object> request = Map.of("property", Map.of("type", "A"),
|
return list(q, enabled, page, size, sortBy, sortDir, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> list(String q, String enabled, int page, int size, String sortBy, String sortDir, Long companyId) {
|
||||||
|
Long company = scope.scope(caller(), companyId);
|
||||||
|
Map<String, Object> property = new HashMap<>();
|
||||||
|
property.put("type", "A");
|
||||||
|
if (company != null) property.put("companyId", company);
|
||||||
|
Map<String, Object> request = Map.of("property", property,
|
||||||
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
|
"pageableRest", Map.of("number", 0, "size", 10000, "sorts", List.of(Map.of("direction", "ASC", "property", "id"))));
|
||||||
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(
|
ResponseEntity<Map<String, Object>> ent = restTemplateUtil.postForEntity(
|
||||||
url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_PROPERTY_AND_PAGEABLE), MAP, request);
|
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 s = Math.max(size, 1);
|
||||||
int from = (int) Math.min((long) Math.max(page, 0) * s, filtered.size());
|
int from = (int) Math.min((long) Math.max(page, 0) * s, filtered.size());
|
||||||
List<Map<String, Object>> content = filtered.subList(from, Math.min(from + s, filtered.size())).stream()
|
List<Map<String, Object>> content = filtered.subList(from, Math.min(from + s, filtered.size())).stream()
|
||||||
.map(AdminUserService::clean).toList();
|
.map(m -> present(clean(m))).toList();
|
||||||
return Map.of("content", content, "totalElements", (long) filtered.size(),
|
return Map.of("content", content, "totalElements", (long) filtered.size(),
|
||||||
"totalPages", (filtered.size() + s - 1) / s, "number", Math.max(page, 0), "size", s);
|
"totalPages", (filtered.size() + s - 1) / s, "number", Math.max(page, 0), "size", s);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> findById(Long id) {
|
public Map<String, Object> findById(Long id) {
|
||||||
return clean(load(id));
|
return present(clean(load(id, caller())));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> create(AdminUserRequest r) {
|
public Map<String, Object> create(AdminUserRequest r) {
|
||||||
@@ -87,27 +98,40 @@ public class AdminUserService {
|
|||||||
requireValidPassword(r.password(), r.confirmPassword());
|
requireValidPassword(r.password(), r.confirmPassword());
|
||||||
User caller = caller();
|
User caller = caller();
|
||||||
requireSuperToGrant(caller, r.roles());
|
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) {
|
if (caller.getBranch() == null || caller.getBranch().getId() == null) {
|
||||||
throw error(HttpStatus.BAD_REQUEST, "Your account has no branch to assign", "BRANCH_REQUIRED");
|
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.
|
// 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");
|
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");
|
throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN");
|
||||||
}
|
}
|
||||||
Map<String, Object> user = new HashMap<>();
|
Map<String, Object> user = new HashMap<>();
|
||||||
user.put("name", r.name());
|
user.put("name", r.name());
|
||||||
user.put("surname", r.surname());
|
user.put("surname", r.surname());
|
||||||
user.put("username", r.username());
|
user.put("username", loginName);
|
||||||
user.put("email", r.email());
|
user.put("email", r.email());
|
||||||
user.put("roles", roles(r.roles()));
|
user.put("roles", roles(r.roles()));
|
||||||
user.put("enabled", true);
|
user.put("enabled", true);
|
||||||
user.put("status", "Y");
|
user.put("status", "Y");
|
||||||
user.put("type", "A");
|
user.put("type", "A");
|
||||||
user.put("login", "N");
|
user.put("login", "N");
|
||||||
user.put("companyId", caller.getCompanyId());
|
user.put("companyId", company);
|
||||||
user.put("branch", Map.of("id", caller.getBranch().getId()));
|
user.put("branch", Map.of("id", caller.getBranch().getId()));
|
||||||
user.put("createBy", caller.getUsername());
|
user.put("createBy", caller.getUsername());
|
||||||
user.put("doneBy", caller.getUsername());
|
user.put("doneBy", caller.getUsername());
|
||||||
@@ -118,7 +142,7 @@ public class AdminUserService {
|
|||||||
}
|
}
|
||||||
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
|
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
|
||||||
AuditChanges.put("enabled", null, true);
|
AuditChanges.put("enabled", null, true);
|
||||||
return clean(saved);
|
return present(clean(saved));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Object> update(Long id, AdminUserRequest r) {
|
public Map<String, Object> update(Long id, AdminUserRequest r) {
|
||||||
@@ -126,10 +150,13 @@ public class AdminUserService {
|
|||||||
Map<String, Object> user = loadManaged(id, caller);
|
Map<String, Object> user = loadManaged(id, caller);
|
||||||
requireSuperToGrant(caller, r.roles());
|
requireSuperToGrant(caller, r.roles());
|
||||||
requireOwnRolesUnchanged(caller, id, user, 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)) {
|
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");
|
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");
|
throw error(HttpStatus.CONFLICT, "Email is already taken", "EMAIL_TAKEN");
|
||||||
}
|
}
|
||||||
if (r.roles() != null && r.roles().isEmpty()) {
|
if (r.roles() != null && r.roles().isEmpty()) {
|
||||||
@@ -151,7 +178,7 @@ public class AdminUserService {
|
|||||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
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());
|
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) {
|
public int resetPassword(Long id) {
|
||||||
@@ -159,9 +186,14 @@ public class AdminUserService {
|
|||||||
return adminAuthenticationService.resetAdminPassword((String) user.get("username"), (String) user.get("email"));
|
return adminAuthenticationService.resetAdminPassword((String) user.get("username"), (String) user.get("email"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private Map<String, Object> load(Long id) {
|
/** Another company's user is a 404 for staff; a super admin may open any. */
|
||||||
|
private Map<String, Object> load(Long id, User caller) {
|
||||||
Map<String, Object> user = get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID, id);
|
Map<String, Object> user = get(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID, id);
|
||||||
if (user == null || !"A".equals(user.get("type"))) throw error(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
|
Long visible = scope.scope(caller, null);
|
||||||
|
if (user == null || !"A".equals(user.get("type"))
|
||||||
|
|| visible != null && !visible.equals(user.get("companyId") instanceof Number n ? Long.valueOf(n.longValue()) : null)) {
|
||||||
|
throw error(HttpStatus.NOT_FOUND, "User not found", "USER_NOT_FOUND");
|
||||||
|
}
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,28 +224,24 @@ public class AdminUserService {
|
|||||||
|
|
||||||
/** The target admin; a non-super caller may not manage a super admin. */
|
/** The target admin; a non-super caller may not manage a super admin. */
|
||||||
private Map<String, Object> loadManaged(Long id, User caller) {
|
private Map<String, Object> loadManaged(Long id, User caller) {
|
||||||
Map<String, Object> user = load(id);
|
Map<String, Object> user = load(id, caller);
|
||||||
// idOf also reads a role services-system sent as a bare id
|
// 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)))) {
|
x -> Long.valueOf(SUPER_ADMIN_ROLE_ID).equals(AdminRoleService.idOf(x)))) {
|
||||||
throw superRequired("Only a super admin can manage a super admin");
|
throw superRequired("Only a super admin can manage a super admin");
|
||||||
}
|
}
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean isSuper(User caller) {
|
|
||||||
return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void requireSuperToGrant(User caller, List<AdminRoleRef> requested) {
|
private static void requireSuperToGrant(User caller, List<AdminRoleRef> requested) {
|
||||||
if (!isSuper(caller) && requested != null && requested.stream().anyMatch(r -> r.id() != null && r.id() == SUPER_ADMIN_ROLE_ID)) {
|
if (!AdminCompanyScope.isSuper(caller) && requested != null && requested.stream().anyMatch(r -> r.id() != null && r.id() == SUPER_ADMIN_ROLE_ID)) {
|
||||||
throw superRequired("Only a super admin can grant the super admin role");
|
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. */
|
/** A non-super admin may not change their own roles; hidden roles are not part of what they could change. */
|
||||||
private static void requireOwnRolesUnchanged(User caller, Long id, Map<String, Object> stored, List<AdminRoleRef> requested) {
|
private static void requireOwnRolesUnchanged(User caller, Long id, Map<String, Object> stored, List<AdminRoleRef> requested) {
|
||||||
if (requested == null || isSuper(caller) || caller.getId() == null || !caller.getId().equals(id)) return;
|
if (requested == null || AdminCompanyScope.isSuper(caller) || caller.getId() == null || !caller.getId().equals(id)) return;
|
||||||
Set<Long> current = new HashSet<>();
|
Set<Long> current = new HashSet<>();
|
||||||
if (stored.get("roles") instanceof List<?> l) {
|
if (stored.get("roles") instanceof List<?> l) {
|
||||||
for (Object o : 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");
|
if (!wanted.equals(current)) throw error(HttpStatus.FORBIDDEN, "You cannot change your own roles", "OWN_ROLES");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean hasSuperRole(List<AdminRoleRef> roles) {
|
||||||
|
return roles != null && roles.stream().anyMatch(x -> x.id() != null && x.id() == SUPER_ADMIN_ROLE_ID);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** services-system finds the user by email within one company (null company = super admins); null when free. */
|
||||||
|
private Map<String, Object> byEmail(String api, Long companyId, Object... vars) {
|
||||||
|
if (companyId == null) return get(api, vars);
|
||||||
|
Object[] all = java.util.Arrays.copyOf(vars, vars.length + 1);
|
||||||
|
all[vars.length] = companyId;
|
||||||
|
return get(api + "?companyId={companyId}", all);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String companyCode(Long companyId) {
|
||||||
|
Map<String, Object> company;
|
||||||
|
try {
|
||||||
|
company = get(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID, companyId);
|
||||||
|
} catch (org.springframework.web.client.HttpClientErrorException.NotFound e) {
|
||||||
|
company = null;
|
||||||
|
}
|
||||||
|
if (company == null || !(company.get("code") instanceof String code) || code.isBlank()) {
|
||||||
|
throw error(HttpStatus.BAD_REQUEST, "Company not found", "COMPANY_NOT_FOUND");
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The screens show the local part as username and the full sign-in name as loginName. */
|
||||||
|
private static Map<String, Object> present(Map<String, Object> user) {
|
||||||
|
if (user.get("username") instanceof String login) {
|
||||||
|
user.put("loginName", login);
|
||||||
|
int at = login.indexOf('@');
|
||||||
|
user.put("username", at < 0 ? login : login.substring(0, at));
|
||||||
|
}
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CodedResponseStatusException field(String reason, String code, String field) {
|
||||||
|
CodedResponseStatusException e = error(HttpStatus.BAD_REQUEST, reason, code);
|
||||||
|
e.getBody().setProperty("details", Map.of("field", field));
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
|
||||||
private static CodedResponseStatusException superRequired(String reason) {
|
private static CodedResponseStatusException superRequired(String reason) {
|
||||||
return error(HttpStatus.FORBIDDEN, reason, "SUPER_ADMIN_REQUIRED");
|
return error(HttpStatus.FORBIDDEN, reason, "SUPER_ADMIN_REQUIRED");
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-5
@@ -43,7 +43,7 @@ class AdminLoginSecurityControllerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void audit_passesFiltersAndPaging() throws Exception {
|
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));
|
.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")
|
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"))
|
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
|
||||||
@@ -53,21 +53,21 @@ class AdminLoginSecurityControllerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void audit_defaultsToFirstPageOfTwenty() throws Exception {
|
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());
|
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
|
@Test
|
||||||
void locked_returnsList() throws Exception {
|
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"));
|
mvc.perform(get("/api/admin/login-security/locked")).andExpect(status().isOk()).andExpect(jsonPath("$[0].username").value("sales1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void unlock_returns204() throws Exception {
|
void unlock_returns204() throws Exception {
|
||||||
mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent());
|
mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent());
|
||||||
verify(security).unlock("sales1");
|
verify(security).unlock("sales1", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
+3
-3
@@ -46,7 +46,7 @@ class AdminUserControllerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void list_passesParamsAndReturnsPageShape() throws Exception {
|
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));
|
.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")
|
mvc.perform(get("/api/admin/users").param("q", "ali").param("enabled", "true").param("page", "1")
|
||||||
.param("size", "5").param("sortBy", "name").param("sortDir", "desc"))
|
.param("size", "5").param("sortBy", "name").param("sortDir", "desc"))
|
||||||
@@ -57,9 +57,9 @@ class AdminUserControllerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void list_legacySearchKeyActsAsQ() throws Exception {
|
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());
|
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
|
@Test
|
||||||
|
|||||||
+5
-4
@@ -64,7 +64,7 @@ class AdminAclServiceTest {
|
|||||||
module(ROOT, "BO_ROOT", null, 1),
|
module(ROOT, "BO_ROOT", null, 1),
|
||||||
module(USERS, "BO_USERS", ROOT, 1, 4),
|
module(USERS, "BO_USERS", ROOT, 1, 4),
|
||||||
module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5));
|
module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5));
|
||||||
caller(5);
|
caller(1, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
@AfterEach
|
@AfterEach
|
||||||
@@ -198,20 +198,21 @@ class AdminAclServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void update_nonSuperCallerEditingARoleTheyHoldIsRefused() {
|
void update_nonSuperCallerEditingARoleTheyHoldIsRefused() {
|
||||||
caller(5, 2); // role 2 is attached to every admin and is ignored
|
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();
|
verifyNothingChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void update_ownRoleIsRefusedEvenWhenAnotherCallerRoleGrantsBoRoles() {
|
void update_ownRoleIsRefusedEvenWhenAnotherCallerRoleGrantsBoRoles() {
|
||||||
caller(5, 6, 2);
|
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();
|
verifyNothingChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void update_ownRoleIsRefusedEvenWhenTheChangeKeepsBoRoles() {
|
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();
|
verifyNothingChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-5
@@ -49,7 +49,8 @@ class AdminInterestServiceTest {
|
|||||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||||
User caller = new User();
|
User caller = new User();
|
||||||
caller.setUsername("boss");
|
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(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||||
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||||
@@ -69,7 +70,7 @@ class AdminInterestServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void stubList(Map<String, Object>... rows) {
|
private void stubList(Map<String, Object>... 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<String, Object> saved() {
|
private Map<String, Object> saved() {
|
||||||
@@ -95,10 +96,10 @@ class AdminInterestServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void createSendsTrimmedActiveInterestForTheCallersCompany() {
|
void createSendsTrimmedActiveInterest() {
|
||||||
service.create(new AdminInterestRequest(" Kitchen appliances ", null, null));
|
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");
|
.containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,7 +129,7 @@ class AdminInterestServiceTest {
|
|||||||
|
|
||||||
service.update(2L, new AdminInterestRequest(null, false, null));
|
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);
|
.containsEntry("active", false).containsEntry("sortOrder", 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
@@ -42,6 +42,7 @@ class AdminLoginSecurityServiceAuditChangesTest {
|
|||||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||||
User caller = new User();
|
User caller = new User();
|
||||||
caller.setUsername("boss");
|
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);
|
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
@@ -54,6 +54,7 @@ class AdminLoginSecurityServiceTest {
|
|||||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||||
User caller = new User();
|
User caller = new User();
|
||||||
caller.setUsername("boss");
|
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);
|
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
@@ -50,6 +50,7 @@ class AdminRoleServiceTest {
|
|||||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||||
User caller = new User();
|
User caller = new User();
|
||||||
caller.setUsername("boss");
|
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);
|
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||||
stubRoles(stored());
|
stubRoles(stored());
|
||||||
}
|
}
|
||||||
|
|||||||
+236
@@ -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<HttpReqRespUtils> 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<String, Object> 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<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq("/counter/interest/save"), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
assertThat((Map<String, Object>) 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<String, Object> postedAuditBody() {
|
||||||
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq("/loginSecurity/audit"), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
return (Map<String, Object>) 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<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq("/loginSecurity/unlock"), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
assertThat((Map<String, Object>) body.getValue()).containsEntry("companyId", 7L).containsEntry("username", "ann@ins");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unlock_superWithNoCompanySendsNone() {
|
||||||
|
superAdmin();
|
||||||
|
security.unlock("ann@ins", null);
|
||||||
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq("/loginSecurity/unlock"), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
assertThat((Map<String, Object>) 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-2
@@ -53,11 +53,12 @@ class AdminUserServiceAuditChangesTest {
|
|||||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||||
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
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)))
|
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"))));
|
.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/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/findByEmailAndCompanyId/{email}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).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/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()))
|
when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any()))
|
||||||
.thenAnswer(i -> {
|
.thenAnswer(i -> {
|
||||||
Map<String, Object> saved = new HashMap<>((Map<String, Object>) i.getArgument(2));
|
Map<String, Object> saved = new HashMap<>((Map<String, Object>) i.getArgument(2));
|
||||||
@@ -87,6 +88,7 @@ class AdminUserServiceAuditChangesTest {
|
|||||||
u.put("email", "sam@x.com");
|
u.put("email", "sam@x.com");
|
||||||
u.put("enabled", enabled);
|
u.put("enabled", enabled);
|
||||||
u.put("type", "A");
|
u.put("type", "A");
|
||||||
|
u.put("companyId", 7L);
|
||||||
u.put("roles", List.of(roles));
|
u.put("roles", List.of(roles));
|
||||||
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
|
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
|
||||||
}
|
}
|
||||||
|
|||||||
+345
@@ -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<AdminRoleRef> SALES = List.of(new AdminRoleRef(4L, "ROLE_SALES"));
|
||||||
|
private static final List<AdminRoleRef> SUPER = List.of(new AdminRoleRef(1L, "ROLE_SUPER_ADMIN"));
|
||||||
|
|
||||||
|
private RestTemplateCustomUtil rest;
|
||||||
|
private AdminAuthenticationService auth;
|
||||||
|
private AdminUserService service;
|
||||||
|
private MockedStatic<HttpReqRespUtils> 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<String, Object> m = new HashMap<>((Map<String, Object>) i.getArgument(2)); m.putIfAbsent("id", 99L); return ResponseEntity.ok(m); });
|
||||||
|
staff(7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void close() { http.close(); }
|
||||||
|
|
||||||
|
private static Map<String, Object> fullRole(long id, String name) {
|
||||||
|
Map<String, Object> 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<Role> 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<String, Object> row(long id, String username, Long companyId) {
|
||||||
|
Map<String, Object> 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<String, Object>... rows) {
|
||||||
|
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||||
|
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(rows))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubFind(Map<String, Object> row) {
|
||||||
|
when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(row.get("id")))).thenReturn(ResponseEntity.ok(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> sentProperty() {
|
||||||
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
return (Map<String, Object>) ((Map<String, Object>) body.getValue()).get("property");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> savedBody() {
|
||||||
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||||
|
return (Map<String, Object>) body.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AdminUserRequest create(String username, List<AdminRoleRef> 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<Map<String, Object>> rows = (List<Map<String, Object>>) 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<String, Object> 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<String, Object> 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-11
@@ -41,8 +41,8 @@ class AdminUserServiceTest {
|
|||||||
private static final String SAVE = "/user/save";
|
private static final String SAVE = "/user/save";
|
||||||
private static final String PAGE = "/user/findByPropertyAndPageable";
|
private static final String PAGE = "/user/findByPropertyAndPageable";
|
||||||
private static final String BY_USERNAME = "/user/findByUsername/{username}";
|
private static final String BY_USERNAME = "/user/findByUsername/{username}";
|
||||||
private static final String BY_EMAIL = "/user/findByEmail/{email}";
|
private static final String BY_EMAIL = "/user/findByEmailAndCompanyId/{email}?companyId={companyId}";
|
||||||
private static final String BY_EMAIL_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
|
private static final String BY_EMAIL_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}";
|
||||||
|
|
||||||
private RestTemplateCustomUtil rest;
|
private RestTemplateCustomUtil rest;
|
||||||
private AdminAuthenticationService auth;
|
private AdminAuthenticationService auth;
|
||||||
@@ -65,6 +65,8 @@ class AdminUserServiceTest {
|
|||||||
branch.setId(3L);
|
branch.setId(3L);
|
||||||
caller.setBranch(branch);
|
caller.setBranch(branch);
|
||||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
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)))
|
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"))));
|
.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();
|
User u = new User();
|
||||||
u.setId(1L);
|
u.setId(1L);
|
||||||
u.setUsername("boss");
|
u.setUsername("boss");
|
||||||
u.setCompanyId(7L);
|
u.setCompanyId(null);
|
||||||
LocationHierarchy b = new LocationHierarchy();
|
LocationHierarchy b = new LocationHierarchy();
|
||||||
b.setId(3L);
|
b.setId(3L);
|
||||||
u.setBranch(b);
|
u.setBranch(b);
|
||||||
@@ -112,6 +114,7 @@ class AdminUserServiceTest {
|
|||||||
m.put("email", email);
|
m.put("email", email);
|
||||||
m.put("enabled", enabled);
|
m.put("enabled", enabled);
|
||||||
m.put("type", "A");
|
m.put("type", "A");
|
||||||
|
m.put("companyId", 7L);
|
||||||
m.put("password", "$2a$secret");
|
m.put("password", "$2a$secret");
|
||||||
m.put("passwordSecondary", "$2a$secret2");
|
m.put("passwordSecondary", "$2a$secret2");
|
||||||
m.put("passwordEmrm", "$2a$secret3");
|
m.put("passwordEmrm", "$2a$secret3");
|
||||||
@@ -139,9 +142,9 @@ class AdminUserServiceTest {
|
|||||||
private void stubNoDuplicates() {
|
private void stubNoDuplicates() {
|
||||||
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any()))
|
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any()))
|
||||||
.thenReturn(ResponseEntity.ok().build());
|
.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());
|
.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());
|
.thenReturn(ResponseEntity.ok().build());
|
||||||
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
||||||
@@ -248,7 +251,7 @@ class AdminUserServiceTest {
|
|||||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||||
Map<String, Object> saved = (Map<String, Object>) body.getValue();
|
Map<String, Object> saved = (Map<String, Object>) 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("name", "New").containsEntry("enabled", true).containsEntry("status", "Y")
|
||||||
.containsEntry("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L)
|
.containsEntry("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L)
|
||||||
.containsEntry("createBy", "boss").containsEntry("doneBy", "boss");
|
.containsEntry("createBy", "boss").containsEntry("doneBy", "boss");
|
||||||
@@ -263,7 +266,7 @@ class AdminUserServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void create_duplicateUsername_is409UsernameTaken() {
|
void create_duplicateUsername_is409UsernameTaken() {
|
||||||
stubNoDuplicates();
|
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")));
|
.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");
|
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(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||||
@@ -274,7 +277,7 @@ class AdminUserServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void create_duplicateEmail_is409EmailTaken() {
|
void create_duplicateEmail_is409EmailTaken() {
|
||||||
stubNoDuplicates();
|
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")));
|
.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");
|
assertCoded(() -> service.create(req("N", "n", "dup@x.com", ROLES)), HttpStatus.CONFLICT, "EMAIL_TAKEN");
|
||||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||||
@@ -379,7 +382,7 @@ class AdminUserServiceTest {
|
|||||||
void update_emailUsedByAnotherUser_is409() {
|
void update_emailUsedByAnotherUser_is409() {
|
||||||
stubNoDuplicates();
|
stubNoDuplicates();
|
||||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
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")));
|
.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)),
|
assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, "taken@x.com", null, null)),
|
||||||
HttpStatus.CONFLICT, "EMAIL_TAKEN");
|
HttpStatus.CONFLICT, "EMAIL_TAKEN");
|
||||||
@@ -399,7 +402,7 @@ class AdminUserServiceTest {
|
|||||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||||
stubSave(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));
|
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<Object> body = ArgumentCaptor.forClass(Object.class);
|
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("email", "a@x.com");
|
assertThat((Map<String, Object>) body.getValue()).containsEntry("email", "a@x.com");
|
||||||
@@ -506,8 +509,10 @@ class AdminUserServiceTest {
|
|||||||
void superCaller_canGrantSuperAdmin() {
|
void superCaller_canGrantSuperAdmin() {
|
||||||
stubNoDuplicates();
|
stubNoDuplicates();
|
||||||
callerIsSuper();
|
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"));
|
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());
|
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user