feat(mobile-api): admin users API (list, create, edit, deactivate, reset password)
New users get a temporary password by email and the creating admin's company. Self-deactivation and super-admin changes by non-super admins are refused. services-system: saving a user no longer cascades into role rows. Local seed: dev admin on the GLOBAL branch (id 0 does not exist). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
9f22837a00
commit
f5d1b6d032
11 files changed
+1038
-3
No files matched your search
+563
@@ -0,0 +1,563 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.LocationHierarchy;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminUserServiceTest {
|
||||
|
||||
private static final String FIND_BY_ID = "/user/findById/{id}";
|
||||
private static final String SAVE = "/user/save";
|
||||
private static final String PAGE = "/user/findByPropertyAndPageable";
|
||||
private static final String BY_USERNAME = "/user/findByUsername/{username}";
|
||||
private static final String BY_EMAIL = "/user/findByEmail/{email}";
|
||||
private static final String BY_EMAIL_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
|
||||
private static final String UPDATE_PWD = "/user/updateUserPassword";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminUserService service;
|
||||
private MockedStatic<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");
|
||||
User caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setUsername("boss");
|
||||
caller.setCompanyId(7L);
|
||||
LocationHierarchy branch = new LocationHierarchy();
|
||||
branch.setId(3L);
|
||||
caller.setBranch(branch);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.getForEntity(eq("/role/findAll"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(fullRole(1, "ROLE_SUPER_ADMIN"), fullRole(4, "ROLE_SALES"), fullRole(5, "ROLE_OPS"))));
|
||||
}
|
||||
|
||||
private static Map<String, Object> fullRole(long id, String name) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("level", 2);
|
||||
m.put("tracekey", "tk" + id);
|
||||
m.put("createBy", "sys");
|
||||
return m;
|
||||
}
|
||||
|
||||
private void callerIsSuper() {
|
||||
Role r = new Role();
|
||||
r.setId(1L);
|
||||
when(auth.loadUserByToken("tok")).thenAnswer(i -> {
|
||||
User u = new User();
|
||||
u.setId(1L);
|
||||
u.setUsername("boss");
|
||||
u.setCompanyId(7L);
|
||||
LocationHierarchy b = new LocationHierarchy();
|
||||
b.setId(3L);
|
||||
u.setBranch(b);
|
||||
u.setRoles(List.of(r));
|
||||
return u;
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, Object> superAdminRow(long id) {
|
||||
Map<String, Object> m = row(id, "Root", "root", "r@x.com", true);
|
||||
m.put("roles", List.of(fullRole(1, "ROLE_SUPER_ADMIN")));
|
||||
return m;
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private Map<String, Object> row(long id, String name, String username, String email, boolean enabled, String... roles) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("username", username);
|
||||
m.put("email", email);
|
||||
m.put("enabled", enabled);
|
||||
m.put("type", "A");
|
||||
m.put("password", "$2a$secret");
|
||||
m.put("passwordSecondary", "$2a$secret2");
|
||||
m.put("passwordEmrm", "$2a$secret3");
|
||||
List<Map<String, Object>> rs = new ArrayList<>();
|
||||
for (String r : roles) rs.add(new HashMap<>(Map.of("id", 10L, "name", r)));
|
||||
m.put("roles", rs);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stubPage(Map<String, Object>... rows) {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(rows))));
|
||||
}
|
||||
|
||||
private void stubFind(long id, Map<String, Object> row) {
|
||||
when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(id)))
|
||||
.thenReturn(ResponseEntity.ok(row));
|
||||
}
|
||||
|
||||
private void stubSave(Map<String, Object> saved) {
|
||||
when(rest.postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(saved));
|
||||
}
|
||||
|
||||
private void stubNoDuplicates() {
|
||||
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any()))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
when(auth.resetAdminPassword(anyString(), anyString())).thenReturn(1);
|
||||
}
|
||||
|
||||
private AdminUserRequest req(String name, String username, String email, List<AdminRoleRef> roles) {
|
||||
return new AdminUserRequest(name, null, username, email, null, roles);
|
||||
}
|
||||
|
||||
private static final List<AdminRoleRef> ROLES = List.of(new AdminRoleRef(4L, "ROLE_SALES"));
|
||||
|
||||
private static void assertCoded(Runnable r, HttpStatus status, String code) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getCode()).isEqualTo(code);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- list ----
|
||||
|
||||
@Test
|
||||
void list_asksDownstreamForAdminsOnly() {
|
||||
stubPage(row(1, "A", "a", "a@x.com", true, "R"));
|
||||
service.list(null, null, 0, 20, null, null);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
Map<String, Object> sent = (Map<String, Object>) body.getValue();
|
||||
assertThat((Map<String, Object>) sent.get("property")).containsEntry("type", "A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_searchesNameUsernameEmailCaseInsensitive() {
|
||||
stubPage(row(1, "Alice Tan", "alice", "a@x.com", true, "R"),
|
||||
row(2, "Bob", "bobby", "b@x.com", true, "R"),
|
||||
row(3, "Cy", "cy", "CARL@x.com", true, "R"));
|
||||
assertThat(names(service.list("ALI", null, 0, 20, null, null))).containsExactly("Alice Tan");
|
||||
assertThat(names(service.list("bobb", null, 0, 20, null, null))).containsExactly("Bob");
|
||||
assertThat(names(service.list("carl", null, 0, 20, null, null))).containsExactly("Cy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_filtersByEnabled() {
|
||||
stubPage(row(1, "On", "on", "o@x.com", true, "R"), row(2, "Off", "off", "f@x.com", false, "R"));
|
||||
assertThat(names(service.list(null, "false", 0, 20, null, null))).containsExactly("Off");
|
||||
assertThat(names(service.list(null, "true", 0, 20, null, null))).containsExactly("On");
|
||||
assertThat(names(service.list(null, null, 0, 20, null, null))).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_sortsAndPagesOnTheServer() {
|
||||
stubPage(row(1, "Cc", "c", "c@x.com", true, "R"), row(2, "Aa", "a", "a@x.com", true, "R"),
|
||||
row(3, "Bb", "b", "b@x.com", true, "R"));
|
||||
Map<String, Object> p0 = service.list(null, null, 0, 2, "name", "asc");
|
||||
assertThat(names(p0)).containsExactly("Aa", "Bb");
|
||||
assertThat(p0).containsEntry("totalElements", 3L).containsEntry("totalPages", 2)
|
||||
.containsEntry("number", 0).containsEntry("size", 2);
|
||||
assertThat(names(service.list(null, null, 1, 2, "name", "asc"))).containsExactly("Cc");
|
||||
assertThat(names(service.list(null, null, 0, 3, "username", "desc"))).containsExactly("Cc", "Bb", "Aa");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_neverReturnsPasswordHashes() {
|
||||
stubPage(row(1, "A", "a", "a@x.com", true, "R"));
|
||||
Map<String, Object> first = ((List<Map<String, Object>>) service.list(null, null, 0, 20, null, null).get("content")).get(0);
|
||||
assertThat(first).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm");
|
||||
}
|
||||
|
||||
private List<String> names(Map<String, Object> page) {
|
||||
return ((List<Map<String, Object>>) page.get("content")).stream().map(m -> (String) m.get("name")).toList();
|
||||
}
|
||||
|
||||
// ---- get ----
|
||||
|
||||
@Test
|
||||
void findById_returnsAdminWithoutPasswords() {
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
assertThat(service.findById(5L)).containsEntry("username", "a")
|
||||
.doesNotContainKeys("password", "passwordSecondary", "passwordEmrm");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findById_unknownOrNonAdmin_is404() {
|
||||
when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
assertCoded(() -> service.findById(8L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND");
|
||||
Map<String, Object> member = row(9, "M", "m", "m@x.com", true, "R");
|
||||
member.put("type", "M");
|
||||
stubFind(9, member);
|
||||
assertCoded(() -> service.findById(9L), HttpStatus.NOT_FOUND, "USER_NOT_FOUND");
|
||||
}
|
||||
|
||||
// ---- create ----
|
||||
|
||||
@Test
|
||||
void create_savesActiveAdminWithCallerCompanyThenSendsTemporaryPassword() {
|
||||
stubNoDuplicates();
|
||||
stubSave(row(20, "New", "newbie", "n@x.com", true, "ROLE_SALES"));
|
||||
AdminUserRequest r = new AdminUserRequest("New", "Guy", "newbie", "n@x.com", false, ROLES);
|
||||
|
||||
Map<String, Object> out = service.create(r);
|
||||
|
||||
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")
|
||||
.containsEntry("name", "New").containsEntry("enabled", true).containsEntry("status", "Y")
|
||||
.containsEntry("type", "A").containsEntry("login", "N").containsEntry("companyId", 7L)
|
||||
.containsEntry("createBy", "boss").containsEntry("doneBy", "boss");
|
||||
assertThat(saved).doesNotContainKey("id").doesNotContainKey("password");
|
||||
assertThat((Map<String, Object>) saved.get("branch")).containsEntry("id", 3L);
|
||||
assertThat(((List<Map<String, Object>>) saved.get("roles")).get(0)).containsEntry("id", 4L);
|
||||
verify(auth).resetAdminPassword("newbie", "n@x.com");
|
||||
assertThat(out).containsEntry("id", 20L).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_duplicateUsername_is409UsernameTaken() {
|
||||
stubNoDuplicates();
|
||||
when(rest.getForEntity(eq(BY_USERNAME), any(ParameterizedTypeReference.class), eq("dup")))
|
||||
.thenReturn(ResponseEntity.ok(row(2, "X", "dup", "x@x.com", true, "R")));
|
||||
assertCoded(() -> service.create(req("N", "dup", "n@x.com", ROLES)), HttpStatus.CONFLICT, "USERNAME_TAKEN");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_duplicateEmail_is409EmailTaken() {
|
||||
stubNoDuplicates();
|
||||
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("dup@x.com")))
|
||||
.thenReturn(ResponseEntity.ok(row(2, "X", "x", "dup@x.com", true, "R")));
|
||||
assertCoded(() -> service.create(req("N", "n", "dup@x.com", ROLES)), HttpStatus.CONFLICT, "EMAIL_TAKEN");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_missingRequiredFields_is400() {
|
||||
assertCoded(() -> service.create(req("", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(req("N", " ", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(req("N", "u", null, ROLES)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", List.of())), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", null)), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_callerWithoutBranch_is400BranchRequired() {
|
||||
stubNoDuplicates();
|
||||
User noBranch = new User();
|
||||
noBranch.setCompanyId(7L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(noBranch);
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_REQUEST, "BRANCH_REQUIRED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_tempPasswordNotSent_is502AfterUserCreated() {
|
||||
stubNoDuplicates();
|
||||
stubSave(row(20, "N", "u", "e@x.com", true, "R"));
|
||||
when(auth.resetAdminPassword("u", "e@x.com")).thenReturn(0);
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.BAD_GATEWAY, "TEMP_PASSWORD_NOT_SENT");
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_saveReturnsNoId_isServerError() {
|
||||
stubNoDuplicates();
|
||||
stubSave(new HashMap<>());
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", ROLES)), HttpStatus.INTERNAL_SERVER_ERROR, "SAVE_FAILED");
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
}
|
||||
|
||||
// ---- update ----
|
||||
|
||||
@Test
|
||||
void update_changesOnlyNameEmailRolesEnabled() {
|
||||
stubNoDuplicates();
|
||||
Map<String, Object> stored = row(5, "Old", "keep", "old@x.com", true, "R");
|
||||
stored.put("companyId", 7L);
|
||||
stored.put("login", "Y");
|
||||
stubFind(5, stored);
|
||||
stubSave(row(5, "New", "keep", "new@x.com", true, "ROLE_SALES"));
|
||||
AdminUserRequest r = new AdminUserRequest("New", null, "hacker", "new@x.com", true, ROLES);
|
||||
|
||||
service.update(5L, r);
|
||||
|
||||
ArgumentCaptor<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("id", 5L).containsEntry("name", "New").containsEntry("email", "new@x.com")
|
||||
.containsEntry("username", "keep").containsEntry("type", "A").containsEntry("companyId", 7L)
|
||||
.containsEntry("login", "Y").containsEntry("enabled", true).containsEntry("status", "Y");
|
||||
assertThat(((List<Map<String, Object>>) saved.get("roles")).get(0)).containsEntry("id", 4L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_deactivate_setsEnabledFalseAndStatusN() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
stubSave(row(5, "A", "a", "a@x.com", false, "R"));
|
||||
service.update(5L, new AdminUserRequest(null, null, null, null, false, null));
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("enabled", false).containsEntry("status", "N");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_selfDeactivation_is400() {
|
||||
stubFind(1, row(1, "Boss", "boss", "b@x.com", true, "R"));
|
||||
assertCoded(() -> service.update(1L, new AdminUserRequest(null, null, null, null, false, null)),
|
||||
HttpStatus.BAD_REQUEST, "SELF_DEACTIVATION");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_emailUsedByAnotherUser_is409() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
when(rest.getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), eq("taken@x.com"), eq(5L)))
|
||||
.thenReturn(ResponseEntity.ok(row(2, "X", "x", "taken@x.com", true, "R")));
|
||||
assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, "taken@x.com", null, null)),
|
||||
HttpStatus.CONFLICT, "EMAIL_TAKEN");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_unknownUser_is404() {
|
||||
when(rest.getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), eq(8L)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
assertCoded(() -> service.update(8L, req("N", null, "e@x.com", ROLES)), HttpStatus.NOT_FOUND, "USER_NOT_FOUND");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_blankEmail_skipsDuplicateCheckAndKeepsStoredEmail() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
stubSave(row(5, "A", "a", "a@x.com", true, "R"));
|
||||
service.update(5L, new AdminUserRequest(null, null, null, "", null, null));
|
||||
verify(rest, never()).getForEntity(eq(BY_EMAIL_NOT), any(ParameterizedTypeReference.class), any(), any());
|
||||
ArgumentCaptor<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");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_loadsCallerOnce() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
stubSave(row(5, "A", "a", "a@x.com", false, "R"));
|
||||
service.update(5L, new AdminUserRequest("B", null, null, null, false, null));
|
||||
verify(auth, times(1)).loadUserByToken("tok");
|
||||
}
|
||||
|
||||
// ---- roles are sent as {id, name} from the stored role ----
|
||||
|
||||
@Test
|
||||
void create_sendsStoredRoleIdAndNameOnly() {
|
||||
stubNoDuplicates();
|
||||
stubSave(row(20, "N", "u", "e@x.com", true, "R"));
|
||||
service.create(req("N", "u", "e@x.com", List.of(new AdminRoleRef(4L, "whatever"))));
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat(((List<Map<String, Object>>) ((Map<String, Object>) body.getValue()).get("roles")).get(0))
|
||||
.containsOnlyKeys("id", "name").containsEntry("id", 4L).containsEntry("name", "ROLE_SALES");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_sendsStoredRoleIdAndNameOnly() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
stubSave(row(5, "A", "a", "a@x.com", true, "R"));
|
||||
service.update(5L, new AdminUserRequest(null, null, null, null, null, ROLES));
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat(((List<Map<String, Object>>) ((Map<String, Object>) body.getValue()).get("roles")).get(0))
|
||||
.containsOnlyKeys("id", "name").containsEntry("name", "ROLE_SALES");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_savesOnlyWhitelistedUserFields() {
|
||||
stubNoDuplicates();
|
||||
Map<String, Object> stored = row(5, "A", "a", "a@x.com", true, "R");
|
||||
stored.put("status", "Y");
|
||||
stored.put("companyId", 7L);
|
||||
stored.put("emailVerified", "Y");
|
||||
stored.put("showPassword", false);
|
||||
stored.put("linkedAccounts", List.of());
|
||||
stored.put("token", "t");
|
||||
stored.put("memberCode", "m");
|
||||
stored.put("branch", new HashMap<>(Map.of("id", 3L, "code", "G", "children", List.of())));
|
||||
stored.put("userGroup", new HashMap<>(Map.of("id", 9L, "name", "grp")));
|
||||
stubFind(5, stored);
|
||||
stubSave(row(5, "A", "a", "a@x.com", true, "R"));
|
||||
|
||||
service.update(5L, new AdminUserRequest(null, null, null, null, null, null));
|
||||
|
||||
ArgumentCaptor<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).doesNotContainKeys("password", "passwordSecondary", "passwordEmrm", "showPassword",
|
||||
"linkedAccounts", "token", "memberCode");
|
||||
assertThat(saved).containsEntry("emailVerified", "Y").containsEntry("companyId", 7L);
|
||||
assertThat((Map<String, Object>) saved.get("branch")).containsOnlyKeys("id");
|
||||
assertThat((Map<String, Object>) saved.get("userGroup")).containsOnlyKeys("id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_sendsASortSoServicesSystemCanPage() {
|
||||
stubPage(row(1, "A", "a", "a@x.com", true, "R"));
|
||||
service.list(null, null, 0, 20, null, null);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
Map<String, Object> pageable = (Map<String, Object>) ((Map<String, Object>) body.getValue()).get("pageableRest");
|
||||
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("direction", "ASC", "property", "id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownRole_is400UnknownRole_onCreateAndUpdate() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
List<AdminRoleRef> bad = List.of(new AdminRoleRef(99L, "NOPE"));
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", bad)), HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE");
|
||||
assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, bad)),
|
||||
HttpStatus.BAD_REQUEST, "UNKNOWN_ROLE");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
// ---- super admin guard ----
|
||||
|
||||
private static final List<AdminRoleRef> SUPER = List.of(new AdminRoleRef(1L, "ROLE_SUPER_ADMIN"));
|
||||
|
||||
@Test
|
||||
void nonSuperCaller_cannotGrantSuperAdmin() {
|
||||
stubNoDuplicates();
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
assertCoded(() -> service.create(req("N", "u", "e@x.com", SUPER)), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
assertCoded(() -> service.update(5L, new AdminUserRequest(null, null, null, null, null, SUPER)),
|
||||
HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void superCaller_canGrantSuperAdmin() {
|
||||
stubNoDuplicates();
|
||||
callerIsSuper();
|
||||
stubSave(row(20, "N", "u", "e@x.com", true, "R"));
|
||||
service.create(req("N", "u", "e@x.com", SUPER));
|
||||
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonSuperCaller_cannotManageSuperAdminTarget() {
|
||||
stubNoDuplicates();
|
||||
stubFind(6, superAdminRow(6));
|
||||
assertCoded(() -> service.update(6L, new AdminUserRequest("X", null, null, null, null, null)),
|
||||
HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
assertCoded(() -> service.resetPassword(6L), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
assertCoded(() -> service.changePassword(6L, "Str0ng#Pass"), HttpStatus.FORBIDDEN, "SUPER_ADMIN_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, never()).postForEntity(eq(UPDATE_PWD), eq(Integer.class), any());
|
||||
verify(auth, never()).resetAdminPassword(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void superCaller_canManageSuperAdminTarget() {
|
||||
callerIsSuper();
|
||||
stubFind(6, superAdminRow(6));
|
||||
when(auth.resetAdminPassword("root", "r@x.com")).thenReturn(1);
|
||||
assertThat(service.resetPassword(6L)).isEqualTo(1);
|
||||
}
|
||||
|
||||
// ---- shared roles in list (services-system sends repeats as bare ids) ----
|
||||
|
||||
private Map<String, Object> userWithRoles(long id, String name, Object... roles) {
|
||||
Map<String, Object> m = row(id, name, name.toLowerCase(), name + "@x.com", true);
|
||||
m.put("roles", new ArrayList<>(List.of(roles)));
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_sharedRoleSentAsBareId_sortByRolesDoesNotThrow() {
|
||||
stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L));
|
||||
assertThat(names(service.list(null, null, 0, 20, "roles", "asc"))).containsExactly("Aa", "Bb");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_bareRoleIdResolvedEvenWhenFullRoleIsOnAnotherPage() {
|
||||
stubPage(userWithRoles(1, "Aa", fullRole(4, "ROLE_SALES")), userWithRoles(2, "Bb", 4L));
|
||||
Map<String, Object> page1 = service.list(null, null, 1, 1, "name", "asc");
|
||||
Map<String, Object> u = ((List<Map<String, Object>>) page1.get("content")).get(0);
|
||||
assertThat(u).containsEntry("name", "Bb");
|
||||
assertThat(((List<Map<String, Object>>) u.get("roles")).get(0)).containsEntry("name", "ROLE_SALES").containsEntry("tracekey", "tk4");
|
||||
}
|
||||
|
||||
// ---- passwords ----
|
||||
|
||||
@Test
|
||||
void resetPassword_usesStoredUsernameAndEmail() {
|
||||
stubFind(5, row(5, "A", "stored", "stored@x.com", true, "R"));
|
||||
when(auth.resetAdminPassword("stored", "stored@x.com")).thenReturn(1);
|
||||
assertThat(service.resetPassword(5L)).isEqualTo(1);
|
||||
verify(auth).resetAdminPassword("stored", "stored@x.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changePassword_rulesRejected_is400() {
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(0));
|
||||
assertCoded(() -> service.changePassword(5L, "weak"), HttpStatus.BAD_REQUEST, "PASSWORD_RULES");
|
||||
}
|
||||
|
||||
@Test
|
||||
void changePassword_ok_returnsRowsUpdated() {
|
||||
stubFind(5, row(5, "A", "a", "a@x.com", true, "R"));
|
||||
when(rest.postForEntity(eq(UPDATE_PWD), eq(Integer.class), any())).thenReturn(ResponseEntity.ok(1));
|
||||
assertThat(service.changePassword(5L, "Str0ng#Pass")).isEqualTo(1);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(UPDATE_PWD), eq(Integer.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("userId", 5L).containsEntry("password", "Str0ng#Pass");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user