feat: admin services supply allow-listed audit changes
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
1523dc566b
commit
adc62ac436
12 files changed
+668
-8
No files matched your search
@@ -44,7 +44,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
|
||||
- `AuditChanges` content lands in `changes` and is cleared between requests.
|
||||
- Scope: `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
|
||||
- [ ] 3.2 Allow-listed changes from the services (design decision 5).
|
||||
- [x] 3.2 Allow-listed changes from the services (design decision 5).
|
||||
- Tests first, one per service:
|
||||
- user role names and enabled flag before and after;
|
||||
- role modules added and removed;
|
||||
|
||||
+10
-1
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminModuleGrant;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -52,8 +53,12 @@ public class AdminAclService {
|
||||
List<Map<String, Object>> modules = modules();
|
||||
Set<Long> known = new HashSet<>();
|
||||
Set<Long> current = new HashSet<>();
|
||||
Map<Long, String> codes = new java.util.HashMap<>();
|
||||
for (Map<String, Object> m : modules) {
|
||||
if (isGrantable(m)) known.add(AdminRoleService.idOf(m));
|
||||
if (isGrantable(m)) {
|
||||
known.add(AdminRoleService.idOf(m));
|
||||
codes.put(AdminRoleService.idOf(m), String.valueOf(m.get("name")));
|
||||
}
|
||||
if (isGrantable(m) && grantedTo(m, roleId)) current.add(AdminRoleService.idOf(m));
|
||||
}
|
||||
Set<Long> wanted = new HashSet<>(moduleIds);
|
||||
@@ -62,6 +67,10 @@ public class AdminAclService {
|
||||
// ponytail: not atomic, adds run before deletes and a failure midway leaves a partial grant; a repeated PUT converges. Upgrade: one services-system endpoint that replaces grants in a transaction.
|
||||
for (Long id : wanted) if (!current.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_ADD_MODULE_ROLE, id, roleId);
|
||||
for (Long id : current) if (!wanted.contains(id)) call(RestApiSystemServiceConstants.API_REST_SYSTEM_MODULE_DELETE_MODULE_ROLE, id, roleId);
|
||||
List<String> added = wanted.stream().filter(id -> !current.contains(id)).map(codes::get).sorted().toList();
|
||||
List<String> removed = current.stream().filter(id -> !wanted.contains(id)).map(codes::get).sorted().toList();
|
||||
if (!added.isEmpty()) AuditChanges.put("modulesAdded", null, added);
|
||||
if (!removed.isEmpty()) AuditChanges.put("modulesRemoved", null, removed);
|
||||
return getGrantTree(roleId);
|
||||
}
|
||||
|
||||
|
||||
+13
-2
@@ -10,6 +10,7 @@ import com.solvway.mobile.api.dto.admin.AdminEventLeadCaptureRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadMatchRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -23,6 +24,7 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -260,8 +262,17 @@ public class AdminEventLeadService {
|
||||
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
|
||||
body.put("notes", trimmed(r.notes()));
|
||||
body.put("doneBy", caller.getUsername());
|
||||
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody(),
|
||||
known, new HashMap<>());
|
||||
Map<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
|
||||
// field names only: follow-up values are personal data
|
||||
List<String> changed = new ArrayList<>();
|
||||
if (!Objects.equals(r.salespersonId(), currentSalesperson)) changed.add("salespersonId");
|
||||
if (!Objects.equals(temperature, current.get("temperature"))) changed.add("temperature");
|
||||
if (!Objects.equals(status, current.get("status"))) changed.add("status");
|
||||
if (!new HashSet<>(interestIds).equals(new HashSet<>(longs(current.get("interestIds"))))) changed.add("interestIds");
|
||||
if (!Objects.equals(body.get("nextFollowUpDate"), current.get("nextFollowUpDate") == null ? null : current.get("nextFollowUpDate").toString())) changed.add("nextFollowUpDate");
|
||||
if (!Objects.equals(body.get("notes"), current.get("notes"))) changed.add("notes");
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
return view(saved, known, new HashMap<>());
|
||||
}
|
||||
|
||||
// --- rules ---
|
||||
|
||||
+23
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
@@ -19,6 +20,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.email;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
@@ -118,11 +120,31 @@ public class AdminLeadService {
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("notes", notes);
|
||||
body.put("doneBy", caller.getUsername());
|
||||
Map<String, Object> before = storedOrNull(caller.getCompanyId(), id);
|
||||
Map<String, Object> saved;
|
||||
try {
|
||||
return detail(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody());
|
||||
saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_UPDATE), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw notFound();
|
||||
}
|
||||
// field names only: lead values are personal data. No readable before-state means nothing is recorded.
|
||||
if (before != null) {
|
||||
List<String> changed = new ArrayList<>();
|
||||
for (String f : List.of("name", "mobileE164", "email", "companyName", "jobTitle", "notes")) {
|
||||
if (!Objects.equals(before.get(f), body.get(f))) changed.add("mobileE164".equals(f) ? "phone" : f);
|
||||
}
|
||||
if (!changed.isEmpty()) AuditChanges.fields(changed.toArray(String[]::new));
|
||||
}
|
||||
return detail(saved);
|
||||
}
|
||||
|
||||
/** Best-effort read of the lead before it is changed, for the audit trail only. */
|
||||
private Map<String, Object> storedOrNull(Long companyId, long id) {
|
||||
try {
|
||||
return restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_LEAD_DETAIL), MAP, companyId, id).getBody();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Digits to match against the stored E.164 mobile, or null when the term is not a phone-like number. */
|
||||
|
||||
+36
@@ -6,6 +6,7 @@ import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -15,9 +16,11 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Passes the Login security screen's calls to services-system, turning its 400s into coded admin errors. */
|
||||
@@ -59,7 +62,13 @@ public class AdminLoginSecurityService {
|
||||
}
|
||||
|
||||
public Map<String, Object> saveConfig(Map<String, Object> config) {
|
||||
Map<String, Object> before = readOrNull(this::config);
|
||||
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
|
||||
if (before != null && saved != null) {
|
||||
for (String key : List.of("enabled", "maxAttempts", "period", "unit")) {
|
||||
if (!Objects.equals(before.get(key), saved.get(key))) AuditChanges.put(key, before.get(key), saved.get(key));
|
||||
}
|
||||
}
|
||||
log.info("lockout settings changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
@@ -69,11 +78,38 @@ public class AdminLoginSecurityService {
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
|
||||
List<Map<String, Object>> before = readOrNull(this::passwordRules);
|
||||
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
|
||||
if (before != null && saved != null) {
|
||||
Map<Object, Map<String, Object>> old = new HashMap<>();
|
||||
before.forEach(b -> old.put(b.get("param"), b));
|
||||
for (Map<String, Object> now : saved) {
|
||||
Map<String, Object> was = old.get(now.get("param"));
|
||||
if (was != null && !(Objects.equals(was.get("status"), now.get("status")) && Objects.equals(was.get("value"), now.get("value")))) {
|
||||
AuditChanges.put(String.valueOf(now.get("param")), ruleState(was), ruleState(now));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info("password rules changed by {}", callerName());
|
||||
return saved;
|
||||
}
|
||||
|
||||
private static Map<String, Object> ruleState(Map<String, Object> rule) {
|
||||
Map<String, Object> state = new HashMap<>();
|
||||
state.put("status", rule.get("status"));
|
||||
state.put("value", rule.get("value"));
|
||||
return state;
|
||||
}
|
||||
|
||||
/** Best-effort read of the settings before they change, for the audit trail only. */
|
||||
private static <T> T readOrNull(Supplier<T> read) {
|
||||
try {
|
||||
return read.get();
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T post(String api, ParameterizedTypeReference<T> type, Object body) {
|
||||
return upstream(() -> restTemplateUtil.postForEntity(url(api), type, body).getBody());
|
||||
}
|
||||
|
||||
+16
-1
@@ -6,6 +6,7 @@ import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.AdminRoleRef;
|
||||
import com.solvway.mobile.api.dto.admin.AdminUserRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -115,6 +116,8 @@ public class AdminUserService {
|
||||
if (adminAuthenticationService.setAdminPassword(((Number) saved.get("id")).longValue(), r.password()) == 0) {
|
||||
throw error(HttpStatus.INTERNAL_SERVER_ERROR, "User created but the password was not stored; set a temporary password", "SAVE_FAILED");
|
||||
}
|
||||
AuditChanges.put("roles", null, sortedRoleNames(user.get("roles")));
|
||||
AuditChanges.put("enabled", null, true);
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
@@ -132,6 +135,8 @@ public class AdminUserService {
|
||||
if (r.roles() != null && r.roles().isEmpty()) {
|
||||
throw error(HttpStatus.BAD_REQUEST, "At least one role is required", "REQUIRED_FIELD");
|
||||
}
|
||||
List<String> rolesBefore = sortedRoleNames(user.get("roles"));
|
||||
Object enabledBefore = user.get("enabled");
|
||||
if (StringUtils.hasText(r.name())) user.put("name", r.name());
|
||||
if (r.surname() != null) user.put("surname", r.surname());
|
||||
if (StringUtils.hasText(r.email())) user.put("email", r.email());
|
||||
@@ -141,7 +146,12 @@ public class AdminUserService {
|
||||
user.put("status", r.enabled() ? "Y" : "N");
|
||||
}
|
||||
user.put("doneBy", caller.getUsername());
|
||||
return clean(save(user));
|
||||
Map<String, Object> saved = save(user);
|
||||
// names and ids only: never the user's name, surname or email
|
||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
||||
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
|
||||
return clean(saved);
|
||||
}
|
||||
|
||||
public int resetPassword(Long id) {
|
||||
@@ -301,6 +311,11 @@ public class AdminUserService {
|
||||
return Comparator.comparing(m -> String.valueOf(m.get(key)).toLowerCase());
|
||||
}
|
||||
|
||||
private static List<String> sortedRoleNames(Object roles) {
|
||||
if (!(roles instanceof List<?> l)) return List.of();
|
||||
return l.stream().map(r -> r instanceof Map<?, ?> rm ? String.valueOf(rm.get("name")) : String.valueOf(r)).sorted().toList();
|
||||
}
|
||||
|
||||
private static String roleNames(Map<String, Object> m) {
|
||||
Object roles = m.get("roles");
|
||||
if (!(roles instanceof List<?> l)) return "";
|
||||
|
||||
+2
-2
@@ -39,11 +39,11 @@ public final class AuditChanges {
|
||||
changes.put("fields", List.of(names));
|
||||
}
|
||||
|
||||
static Map<String, Object> current() {
|
||||
public static Map<String, Object> current() {
|
||||
return CURRENT.get();
|
||||
}
|
||||
|
||||
static void clear() {
|
||||
public static void clear() {
|
||||
CURRENT.remove();
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
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.useraccess.AuditChanges;
|
||||
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.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
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.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.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminAclServiceAuditChangesTest {
|
||||
|
||||
private static final long ROOT = 40000000L, USERS = 40700000L, ROLES = 40800000L, LEADS = 40900000L;
|
||||
|
||||
private AdminAclService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
AdminRoleService roles = mock(AdminRoleService.class);
|
||||
service = new AdminAclService(rest, auth, roles);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(roles.find(4L)).thenReturn(Map.of("id", 4L, "name", "ROLE_SALES"));
|
||||
// role 4 holds BO_USERS and BO_ROLES
|
||||
when(rest.getForEntity(eq("/module/findAllByArea/{area}"), any(ParameterizedTypeReference.class), eq("BO"))).thenReturn(ResponseEntity.ok(List.of(
|
||||
module(ROOT, "BO_ROOT", "R"),
|
||||
module(USERS, "BO_USERS", "M", 4),
|
||||
module(ROLES, "BO_ROLES", "M", 4),
|
||||
module(LEADS, "BO_LEADS", "M"))));
|
||||
User u = new User();
|
||||
u.setId(50L);
|
||||
Role r = new Role();
|
||||
r.setId(1L);
|
||||
u.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> module(long id, String name, String type, long... roleIds) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
m.put("type", type);
|
||||
m.put("parent", "R".equals(type) ? null : ROOT);
|
||||
m.put("roles", java.util.Arrays.stream(roleIds).mapToObj(x -> (Object) Map.of("id", x, "name", "R" + x)).toList());
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsAddedAndRemovedModuleCodes() {
|
||||
service.updateGrants(4L, List.of(USERS, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded", "modulesRemoved");
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesAdded")).containsEntry("after", List.of("BO_LEADS")).containsEntry("before", null);
|
||||
assertThat((Map<String, Object>) AuditChanges.current().get("modulesRemoved")).containsEntry("after", List.of("BO_ROLES")).containsEntry("before", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_recordsOnlyTheNonEmptySide() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES, LEADS));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("modulesAdded");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGrants_sameSetRecordsNothing() {
|
||||
service.updateGrants(4L, List.of(USERS, ROLES));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminEventLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
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.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEventLeadServiceAuditChangesTest {
|
||||
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long EL = 3312853897594494976L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminEventLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEventLeadService(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(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
Event e = new Event();
|
||||
e.setUuid(EV);
|
||||
e.setName("Fair");
|
||||
e.setEnabled(GeneralEnum.FlagYesNo.Y);
|
||||
when(rest.getForEntity(eq("/counter/event/findByUuid/{uuid}"), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
when(rest.getForEntity(eq("/counter/interest/findByCompany/{companyId}"), any(ParameterizedTypeReference.class), eq(COMPANY)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(
|
||||
Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0),
|
||||
Map.of("id", 4L, "companyId", COMPANY, "name", "Kitchen", "active", true, "sortOrder", 0))));
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("eventLeadUuid", EL);
|
||||
d.put("eventUuid", EV);
|
||||
d.put("name", "Aisyah");
|
||||
d.put("salespersonUserId", 21L);
|
||||
d.put("temperature", "WARM");
|
||||
d.put("status", "OPEN");
|
||||
d.put("interestIds", List.of(3L));
|
||||
d.put("nextFollowUpDate", "2027-01-20");
|
||||
d.put("notes", "old note");
|
||||
when(rest.getForEntity(eq("/counter/eventLead/findByUuid/{companyId}/{eventLeadUuid}"), any(ParameterizedTypeReference.class), eq(COMPANY), eq(EL)))
|
||||
.thenReturn(ResponseEntity.ok(d));
|
||||
when(rest.postForEntity(eq("/counter/eventLead/update"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> ResponseEntity.ok(new HashMap<String, Object>(Map.of("eventLeadUuid", EL, "eventUuid", EV))));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private void update(AdminEventLeadUpdateRequest r) {
|
||||
service.update(String.valueOf(EV), String.valueOf(EL), r);
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsChangedFieldNamesAndNoValues() throws Exception {
|
||||
update(new AdminEventLeadUpdateRequest(21L, "HOT", "OPEN", List.of(3L, 4L), "2027-01-20", "private call note"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("fields");
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactlyInAnyOrder("temperature", "interestIds", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("private call note", "old note", "HOT", "2027-01-20");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_nothingChangedRecordsNothing() {
|
||||
update(new AdminEventLeadUpdateRequest(21L, "WARM", "OPEN", List.of(3L), "2027-01-20", "old note"));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.AdminLeadUpdateRequest;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
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.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
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.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminLeadServiceAuditChangesTest {
|
||||
|
||||
private static final String DETAIL = "/counter/lead/detail/{companyId}/{leadUuid}";
|
||||
private static final String UPDATE = "/counter/lead/update";
|
||||
private static final long LEAD = 3312853897040846848L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminLeadService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminLeadService(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(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(5L);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any())).thenAnswer(i -> ResponseEntity.ok(i.getArgument(2)));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private void stored() {
|
||||
Map<String, Object> d = new HashMap<>();
|
||||
d.put("leadUuid", LEAD);
|
||||
d.put("name", "Old Name");
|
||||
d.put("mobileE164", "+60123456701");
|
||||
d.put("email", "old@example.test");
|
||||
d.put("companyName", "Acme");
|
||||
when(rest.getForEntity(eq(DETAIL), any(ParameterizedTypeReference.class), eq(5L), eq(LEAD))).thenReturn(ResponseEntity.ok(d));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsChangedFieldNamesAndNoValues() throws Exception {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", "fresh@example.test", "Acme", null, "secret note"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("fields");
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactlyInAnyOrder("name", "email", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("Brand New Name", "fresh@example.test", "secret note", "Old Name", "0123456701");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_nothingChangedRecordsNothing() {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Old Name", "012-345 6701", "old@example.test", "Acme", null, null));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_unreadableBeforeStateRecordsNothing() {
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", null, null, null, null));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_phoneAndNotesRecordedByNameWithoutEitherNumber() throws Exception {
|
||||
stored();
|
||||
|
||||
service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Old Name", "019-876 5432", "old@example.test", "Acme", null, "fresh private note"));
|
||||
|
||||
assertThat((List<String>) AuditChanges.current().get("fields")).containsExactly("phone", "notes");
|
||||
String json = new ObjectMapper().writeValueAsString(AuditChanges.current());
|
||||
assertThat(json).doesNotContain("+60123456701", "123456701", "+60198765432", "198765432", "fresh private note");
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_refusedByValidationRecordsNothing() {
|
||||
stored();
|
||||
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest(" ", "012-345 6701", null, null, null, null)))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_saveAnswering404RecordsNothing() {
|
||||
stored();
|
||||
when(rest.postForEntity(eq(UPDATE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "gone", HttpHeaders.EMPTY, new byte[0], null));
|
||||
|
||||
assertThatThrownBy(() -> service.update(String.valueOf(LEAD), new AdminLeadUpdateRequest("Brand New Name", "012-345 6701", "old@example.test", "Acme", null, null)))
|
||||
.isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
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.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminLoginSecurityServiceAuditChangesTest {
|
||||
|
||||
private static final String CONFIG = "/loginSecurity/config";
|
||||
private static final String RULES = "/loginSecurity/passwordRules";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminLoginSecurityService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminLoginSecurityService(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.setUsername("boss");
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> change(Object before, Object after) {
|
||||
Map<String, Object> m = new java.util.HashMap<>();
|
||||
m.put("before", before);
|
||||
m.put("after", after);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveConfig_recordsChangedSettingsOnly() {
|
||||
Map<String, Object> before = Map.of("enabled", true, "maxAttempts", 5, "period", 15, "unit", "MINUTES");
|
||||
Map<String, Object> after = Map.of("enabled", true, "maxAttempts", 3, "period", 30, "unit", "MINUTES");
|
||||
when(rest.getForEntity(eq(CONFIG), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(before));
|
||||
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(after));
|
||||
|
||||
service.saveConfig(after);
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("maxAttempts", "period")
|
||||
.containsEntry("maxAttempts", change(5, 3)).containsEntry("period", change(15, 30));
|
||||
}
|
||||
|
||||
@Test
|
||||
void savePasswordRules_recordsChangedRulesOnly() {
|
||||
List<Map<String, Object>> before = List.of(
|
||||
Map.of("id", 1, "param", "MIN_LENGTH", "status", true, "value", "8"),
|
||||
Map.of("id", 2, "param", "UPPERCASE", "status", true, "value", "1"));
|
||||
List<Map<String, Object>> after = List.of(
|
||||
Map.of("id", 1, "param", "MIN_LENGTH", "status", true, "value", "12"),
|
||||
Map.of("id", 2, "param", "UPPERCASE", "status", true, "value", "1"));
|
||||
when(rest.getForEntity(eq(RULES), any(ParameterizedTypeReference.class))).thenReturn(ResponseEntity.ok(before));
|
||||
when(rest.postForEntity(eq(RULES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(after));
|
||||
|
||||
service.savePasswordRules(after);
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("MIN_LENGTH")
|
||||
.containsEntry("MIN_LENGTH", change(Map.of("status", true, "value", "8"), Map.of("status", true, "value", "12")));
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.LocationHierarchy;
|
||||
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.useraccess.AuditChanges;
|
||||
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.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
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.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminUserServiceAuditChangesTest {
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminUserService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
AuditChanges.clear();
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
AdminAuthenticationService 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(auth.passesAdminPasswordRules(anyString())).thenReturn(true);
|
||||
when(auth.setAdminPassword(any(), anyString())).thenReturn(1);
|
||||
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.postForEntity(eq("/user/save"), any(ParameterizedTypeReference.class), any()))
|
||||
.thenAnswer(i -> {
|
||||
Map<String, Object> saved = new HashMap<>((Map<String, Object>) i.getArgument(2));
|
||||
saved.put("id", 9L);
|
||||
return ResponseEntity.ok(saved);
|
||||
});
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() {
|
||||
http.close();
|
||||
AuditChanges.clear();
|
||||
}
|
||||
|
||||
private static Map<String, Object> role(long id, String name) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("name", name);
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stored(boolean enabled, Map<String, Object>... roles) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", 9L);
|
||||
u.put("name", "Sam");
|
||||
u.put("username", "sam");
|
||||
u.put("email", "sam@x.com");
|
||||
u.put("enabled", enabled);
|
||||
u.put("type", "A");
|
||||
u.put("roles", List.of(roles));
|
||||
when(rest.getForEntity(eq("/user/findById/{id}"), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private static Map<String, Object> change(Object before, Object after) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("before", before);
|
||||
m.put("after", after);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsRoleNamesAndEnabledBeforeAndAfter() {
|
||||
stored(true, role(5, "ROLE_OPS"), role(4, "ROLE_SALES"));
|
||||
|
||||
service.update(9L, new AdminUserRequest("Sam", null, null, null, false, List.of(new AdminRoleRef(6L, null), new AdminRoleRef(4L, null))));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("roles", "enabled")
|
||||
.containsEntry("roles", change(List.of("ROLE_OPS", "ROLE_SALES"), List.of("ROLE_ACCOUNTS", "ROLE_SALES")))
|
||||
.containsEntry("enabled", change(true, false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsNothingForUnchangedOrAbsentFields() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
|
||||
service.update(9L, new AdminUserRequest("Renamed", "Surname", null, "new@x.com", true, List.of(new AdminRoleRef(4L, null))));
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void update_recordsNothingWhenRefused() {
|
||||
stored(true, role(4, "ROLE_SALES"));
|
||||
|
||||
assertThatThrownBy(() -> service.update(9L, new AdminUserRequest(null, null, null, null, null, List.of()))).isInstanceOf(RuntimeException.class);
|
||||
|
||||
assertThat(AuditChanges.current()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void create_recordsRolesAndEnabled() {
|
||||
service.create(new AdminUserRequest("Sam", null, "sam", "sam@x.com", null,
|
||||
List.of(new AdminRoleRef(5L, null), new AdminRoleRef(4L, null)), "Good#Pass1", "Good#Pass1"));
|
||||
|
||||
assertThat(AuditChanges.current()).containsOnlyKeys("roles", "enabled")
|
||||
.containsEntry("roles", change(null, List.of("ROLE_OPS", "ROLE_SALES")))
|
||||
.containsEntry("enabled", change(null, true));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user