feat: read-only admin email listing for when no email provider is configured
GET /api/admin/emails lists saved emails newest first (no bodies), and
GET /api/admin/emails/{id} returns one with its body, under a new BO_EMAILS
module. A caller who is not a super admin cannot open an email addressed to a
super admin. Each view logs the email id and viewer, never the body.
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
b18e2e625a
commit
0961a10bb2
6 files changed
+472
No files matched your search
@@ -118,3 +118,7 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
|
||||
(40400000, 'BO_LEADS', 'Leads', 'BO', 'M', 40000000, '/leads', 'Users'),
|
||||
(40500000, 'BO_LEADS_EDIT', 'Edit leads', 'BO', 'M', 40000000, NULL, NULL),
|
||||
(40600000, 'BO_LEADS_EXPORT', 'Export leads', 'BO', 'M', 40000000, NULL, NULL);
|
||||
|
||||
-- add-admin-email-listing/sql/01-email-module.sql
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(40900000, 'BO_EMAILS', 'Emails', 'BO', 'M', 40000000, '/emails', 'Mail');
|
||||
+2
@@ -5,4 +5,6 @@ public class RestApiEmailServiceConstants {
|
||||
private RestApiEmailServiceConstants() {}
|
||||
|
||||
public static final String API_REST_EMAIL_SEND = "/email/send";
|
||||
public static final String API_REST_EMAIL_FIND_BY_PROPERTY_AND_PAGEABLE = "/email/findByPropertyAndPageable";
|
||||
public static final String API_REST_EMAIL_FIND_BY_ID = "/email/findById/{id}";
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.AdminEmailService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** Read-only listing of saved emails for the portal. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule("BO_EMAILS")
|
||||
public class AdminEmailController {
|
||||
|
||||
private final AdminEmailService adminEmailService;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/emails")
|
||||
public ResponseEntity<Map<String, Object>> list(
|
||||
@RequestParam(required = false) String recipient,
|
||||
@RequestParam(required = false) String subject,
|
||||
@RequestParam(required = false) String from,
|
||||
@RequestParam(required = false) String to,
|
||||
@RequestParam(defaultValue = "0") int page,
|
||||
@RequestParam(defaultValue = "20") int size) {
|
||||
return ResponseEntity.ok(adminEmailService.list(recipient, subject, from, to, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/emails/{id}")
|
||||
public ResponseEntity<Map<String, Object>> detail(@PathVariable Long id) {
|
||||
return ResponseEntity.ok(adminEmailService.detail(id));
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiEmailServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Read-only view of the emails service-email has saved, so a temporary password can be passed on while no
|
||||
* email provider is configured. The list never carries a body; the detail does, except that an email to a
|
||||
* super admin is refused to a caller who is not one.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdminEmailService {
|
||||
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final long SUPER_ADMIN_ROLE_ID = 1L;
|
||||
private static final int MAX_PAGE_SIZE = 100;
|
||||
private static final DateTimeFormatter UPSTREAM_DATE = DateTimeFormatter.ofPattern("dd-MM-yyyy");
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
|
||||
public Map<String, Object> list(String recipient, String subject, String from, String to, int page, int size) {
|
||||
Map<String, Object> property = new LinkedHashMap<>();
|
||||
if (StringUtils.hasText(recipient)) property.put("recipient", recipient.trim());
|
||||
if (StringUtils.hasText(subject)) property.put("subject", subject.trim());
|
||||
if (StringUtils.hasText(from)) property.put("startDate", upstreamDate(from));
|
||||
if (StringUtils.hasText(to)) property.put("endDate", upstreamDate(to));
|
||||
Map<String, Object> pageable = Map.of("number", Math.max(page, 0), "size", Math.min(Math.max(size, 1), MAX_PAGE_SIZE),
|
||||
"sorts", List.of(Map.of("property", "datetime", "direction", "DESC")));
|
||||
Map<String, Object> result = restTemplateUtil.postForEntity(
|
||||
url(RestApiEmailServiceConstants.API_REST_EMAIL_FIND_BY_PROPERTY_AND_PAGEABLE), MAP,
|
||||
Map.of("property", property, "pageableRest", pageable)).getBody();
|
||||
Map<String, Object> out = new LinkedHashMap<>(result == null ? Map.of() : result);
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
if (out.get("content") instanceof List<?> content) {
|
||||
for (Object item : content) if (item instanceof Map<?, ?> row) rows.add(listRow(row));
|
||||
}
|
||||
out.put("content", rows);
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> detail(Long id) {
|
||||
Map<String, Object> row = restTemplateUtil.getForEntity(url(RestApiEmailServiceConstants.API_REST_EMAIL_FIND_BY_ID), MAP, id).getBody();
|
||||
if (row == null || row.isEmpty()) {
|
||||
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Email not found", "EMAIL_NOT_FOUND");
|
||||
}
|
||||
User caller = caller();
|
||||
List<Map<String, Object>> recipients = new ArrayList<>();
|
||||
if (row.get("recipients") instanceof List<?> list) {
|
||||
for (Object item : list) {
|
||||
if (item instanceof Map<?, ?> r && r.get("recipient") != null) {
|
||||
Map<String, Object> ref = new LinkedHashMap<>();
|
||||
ref.put("recipient", String.valueOf(r.get("recipient")));
|
||||
ref.put("type", r.get("type") == null ? null : String.valueOf(r.get("type")));
|
||||
recipients.add(ref);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!isSuper(caller) && recipients.stream().anyMatch(r -> isSuperAdminAddress((String) r.get("recipient")))) {
|
||||
throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Only a super admin can read this email", "SUPER_ADMIN_REQUIRED");
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", row.get("id"));
|
||||
out.put("datetime", row.get("datetime"));
|
||||
out.put("sender", row.get("sender"));
|
||||
out.put("subject", row.get("subject"));
|
||||
out.put("status", row.get("status"));
|
||||
out.put("recipients", recipients);
|
||||
out.put("body", row.get("body"));
|
||||
log.info("email {} viewed by {}", id, caller.getUsername());
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Map<String, Object> listRow(Map<?, ?> row) {
|
||||
List<String> to = new ArrayList<>();
|
||||
if (row.get("recipients") instanceof List<?> list) {
|
||||
for (Object item : list) if (item instanceof Map<?, ?> r && r.get("recipient") != null) to.add(String.valueOf(r.get("recipient")));
|
||||
}
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("id", row.get("id") instanceof Number n ? n.longValue() : null);
|
||||
out.put("datetime", row.get("datetime"));
|
||||
out.put("recipients", to);
|
||||
out.put("subject", row.get("subject"));
|
||||
out.put("status", row.get("status"));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** An admin user holding the super admin role; services-system may send a role as a bare id. */
|
||||
private boolean isSuperAdminAddress(String address) {
|
||||
Map<String, Object> user = restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_EMAIL), MAP, address).getBody();
|
||||
return user != null && "A".equals(user.get("type")) && user.get("roles") instanceof List<?> roles
|
||||
&& roles.stream().anyMatch(r -> Long.valueOf(SUPER_ADMIN_ROLE_ID).equals(AdminRoleService.idOf(r)));
|
||||
}
|
||||
|
||||
private static boolean isSuper(User caller) {
|
||||
return caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
|
||||
}
|
||||
|
||||
private static String upstreamDate(String isoDate) {
|
||||
try {
|
||||
return LocalDate.parse(isoDate.trim()).format(UPSTREAM_DATE);
|
||||
} catch (java.time.format.DateTimeParseException e) {
|
||||
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "Dates must be yyyy-MM-dd", "INVALID_DATE");
|
||||
}
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
return caller;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return restTemplateUtil.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.service.AdminEmailService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AdminEmailControllerTest {
|
||||
|
||||
@Mock private AdminEmailService emails;
|
||||
@InjectMocks private AdminEmailController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void guardedByBackOfficeEmailsModule() {
|
||||
assertThat(AdminEmailController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_EMAILS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_passesFiltersAndPaging() throws Exception {
|
||||
when(emails.list("sales1", "Reset", "2026-11-01", "2026-11-30", 1, 5))
|
||||
.thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6));
|
||||
mvc.perform(get("/api/admin/emails").param("recipient", "sales1").param("subject", "Reset")
|
||||
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content[0].id").value(7))
|
||||
.andExpect(jsonPath("$.totalElements").value(6));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_defaultsToFirstPageOfTwenty() throws Exception {
|
||||
when(emails.list(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
|
||||
mvc.perform(get("/api/admin/emails")).andExpect(status().isOk());
|
||||
verify(emails).list(null, null, null, null, 0, 20);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_returnsTheEmail() throws Exception {
|
||||
when(emails.detail(7L)).thenReturn(Map.of("id", 7, "body", "<p>hi</p>"));
|
||||
mvc.perform(get("/api/admin/emails/7")).andExpect(status().isOk()).andExpect(jsonPath("$.body").value("<p>hi</p>"));
|
||||
}
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
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.slf4j.LoggerFactory;
|
||||
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.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.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminEmailServiceTest {
|
||||
|
||||
private static final String PAGE = "/email/findByPropertyAndPageable";
|
||||
private static final String FIND = "/email/findById/{id}";
|
||||
private static final String BY_EMAIL = "/user/findByEmail/{email}";
|
||||
private static final String BODY = "<p>Hi sales1,</p><p>Your temporary password: Xy7kPq2m</p>";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private AdminEmailService service;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
service = new AdminEmailService(rest, auth);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
callerWithRole(4L);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void callerWithRole(long roleId) {
|
||||
User caller = new User();
|
||||
caller.setId(1L);
|
||||
caller.setUsername("boss");
|
||||
Role r = new Role();
|
||||
r.setId(roleId);
|
||||
caller.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
}
|
||||
|
||||
private static Map<String, Object> emailRow(long id, String to) {
|
||||
Map<String, Object> m = new HashMap<>();
|
||||
m.put("id", id);
|
||||
m.put("sender", "noreply@example.com");
|
||||
m.put("subject", "Reset Admin Password");
|
||||
m.put("body", BODY);
|
||||
m.put("status", "Y");
|
||||
m.put("resend", 0);
|
||||
m.put("datetime", "2026-11-30T10:15:00");
|
||||
m.put("recipients", List.of(Map.of("recipient", to, "type", "R")));
|
||||
return m;
|
||||
}
|
||||
|
||||
private void stubFind(long id, Map<String, Object> row) {
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(row));
|
||||
}
|
||||
|
||||
private void stubUserByEmail(String email, Map<String, Object> user) {
|
||||
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq(email))).thenReturn(ResponseEntity.ok(user));
|
||||
}
|
||||
|
||||
private static Map<String, Object> adminUser(long... roleIds) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("type", "A");
|
||||
u.put("roles", java.util.Arrays.stream(roleIds).mapToObj(id -> Map.of("id", id)).toList());
|
||||
return u;
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_sendsOnlyGivenFiltersNewestFirstAndConvertsDates() {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(), "totalElements", 0)));
|
||||
|
||||
service.list("sales1", null, "2026-11-01", "2026-11-30", 2, 10);
|
||||
|
||||
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"))
|
||||
.containsOnly(Map.entry("recipient", "sales1"), Map.entry("startDate", "01-11-2026"), Map.entry("endDate", "30-11-2026"));
|
||||
Map<String, Object> pageable = (Map<String, Object>) sent.get("pageableRest");
|
||||
assertThat(pageable).containsEntry("number", 2).containsEntry("size", 10);
|
||||
assertThat((List<Map<String, Object>>) pageable.get("sorts")).containsExactly(Map.of("property", "datetime", "direction", "DESC"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_rowsCarryMetadataButNeverTheBody() {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of(emailRow(7, "sales1@example.com")), "totalElements", 1)));
|
||||
|
||||
Map<String, Object> out = service.list(null, null, null, null, 0, 20);
|
||||
|
||||
List<Map<String, Object>> rows = (List<Map<String, Object>>) out.get("content");
|
||||
assertThat(rows).hasSize(1);
|
||||
assertThat(rows.get(0)).containsOnlyKeys("id", "datetime", "recipients", "subject", "status")
|
||||
.containsEntry("id", 7L).containsEntry("subject", "Reset Admin Password")
|
||||
.containsEntry("recipients", List.of("sales1@example.com"));
|
||||
assertThat(out).containsEntry("totalElements", 1);
|
||||
assertThat(out.toString()).doesNotContain("Xy7kPq2m");
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_returnsBodyAndRecipientsForAnOrdinaryRecipient() {
|
||||
stubFind(7, emailRow(7, "sales1@example.com"));
|
||||
stubUserByEmail("sales1@example.com", adminUser(4));
|
||||
|
||||
Map<String, Object> out = service.detail(7L);
|
||||
|
||||
assertThat(out).containsEntry("body", BODY).containsEntry("subject", "Reset Admin Password");
|
||||
assertThat((List<Map<String, Object>>) out.get("recipients")).containsExactly(Map.of("recipient", "sales1@example.com", "type", "R"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_unknownEmail_is404() {
|
||||
when(rest.getForEntity(eq(FIND), any(ParameterizedTypeReference.class), eq(9L))).thenReturn(ResponseEntity.ok().build());
|
||||
assertThatThrownBy(() -> service.detail(9L)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(e.getCode()).isEqualTo("EMAIL_NOT_FOUND");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_superAdminRecipientWithNonSuperCaller_is403() {
|
||||
stubFind(7, emailRow(7, "root@example.com"));
|
||||
stubUserByEmail("root@example.com", adminUser(1));
|
||||
assertThatThrownBy(() -> service.detail(7L)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(e.getCode()).isEqualTo("SUPER_ADMIN_REQUIRED");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_superAdminRoleSentAsBareId_isStillProtected() {
|
||||
stubFind(7, emailRow(7, "root@example.com"));
|
||||
Map<String, Object> u = new HashMap<>(Map.of("type", "A", "roles", List.of(1)));
|
||||
stubUserByEmail("root@example.com", u);
|
||||
assertThatThrownBy(() -> service.detail(7L)).isInstanceOf(CodedResponseStatusException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_superCallerSkipsTheRecipientLookup() {
|
||||
callerWithRole(1L);
|
||||
stubFind(7, emailRow(7, "root@example.com"));
|
||||
assertThat(service.detail(7L)).containsEntry("body", BODY);
|
||||
verify(rest, never()).getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_recipientWhoIsNoUser_isShown() {
|
||||
stubFind(7, emailRow(7, "visitor@example.com"));
|
||||
when(rest.getForEntity(eq(BY_EMAIL), any(ParameterizedTypeReference.class), eq("visitor@example.com")))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
assertThat(service.detail(7L)).containsEntry("body", BODY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void detail_auditLineNamesEmailAndViewerButNotTheBody() {
|
||||
stubFind(7, emailRow(7, "sales1@example.com"));
|
||||
stubUserByEmail("sales1@example.com", adminUser(4));
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(AdminEmailService.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
service.detail(7L);
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
}
|
||||
assertThat(appender.list).extracting(ILoggingEvent::getFormattedMessage)
|
||||
.anySatisfy(m -> assertThat(m).isEqualTo("email 7 viewed by boss"))
|
||||
.allSatisfy(m -> assertThat(m).doesNotContain("Xy7kPq2m"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_badDate_is400InvalidDate() {
|
||||
assertThatThrownBy(() -> service.list(null, null, "30/11/2026", null, 0, 20))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getCode()).isEqualTo("INVALID_DATE");
|
||||
});
|
||||
verify(rest, never()).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void list_pageSizeIsCappedAtOneHundred() {
|
||||
when(rest.postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
|
||||
service.list(null, null, null, null, 0, 100000);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PAGE), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) ((Map<String, Object>) body.getValue()).get("pageableRest")).containsEntry("size", 100);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user