feat(mobile-api): public QR registration and registration-link admin APIs
Public page and submit for a registration code (one 404 for every unusable code, load and submit limits, honeypot, consent), event and own codes for staff, the switch audited against the event uuid rather than the token, and the super-admin privacy-notice endpoints. 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
ab1643e36e
commit
cf8478d00c
19 files changed
+1292
-9
No files matched your search
+121
@@ -0,0 +1,121 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
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.service.AdminAuthenticationService;
|
||||
import com.solvway.mobile.api.service.AdminCompanyService;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
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.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
/** Privacy notice endpoints of the Companies screen: super admin only. */
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class AdminCompanyPrivacyNoticeTest {
|
||||
|
||||
private static final String NOTICE = "/company/{id}/privacyNotice";
|
||||
private static final String BODY = "{\"textEn\":\"English\",\"textMs\":\"Malay\"}";
|
||||
|
||||
private final AdminCompanyService companies = mock(AdminCompanyService.class);
|
||||
private final AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
|
||||
private MockMvc mvc;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(new AdminCompanyController(companies, auth, new AdminCompanyScope())).build();
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void caller(Long companyId, long roleId) {
|
||||
User u = new User();
|
||||
u.setCompanyId(companyId);
|
||||
u.setUsername("root");
|
||||
Role r = new Role("R");
|
||||
r.setId(roleId);
|
||||
u.setRoles(List.of(r));
|
||||
when(auth.loadUserByToken("tok")).thenReturn(u);
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlersAreAuthenticated() throws Exception {
|
||||
assertThat(AdminCompanyController.class.getDeclaredMethods()).filteredOn(m -> m.getName().toLowerCase().contains("privacy"))
|
||||
.hasSize(2).allSatisfy(m -> assertThat(m.isAnnotationPresent(AppAuth.class)).isTrue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staff_get403_andNothingIsCalled() throws Exception {
|
||||
caller(5L, 1);
|
||||
mvc.perform(get("/api/admin/companies/5/privacy-notice")).andExpect(status().isForbidden());
|
||||
mvc.perform(put("/api/admin/companies/5/privacy-notice").contentType(MediaType.APPLICATION_JSON).content(BODY)).andExpect(status().isForbidden());
|
||||
verifyNoInteractions(companies);
|
||||
}
|
||||
|
||||
@Test
|
||||
void superAdmin_getsAndSaves_withCallerAsDoneBy() throws Exception {
|
||||
caller(null, 1);
|
||||
when(companies.privacyNotice(5L)).thenReturn(Map.of("id", 9, "textEn", "English"));
|
||||
when(companies.savePrivacyNotice(eq(5L), any(), eq("root"))).thenReturn(Map.of("id", 10, "textEn", "English"));
|
||||
mvc.perform(get("/api/admin/companies/5/privacy-notice")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(9));
|
||||
mvc.perform(put("/api/admin/companies/5/privacy-notice").contentType(MediaType.APPLICATION_JSON).content(BODY))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.id").value(10));
|
||||
verify(companies).savePrivacyNotice(eq(5L), eq(Map.of("textEn", "English", "textMs", "Malay")), eq("root"));
|
||||
}
|
||||
|
||||
// --- service ---
|
||||
|
||||
private static HttpClientErrorException err(HttpStatus s, String body) {
|
||||
return HttpClientErrorException.create(s, s.name(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void service_sendsTextsAndDoneBy_andMapsUpstreamErrors() {
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
AdminCompanyService service = new AdminCompanyService(rest);
|
||||
when(rest.postForEntity(eq("/company/5/privacyNotice"), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 10)));
|
||||
assertThat(service.savePrivacyNotice(5L, Map.of("textEn", "E", "textMs", "M"), "root")).containsEntry("id", 10);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq("/company/5/privacyNotice"), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("textEn", "E").containsEntry("textMs", "M").containsEntry("doneBy", "root");
|
||||
|
||||
when(rest.getForEntity(eq("/company/9/privacyNotice"), any(ParameterizedTypeReference.class))).thenThrow(err(HttpStatus.NOT_FOUND, "{}"));
|
||||
assertThatThrownBy(() -> service.privacyNotice(9L)).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.RegistrationLinkService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
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.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class AdminRegistrationLinkControllerTest {
|
||||
|
||||
private final RegistrationLinkService service = mock(RegistrationLinkService.class);
|
||||
private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new AdminRegistrationLinkController(service)).build();
|
||||
|
||||
private static Method handler(String name) {
|
||||
return Arrays.stream(AdminRegistrationLinkController.class.getDeclaredMethods()).filter(m -> m.getName().equals(name)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyHandlerIsAuthenticatedAndGated() {
|
||||
for (Method m : AdminRegistrationLinkController.class.getDeclaredMethods()) {
|
||||
if (m.isSynthetic() || !Modifier.isPublic(m.getModifiers())) continue;
|
||||
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue();
|
||||
assertThat(m.isAnnotationPresent(AdminModule.class)).as(m.getName()).isTrue();
|
||||
}
|
||||
assertThat(handler("links").getAnnotation(AdminModule.class).value()).containsExactly("BO_EVENTS");
|
||||
assertThat(handler("setEnabled").getAnnotation(AdminModule.class).value()).containsExactly("BO_EVENTS");
|
||||
assertThat(handler("mine").getAnnotation(AdminModule.class).value()).containsExactly(AdminModule.ANY_ADMIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void links_get() throws Exception {
|
||||
when(service.links("77")).thenReturn(Map.of("event", Map.of("token", "ev1", "enabled", true)));
|
||||
mvc.perform(get("/api/admin/events/77/registration-links")).andExpect(status().isOk()).andExpect(jsonPath("$.event.token").value("ev1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void toggle_put() throws Exception {
|
||||
when(service.setEnabled("77", "t1", false)).thenReturn(Map.of("token", "t1", "enabled", false));
|
||||
mvc.perform(put("/api/admin/events/77/registration-links/t1").contentType(MediaType.APPLICATION_JSON).content("{\"enabled\":false}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.enabled").value(false));
|
||||
verify(service).setEnabled("77", "t1", false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void myLinks_get() throws Exception {
|
||||
when(service.mine()).thenReturn(List.of(Map.of("token", "t1")));
|
||||
mvc.perform(get("/api/admin/my-registration-links")).andExpect(status().isOk()).andExpect(jsonPath("$[0].token").value("t1"));
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.solvway.mobile.api.controller.publicapi;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.PublicRegistrationRequest;
|
||||
import com.solvway.mobile.api.service.PublicRegistrationService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Arrays;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class PublicRegistrationControllerTest {
|
||||
|
||||
private final PublicRegistrationService service = mock(PublicRegistrationService.class);
|
||||
private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new PublicRegistrationController(service)).build();
|
||||
|
||||
@Test
|
||||
void everyHandlerSkipsSignIn() {
|
||||
Method[] handlers = Arrays.stream(PublicRegistrationController.class.getDeclaredMethods())
|
||||
.filter(m -> !m.isSynthetic() && Modifier.isPublic(m.getModifiers())).toArray(Method[]::new);
|
||||
assertThat(handlers).hasSize(2);
|
||||
for (Method m : handlers) assertThat(m.getAnnotation(AppAuth.class).skipValidate()).as(m.getName()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsThePage() throws Exception {
|
||||
when(service.page("abc")).thenReturn(Map.of("eventName", "Fair"));
|
||||
mvc.perform(get("/api/public/registration/abc")).andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void post_passesTheBodyAndReturnsEventName() throws Exception {
|
||||
when(service.register(eq("abc"), any())).thenReturn(Map.of("eventName", "Fair"));
|
||||
mvc.perform(post("/api/public/registration/abc").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"A\",\"mobile\":\"0123\",\"consent\":true,\"interestIds\":[3],\"website\":\"\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair"));
|
||||
org.mockito.ArgumentCaptor<PublicRegistrationRequest> c = org.mockito.ArgumentCaptor.forClass(PublicRegistrationRequest.class);
|
||||
verify(service).register(eq("abc"), c.capture());
|
||||
assertThat(c.getValue().consent()).isTrue();
|
||||
assertThat(c.getValue().interestIds()).containsExactly(3L);
|
||||
}
|
||||
}
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.PublicRegistrationRequest;
|
||||
import com.solvway.mobile.api.dto.admin.CompanyEvent;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
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.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class PublicRegistrationServiceTest {
|
||||
|
||||
private static final String LINK = "/counter/registrationLink/findByToken/{token}";
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String COMPANY_URL = "/company/findById/{id}";
|
||||
private static final String NOTICE = "/company/{id}/privacyNotice";
|
||||
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final String REGISTER = "/counter/registration/register";
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long COMPANY = 5L;
|
||||
private static final String TOKEN = "abc123";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private RedisTemplate<String, Object> redis;
|
||||
private ValueOperations<String, Object> ops;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private PublicRegistrationService service;
|
||||
|
||||
private static Clock at(String utc) { return Clock.fixed(Instant.parse(utc), ZoneOffset.UTC); }
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
redis = mock(RedisTemplate.class);
|
||||
ops = mock(ValueOperations.class);
|
||||
when(redis.opsForValue()).thenReturn(ops);
|
||||
when(ops.increment(any())).thenReturn(1L);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getClientIpAddressIfServletRequestExist).thenReturn("1.2.3.4");
|
||||
AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope());
|
||||
service = new PublicRegistrationService(rest, leads, redis, at("2027-01-16T04:00:00Z"));
|
||||
stubLink(true, 21L);
|
||||
stubEvent(true, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
stub(COMPANY_URL, COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "A")));
|
||||
stub(NOTICE, COMPANY, Map.of("id", 9L, "textEn", "English notice", "textMs", "Notis"));
|
||||
stub(TEAM, EV, List.of(Map.of("userId", 21L), Map.of("userId", 22L)));
|
||||
stubUser(21L, true);
|
||||
stubUser(22L, true);
|
||||
stub(INTERESTS, COMPANY, List.of(
|
||||
Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0),
|
||||
Map.of("id", 5L, "companyId", COMPANY, "name", "Old", "active", false, "sortOrder", 1)));
|
||||
when(rest.postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of()));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void stub(String url, Object var, Object body) {
|
||||
when(rest.getForEntity(eq(url), any(ParameterizedTypeReference.class), eq(var))).thenReturn(ResponseEntity.ok(body));
|
||||
}
|
||||
|
||||
private void stubLink(boolean enabled, Long sales) {
|
||||
Map<String, Object> l = new HashMap<>();
|
||||
l.put("token", TOKEN);
|
||||
l.put("enabled", enabled);
|
||||
l.put("eventUuid", EV);
|
||||
l.put("companyId", COMPANY);
|
||||
l.put("salespersonUserId", sales);
|
||||
stub(LINK, TOKEN, l);
|
||||
}
|
||||
|
||||
private void stubEvent(boolean enabled, LocalDateTime end) {
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(COMPANY);
|
||||
e.setUuid(EV);
|
||||
e.setName("KL Food Fair 2027");
|
||||
e.setLocation("MITEC");
|
||||
e.setDateStart(LocalDateTime.of(2027, 1, 15, 0, 0));
|
||||
e.setDateEnd(end);
|
||||
e.setEnabled(enabled ? GeneralEnum.FlagYesNo.Y : GeneralEnum.FlagYesNo.N);
|
||||
stub(EVENT, EV, e);
|
||||
}
|
||||
|
||||
private void stubUser(long id, boolean enabled) {
|
||||
Map<String, Object> u = new HashMap<>();
|
||||
u.put("id", id);
|
||||
u.put("name", "Sales " + id);
|
||||
u.put("type", "A");
|
||||
u.put("companyId", COMPANY);
|
||||
u.put("enabled", enabled);
|
||||
stub(USER, id, u);
|
||||
}
|
||||
|
||||
private static PublicRegistrationRequest req(String website, Boolean consent, List<Long> interests) {
|
||||
return new PublicRegistrationRequest("Aisyah", "012-345 6789", "a@x.com", "Acme", "Chef", interests, consent, website);
|
||||
}
|
||||
|
||||
private static PublicRegistrationRequest ok() { return req(null, true, List.of(3L)); }
|
||||
|
||||
private void assertInactive(Runnable r) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(e.getReason()).isEqualTo("This code is no longer active.");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "CODE_INACTIVE");
|
||||
});
|
||||
}
|
||||
|
||||
// --- GET ---
|
||||
|
||||
@Test
|
||||
void page_unknownToken_inactive() {
|
||||
when(rest.getForEntity(eq(LINK), any(ParameterizedTypeReference.class), eq("nope")))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertInactive(() -> service.page("nope"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_switchedOffLink_inactive() {
|
||||
stubLink(false, 21L);
|
||||
assertInactive(() -> service.page(TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_disabledEvent_inactive() {
|
||||
stubEvent(false, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
assertInactive(() -> service.page(TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_endedEvent_inactive_atMalaysiaDateBoundary() {
|
||||
// 2027-01-17 16:30 UTC is 2027-01-18 00:30 in Kuala Lumpur: the event ended on the 17th.
|
||||
service = svc("2027-01-17T16:30:00Z");
|
||||
assertInactive(() -> service.page(TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_lastDay_stillActive_beforeMalaysiaMidnight() {
|
||||
// 2027-01-17 15:30 UTC is 2027-01-17 23:30 in Kuala Lumpur.
|
||||
service = svc("2027-01-17T15:30:00Z");
|
||||
assertThat(service.page(TOKEN)).containsEntry("eventName", "KL Food Fair 2027");
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_inactiveCompany_inactive() {
|
||||
stub(COMPANY_URL, COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "I")));
|
||||
assertInactive(() -> service.page(TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_noNotice_inactive() {
|
||||
when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertInactive(() -> service.page(TOKEN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_active_payloadHasOnlyActiveInterests() {
|
||||
Map<String, Object> p = service.page(TOKEN);
|
||||
assertThat(p).containsEntry("eventName", "KL Food Fair 2027").containsEntry("startDate", "2027-01-15")
|
||||
.containsEntry("endDate", "2027-01-17").containsEntry("location", "MITEC").containsEntry("companyName", "INS");
|
||||
assertThat((Map<String, Object>) p.get("notice")).containsEntry("id", 9L).containsEntry("textEn", "English notice").containsEntry("textMs", "Notis");
|
||||
assertThat((List<Map<String, Object>>) p.get("interests")).containsExactly(Map.of("id", 3L, "name", "Cookware"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_limit_429_keyedByIp() {
|
||||
when(ops.increment("reg:load:1.2.3.4")).thenReturn(121L);
|
||||
assertThatThrownBy(() -> service.page(TOKEN)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "TOO_MANY");
|
||||
});
|
||||
when(ops.increment("reg:load:1.2.3.4")).thenReturn(120L);
|
||||
assertThat(service.page(TOKEN)).containsKey("eventName");
|
||||
}
|
||||
|
||||
@Test
|
||||
void page_firstHit_setsTenMinuteWindow() {
|
||||
service.page(TOKEN);
|
||||
verify(redis).expire("reg:load:1.2.3.4", 10, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
// --- POST ---
|
||||
|
||||
private Map<String, Object> registered() {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) body.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_inactiveCode_404_andNothingRegistered() {
|
||||
stubLink(false, 21L);
|
||||
assertInactive(() -> service.register(TOKEN, ok()));
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_honeypot_looksLikeSuccess_andRegistersNothing() {
|
||||
assertThat(service.register(TOKEN, req("http://spam", true, List.of(3L)))).containsEntry("eventName", "KL Food Fair 2027");
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_consentMissing_400_withField() {
|
||||
for (Boolean c : new Boolean[]{null, false}) {
|
||||
assertThatThrownBy(() -> service.register(TOKEN, req(null, c, List.of(3L)))).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "CONSENT_REQUIRED");
|
||||
assertThat(String.valueOf(e.getBody().getProperties())).contains("consent");
|
||||
});
|
||||
}
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_validatesLikeStaffCapture() {
|
||||
PublicRegistrationRequest noContact = new PublicRegistrationRequest("Aisyah", " ", null, null, null, List.of(), true, null);
|
||||
assertThatThrownBy(() -> service.register(TOKEN, noContact)).isInstanceOf(CodedResponseStatusException.class)
|
||||
.satisfies(e -> assertThat(((CodedResponseStatusException) e).getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
PublicRegistrationRequest noName = new PublicRegistrationRequest(" ", "0123456789", null, null, null, List.of(), true, null);
|
||||
assertThatThrownBy(() -> service.register(TOKEN, noName)).isInstanceOf(CodedResponseStatusException.class);
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_inactiveInterest_refused() {
|
||||
assertThatThrownBy(() -> service.register(TOKEN, req(null, true, List.of(5L)))).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_happy_sendsNormalisedBody_withServerSideNoticeAndSalesperson() {
|
||||
assertThat(service.register(TOKEN, ok())).containsEntry("eventName", "KL Food Fair 2027");
|
||||
Map<String, Object> b = registered();
|
||||
assertThat(b).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserId", 21L)
|
||||
.containsEntry("name", "Aisyah").containsEntry("email", "a@x.com").containsEntry("companyName", "Acme")
|
||||
.containsEntry("jobTitle", "Chef").containsEntry("interestIds", List.of(3L)).containsEntry("consentNoticeId", 9L);
|
||||
assertThat(b.get("mobileE164")).isEqualTo("+60123456789");
|
||||
assertThat(b.get("consentAt")).isEqualTo("2027-01-16T12:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_salespersonNotOnTeam_isNull() {
|
||||
stub(TEAM, EV, List.of(Map.of("userId", 22L)));
|
||||
service.register(TOKEN, ok());
|
||||
assertThat(registered().get("salespersonUserId")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_salespersonInactive_isNull() {
|
||||
stubUser(21L, false);
|
||||
service.register(TOKEN, ok());
|
||||
assertThat(registered().get("salespersonUserId")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_eventCodeWithoutSalesperson_isNull() {
|
||||
stubLink(true, null);
|
||||
service.register(TOKEN, ok());
|
||||
assertThat(registered().get("salespersonUserId")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_limit_429_keyedByEventAndIp() {
|
||||
when(ops.increment("reg:submit:" + EV + ":1.2.3.4")).thenReturn(61L);
|
||||
assertThatThrownBy(() -> service.register(TOKEN, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS);
|
||||
assertThat(e.getReason()).isEqualTo("Too many registrations from this device. Try again later.");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "TOO_MANY");
|
||||
});
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_deletedSalesperson_isNull_not500() {
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
service.register(TOKEN, ok());
|
||||
assertThat(registered().get("salespersonUserId")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_inactiveToken_stillCountsAndEnforcesTheLoadLimit() {
|
||||
stubLink(false, 21L);
|
||||
assertInactive(() -> service.register(TOKEN, ok()));
|
||||
verify(ops).increment("reg:load:1.2.3.4");
|
||||
when(ops.increment("reg:load:1.2.3.4")).thenReturn(121L);
|
||||
assertThatThrownBy(() -> service.register(TOKEN, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.TOO_MANY_REQUESTS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void register_sameBodyWhateverTheCounterOutcome() {
|
||||
for (String outcome : List.of("CREATED", "LINKED", "ALREADY_CAPTURED", "ASSIGNED")) {
|
||||
when(rest.postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("outcome", outcome)));
|
||||
assertThat(service.register(TOKEN, ok())).as(outcome).isEqualTo(Map.of("eventName", "KL Food Fair 2027"));
|
||||
}
|
||||
}
|
||||
|
||||
private PublicRegistrationService svc(String utc) {
|
||||
return new PublicRegistrationService(rest, new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()), redis, at(utc));
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/** Both new services have a test-clock constructor: Spring must still know which one to use, or mobile-api fails to start. */
|
||||
class PublicRegistrationWiringTest {
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void springCreatesBothServices() {
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.registerBean(RestTemplateCustomUtil.class, () -> mock(RestTemplateCustomUtil.class));
|
||||
ctx.registerBean(AdminAuthenticationService.class, () -> mock(AdminAuthenticationService.class));
|
||||
ctx.registerBean(RedisTemplate.class, () -> mock(RedisTemplate.class));
|
||||
ctx.registerBean(AdminCompanyScope.class);
|
||||
ctx.register(AdminEventLeadService.class, PublicRegistrationService.class, RegistrationLinkService.class);
|
||||
ctx.refresh();
|
||||
assertThat(ctx.getBean(PublicRegistrationService.class)).isNotNull();
|
||||
assertThat(ctx.getBean(RegistrationLinkService.class)).isNotNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.admin.CompanyEvent;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
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.ResponseEntity;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class RegistrationLinkServiceTest {
|
||||
|
||||
private static final String EVENT = "/counter/event/findByUuid/{uuid}";
|
||||
private static final String TEAM = "/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
private static final String USER = "/user/findById/{id}";
|
||||
private static final String ENSURE = "/counter/registrationLink/ensure";
|
||||
private static final String SET = "/counter/registrationLink/setEnabled";
|
||||
private static final String MINE = "/counter/registrationLink/mine";
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long COMPANY = 5L;
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private RegistrationLinkService service;
|
||||
private User caller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
rest = mock(RestTemplateCustomUtil.class);
|
||||
auth = mock(AdminAuthenticationService.class);
|
||||
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
|
||||
http = mockStatic(HttpReqRespUtils.class);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
caller = new User();
|
||||
caller.setId(21L);
|
||||
caller.setUsername("sales1");
|
||||
caller.setCompanyId(COMPANY);
|
||||
when(auth.loadUserByToken("tok")).thenReturn(caller);
|
||||
AdminEventLeadService leads = new AdminEventLeadService(rest, auth, new AdminCompanyScope());
|
||||
service = new RegistrationLinkService(rest, leads, Clock.fixed(Instant.parse("2027-01-16T17:00:00Z"), ZoneOffset.UTC));
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(COMPANY);
|
||||
e.setUuid(EV);
|
||||
e.setDateEnd(LocalDateTime.of(2027, 1, 20, 0, 0));
|
||||
e.setEnabled(GeneralEnum.FlagYesNo.Y);
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
when(rest.getForEntity(eq(TEAM), any(ParameterizedTypeReference.class), eq(EV)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(Map.of("userId", 21L), Map.of("userId", 22L))));
|
||||
stubUser(21L, "Sales One");
|
||||
stubUser(22L, "Sales Two");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void close() { http.close(); }
|
||||
|
||||
private void stubUser(long id, String name) {
|
||||
Map<String, Object> u = new HashMap<>(Map.of("id", id, "name", name, "type", "A", "companyId", COMPANY, "enabled", true));
|
||||
when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id))).thenReturn(ResponseEntity.ok(u));
|
||||
}
|
||||
|
||||
private Map<String, Object> posted(String url) {
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), body.capture());
|
||||
return (Map<String, Object>) body.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void links_ensuresEventAndTeamLinks_andNamesMembers() {
|
||||
Map<String, Object> eventRow = new HashMap<>(Map.of("token", "ev1", "enabled", true));
|
||||
List<Map<String, Object>> rows = List.of(eventRow,
|
||||
Map.of("token", "t21", "enabled", true, "salespersonUserId", 21L),
|
||||
Map.of("token", "t22", "enabled", false, "salespersonUserId", 22L));
|
||||
when(rest.postForEntity(eq(ENSURE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(rows));
|
||||
|
||||
Map<String, Object> out = service.links(String.valueOf(EV));
|
||||
|
||||
assertThat((Map<String, Object>) out.get("event")).containsEntry("token", "ev1").containsEntry("enabled", true);
|
||||
assertThat((List<Map<String, Object>>) out.get("members")).containsExactly(
|
||||
Map.of("userId", 21L, "name", "Sales One", "token", "t21", "enabled", true),
|
||||
Map.of("userId", 22L, "name", "Sales Two", "token", "t22", "enabled", false));
|
||||
assertThat(posted(ENSURE)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("salespersonUserIds", List.of(21L, 22L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setEnabled_passesEventCompanyAndCallerUsername() {
|
||||
when(rest.postForEntity(eq(SET), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("token", "t21", "enabled", false)));
|
||||
assertThat(service.setEnabled(String.valueOf(EV), "t21", false)).containsEntry("enabled", false);
|
||||
assertThat(posted(SET)).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV).containsEntry("token", "t21")
|
||||
.containsEntry("enabled", false).containsEntry("doneBy", "sales1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mine_sendsCallerCompanyIdAndMalaysiaToday() {
|
||||
when(rest.postForEntity(eq(MINE), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(List.of(Map.of("token", "t21"))));
|
||||
assertThat(service.mine()).hasSize(1);
|
||||
// 2027-01-16 17:00 UTC is already 2027-01-17 in Kuala Lumpur.
|
||||
assertThat(posted(MINE)).containsEntry("companyId", COMPANY).containsEntry("userId", 21L).containsEntry("today", "2027-01-17");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mine_withoutCompany_isEmpty_andCallsNothing() {
|
||||
caller.setCompanyId(null);
|
||||
assertThat(service.mine()).isEmpty();
|
||||
org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(MINE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
private void otherCompanyEvent() {
|
||||
CompanyEvent e = new CompanyEvent();
|
||||
e.setCompanyId(6L);
|
||||
e.setUuid(EV);
|
||||
e.setEnabled(GeneralEnum.FlagYesNo.Y);
|
||||
when(rest.getForEntity(eq(EVENT), any(ParameterizedTypeReference.class), eq(EV))).thenReturn(ResponseEntity.ok(e));
|
||||
}
|
||||
|
||||
@Test
|
||||
void links_eventInAnotherCompany_404() {
|
||||
otherCompanyEvent();
|
||||
org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.links(String.valueOf(EV)))
|
||||
.isInstanceOfSatisfying(com.solvway.mobile.api.errorhandler.CodedResponseStatusException.class,
|
||||
x -> assertThat(x.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.NOT_FOUND));
|
||||
org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(ENSURE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setEnabled_eventInAnotherCompany_404() {
|
||||
otherCompanyEvent();
|
||||
org.assertj.core.api.Assertions.assertThatThrownBy(() -> service.setEnabled(String.valueOf(EV), "t21", false))
|
||||
.isInstanceOfSatisfying(com.solvway.mobile.api.errorhandler.CodedResponseStatusException.class,
|
||||
x -> assertThat(x.getStatusCode()).isEqualTo(org.springframework.http.HttpStatus.NOT_FOUND));
|
||||
org.mockito.Mockito.verify(rest, org.mockito.Mockito.never()).postForEntity(eq(SET), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.enums.JwtEnum.JwtCustomClaim;
|
||||
import com.solvway.core.model.AuditEvent;
|
||||
import com.solvway.core.model.Role;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.admin.AdminRegistrationLinkController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
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.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The registration token is a secret-ish link id: switching a link off is audited against the event, never the token. */
|
||||
class AppAccessAspectRegistrationAuditTest {
|
||||
|
||||
private static final String API_KEY = "valid-api-key";
|
||||
private static final String TOK = "admin-tok";
|
||||
private static final String TOPIC = "audit-event-topic";
|
||||
|
||||
@AfterEach
|
||||
void clear() { RequestContextHolder.resetRequestAttributes(); }
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void toggle_recordsTheEventUuid_neverTheToken() throws Throwable {
|
||||
PubSubTemplate pubSubTemplate = mock(PubSubTemplate.class);
|
||||
PubSubUtil pubSubUtil = mock(PubSubUtil.class);
|
||||
JwtTokenUtil jwt = mock(JwtTokenUtil.class);
|
||||
AdminSessionGuard guard = mock(AdminSessionGuard.class);
|
||||
RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
|
||||
ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
|
||||
MethodSignature sig = mock(MethodSignature.class);
|
||||
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
|
||||
cfg.setList(List.of(API_KEY));
|
||||
PubSubConfig pubSubConfig = mock(PubSubConfig.class);
|
||||
pubSubConfig.auditEventTopic = TOPIC;
|
||||
AppAccessAspect aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig,
|
||||
pubSubTemplate, pubSubUtil, cfg, mock(AuthenticationService.class), jwt, guard, rest);
|
||||
|
||||
MockHttpServletRequest req = new MockHttpServletRequest("PUT", "/api/admin/events/3312726793093644288/registration-links/SECRETTOKEN");
|
||||
req.setAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, "/api/admin/events/{uuid}/registration-links/{token}");
|
||||
Map<String, String> vars = new LinkedHashMap<>();
|
||||
vars.put("uuid", "3312726793093644288");
|
||||
vars.put("token", "SECRETTOKEN");
|
||||
req.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, vars);
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(req));
|
||||
|
||||
Method m = Arrays.stream(AdminRegistrationLinkController.class.getMethods()).filter(x -> x.getName().equals("setEnabled")).findFirst().orElseThrow();
|
||||
when(joinPoint.getSignature()).thenReturn(sig);
|
||||
when(sig.getMethod()).thenReturn(m);
|
||||
when(sig.toShortString()).thenReturn("AdminRegistrationLinkController.setEnabled()");
|
||||
User u = new User();
|
||||
u.setEnabled(true);
|
||||
u.setUsername("alice");
|
||||
u.setCompanyId(7L);
|
||||
Role r = new Role();
|
||||
r.setId(1L);
|
||||
u.getRoles().add(r);
|
||||
when(guard.check(eq(TOK), any(Boolean.class))).thenReturn(u);
|
||||
when(rest.getForEntity(any(), any(ParameterizedTypeReference.class), eq("BO")))
|
||||
.thenReturn(ResponseEntity.ok(List.of(Map.of("name", "BO_EVENTS", "roles", List.of(Map.of("id", 1))))));
|
||||
when(joinPoint.proceed()).thenReturn(ResponseEntity.ok("x"));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> h = mockStatic(HttpReqRespUtils.class)) {
|
||||
h.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(API_KEY);
|
||||
h.when(HttpReqRespUtils::getJwtToken).thenReturn(TOK);
|
||||
when(jwt.isTokenExpired(TOK)).thenReturn(false);
|
||||
when(jwt.getCustomClaimFromToken(TOK, JwtCustomClaim.USERTYPE)).thenReturn("A");
|
||||
aspect.appAccessAuthCheck(joinPoint);
|
||||
}
|
||||
|
||||
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
|
||||
verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture());
|
||||
AuditEvent e = (AuditEvent) captor.getValue();
|
||||
assertThat(e.getTargetId()).isEqualTo("3312726793093644288");
|
||||
assertThat(String.valueOf(e.getPathTemplate()) + e.getTargetId() + e.getChanges()).doesNotContain("SECRETTOKEN");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user