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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-30 20:29:34 +08:00
1 parent 00ce47bc49
commit de2ae63cea
20 files changed
+795 -82

No files matched your search

@@ -43,7 +43,7 @@ class AdminLoginSecurityControllerTest {
@Test
void audit_passesFiltersAndPaging() throws Exception {
when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5))
when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5, null))
.thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6));
mvc.perform(get("/api/admin/login-security/audit").param("username", "sales1").param("event", "LOCKED")
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
@@ -53,21 +53,21 @@ class AdminLoginSecurityControllerTest {
@Test
void audit_defaultsToFirstPageOfTwenty() throws Exception {
when(security.audit(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
when(security.audit(null, null, null, null, 0, 20, null)).thenReturn(Map.of("content", List.of()));
mvc.perform(get("/api/admin/login-security/audit")).andExpect(status().isOk());
verify(security).audit(null, null, null, null, 0, 20);
verify(security).audit(null, null, null, null, 0, 20, null);
}
@Test
void locked_returnsList() throws Exception {
when(security.locked()).thenReturn(List.of(Map.of("username", "sales1", "failures", 5)));
when(security.locked(null)).thenReturn(List.of(Map.of("username", "sales1", "failures", 5)));
mvc.perform(get("/api/admin/login-security/locked")).andExpect(status().isOk()).andExpect(jsonPath("$[0].username").value("sales1"));
}
@Test
void unlock_returns204() throws Exception {
mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent());
verify(security).unlock("sales1");
verify(security).unlock("sales1", null);
}
@Test
@@ -46,7 +46,7 @@ class AdminUserControllerTest {
@Test
void list_passesParamsAndReturnsPageShape() throws Exception {
when(users.list("ali", "true", 1, 5, "name", "desc"))
when(users.list("ali", "true", 1, 5, "name", "desc", null))
.thenReturn(Map.of("content", List.of(Map.of("id", 1)), "totalElements", 6L));
mvc.perform(get("/api/admin/users").param("q", "ali").param("enabled", "true").param("page", "1")
.param("size", "5").param("sortBy", "name").param("sortDir", "desc"))
@@ -57,9 +57,9 @@ class AdminUserControllerTest {
@Test
void list_legacySearchKeyActsAsQ() throws Exception {
when(users.list("bob", null, 0, 20, null, null)).thenReturn(Map.of("content", List.of()));
when(users.list("bob", null, 0, 20, null, null, null)).thenReturn(Map.of("content", List.of()));
mvc.perform(get("/api/admin/users").param("searchKey", "bob")).andExpect(status().isOk());
verify(users).list("bob", null, 0, 20, null, null);
verify(users).list("bob", null, 0, 20, null, null, null);
}
@Test
@@ -64,7 +64,7 @@ class AdminAclServiceTest {
module(ROOT, "BO_ROOT", null, 1),
module(USERS, "BO_USERS", ROOT, 1, 4),
module(ROLES, "BO_ROLES", Map.of("id", ROOT, "name", "BO_ROOT"), 1, 5));
caller(5);
caller(1, 5);
}
@AfterEach
@@ -198,20 +198,21 @@ class AdminAclServiceTest {
@Test
void update_nonSuperCallerEditingARoleTheyHoldIsRefused() {
caller(5, 2); // role 2 is attached to every admin and is ignored
assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "OWN_ROLE");
assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
verifyNothingChanged();
}
@Test
void update_ownRoleIsRefusedEvenWhenAnotherCallerRoleGrantsBoRoles() {
caller(5, 6, 2);
assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "OWN_ROLE");
assertCoded(() -> service.updateGrants(5L, List.of()), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
verifyNothingChanged();
}
@Test
void update_ownRoleIsRefusedEvenWhenTheChangeKeepsBoRoles() {
assertCoded(() -> service.updateGrants(5L, List.of(ROLES, USERS)), HttpStatus.FORBIDDEN, "OWN_ROLE");
caller(5);
assertCoded(() -> service.updateGrants(5L, List.of(ROLES, USERS)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
verifyNothingChanged();
}
@@ -49,7 +49,8 @@ class AdminInterestServiceTest {
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
caller.setCompanyId(5L);
caller.setCompanyId(null);
{ com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); }
when(auth.loadUserByToken("tok")).thenReturn(caller);
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
@@ -69,7 +70,7 @@ class AdminInterestServiceTest {
}
private void stubList(Map<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() {
@@ -95,10 +96,10 @@ class AdminInterestServiceTest {
}
@Test
void createSendsTrimmedActiveInterestForTheCallersCompany() {
void createSendsTrimmedActiveInterest() {
service.create(new AdminInterestRequest(" Kitchen appliances ", null, null));
assertThat(saved()).containsEntry("companyId", 5L).containsEntry("name", "Kitchen appliances")
assertThat(saved()).doesNotContainKey("companyId").containsEntry("name", "Kitchen appliances")
.containsEntry("active", true).containsEntry("sortOrder", 0).doesNotContainKey("id");
}
@@ -128,7 +129,7 @@ class AdminInterestServiceTest {
service.update(2L, new AdminInterestRequest(null, false, null));
assertThat(saved()).containsEntry("id", 2L).containsEntry("companyId", 5L).containsEntry("name", "Cookware")
assertThat(saved()).containsEntry("id", 2L).doesNotContainKey("companyId").containsEntry("name", "Cookware")
.containsEntry("active", false).containsEntry("sortOrder", 3);
}
@@ -42,6 +42,7 @@ class AdminLoginSecurityServiceAuditChangesTest {
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
{ com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); }
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
@@ -54,6 +54,7 @@ class AdminLoginSecurityServiceTest {
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
{ com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); }
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
@@ -50,6 +50,7 @@ class AdminRoleServiceTest {
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
{ com.solvway.core.model.Role r = new com.solvway.core.model.Role(); r.setId(1L); caller.setRoles(new java.util.ArrayList<>(java.util.List.of(r))); }
when(auth.loadUserByToken("tok")).thenReturn(caller);
stubRoles(stored());
}
@@ -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);
}
}
@@ -53,11 +53,12 @@ class AdminUserServiceAuditChangesTest {
when(auth.loadUserByToken("tok")).thenReturn(caller);
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins")));
when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(List.of(role(4, "ROLE_SALES"), role(5, "ROLE_OPS"), role(6, "ROLE_ACCOUNTS"))));
when(rest.getForEntity(eq("/user/findByUsername/{username}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq("/user/findByEmail/{email}"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq("/user/findByEmailAndIdNot/{email}/{id}"), any(ParameterizedTypeReference.class), any(), any())).thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq("/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}"), any(ParameterizedTypeReference.class), any(Object[].class))).thenReturn(ResponseEntity.ok().build());
when(rest.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> {
Map<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("enabled", enabled);
u.put("type", "A");
u.put("companyId", 7L);
u.put("roles", List.of(roles));
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
}
@@ -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());
}
}
@@ -41,8 +41,8 @@ class AdminUserServiceTest {
private static final String SAVE = "/user/save";
private static final String PAGE = "/user/findByPropertyAndPageable";
private static final String BY_USERNAME = "/user/findByUsername/{username}";
private static final String BY_EMAIL = "/user/findByEmail/{email}";
private static final String BY_EMAIL_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
private static final String BY_EMAIL = "/user/findByEmailAndCompanyId/{email}?companyId={companyId}";
private static final String BY_EMAIL_NOT = "/user/findByEmailAndCompanyIdAndIdNot/{email}/{id}?companyId={companyId}";
private RestTemplateCustomUtil rest;
private AdminAuthenticationService auth;
@@ -65,6 +65,8 @@ class AdminUserServiceTest {
branch.setId(3L);
caller.setBranch(branch);
when(auth.loadUserByToken("tok")).thenReturn(caller);
when(rest.getForEntity(eq("/company/findById/{id}"), any(ParameterizedTypeReference.class), any()))
.thenAnswer(i -> ResponseEntity.ok(Map.of("id", (Object) i.getArgument(2), "code", "ins")));
when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(List.of(fullRole(1, "ROLE_SUPER_ADMIN"), fullRole(4, "ROLE_SALES"), fullRole(5, "ROLE_OPS"))));
}
@@ -86,7 +88,7 @@ class AdminUserServiceTest {
User u = new User();
u.setId(1L);
u.setUsername("boss");
u.setCompanyId(7L);
u.setCompanyId(null);
LocationHierarchy b = new LocationHierarchy();
b.setId(3L);
u.setBranch(b);
@@ -112,6 +114,7 @@ class AdminUserServiceTest {
m.put("email", email);
m.put("enabled", enabled);
m.put("type", "A");
m.put("companyId", 7L);
m.put("password", "$2a$secret");
m.put("passwordSecondary", "$2a$secret2");
m.put("passwordEmrm", "$2a$secret3");
@@ -139,9 +142,9 @@ class AdminUserServiceTest {
private void stubNoDuplicates() {
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any()))
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any(Object[].class)))
.thenReturn(ResponseEntity.ok().build());
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any()))
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(Object[].class)))
.thenReturn(ResponseEntity.ok().build());
when(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
@@ -248,7 +251,7 @@ class AdminUserServiceTest {
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
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("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L)
.containsEntry("createBy", "boss").containsEntry("doneBy", "boss");
@@ -263,7 +266,7 @@ class AdminUserServiceTest {
@Test
void create_duplicateUsername_is409UsernameTaken() {
stubNoDuplicates();
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup")))
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup@ins")))
.thenReturn(ResponseEntity.ok(row(2, "X", "dup", "x@x.com", true, "R")));
assertCoded(() -> service.create(req("N", "dup", "n@x.com", ROLES)), HttpStatus.CONFLICT, "USERNAME_TAKEN");
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
@@ -274,7 +277,7 @@ class AdminUserServiceTest {
@Test
void create_duplicateEmail_is409EmailTaken() {
stubNoDuplicates();
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com")))
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com"), eq(7L)))
.thenReturn(ResponseEntity.ok(row(2, "X", "x", "dup@x.com", true, "R")));
assertCoded(() -> service.create(req("N", "n", "dup@x.com", ROLES)), HttpStatus.CONFLICT, "EMAIL_TAKEN");
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
@@ -379,7 +382,7 @@ class AdminUserServiceTest {
void update_emailUsedByAnotherUser_is409() {
stubNoDuplicates();
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L)))
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L), eq(7L)))
.thenReturn(ResponseEntity.ok(row(2, "X", "x", "taken@x.com", true, "R")));
assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, "taken@x.com", null, null)),
HttpStatus.CONFLICT, "EMAIL_TAKEN");
@@ -399,7 +402,7 @@ class AdminUserServiceTest {
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
stubSave(row(5, "A", "a", "a@x.com", true, "R"));
service.update(5L, new AdminUserRequest(null, null, null, "", null, null));
verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any());
verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(Object[].class));
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
assertThat((Map<String, Object>) body.getValue()).containsEntry("email", "a@x.com");
@@ -506,8 +509,10 @@ class AdminUserServiceTest {
void superCaller_canGrantSuperAdmin() {
stubNoDuplicates();
callerIsSuper();
when(rest.getForEntity(eq("/user/findByEmailAndCompanyId/{email}"), any(ParameterizedTypeReference.class), any(Object[].class)))
.thenReturn(ResponseEntity.ok().build());
stubSave(row(20, "N", "u", "e@x.com", true, "R"));
service.create(req("N", "u", "e@x.com", SUPER));
service.create(new AdminUserRequest("N", null, "u", "e@x.com", null, SUPER, PW, PW, null, true));
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
}