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
+7
@@ -55,4 +55,11 @@ public class RestApiCounterServiceConstants {
|
||||
|
||||
//Member Voucher
|
||||
public static final String API_REST_COUNTER_MEMBER_VOUCHER_FIND_ELIGIBILITY="/counter/memberVoucher/findEligibility";
|
||||
|
||||
//Registration links and public self-registration
|
||||
public static final String API_REST_COUNTER_REGISTRATION_LINK_FIND_BY_TOKEN="/counter/registrationLink/findByToken/{token}";
|
||||
public static final String API_REST_COUNTER_REGISTRATION_LINK_ENSURE="/counter/registrationLink/ensure";
|
||||
public static final String API_REST_COUNTER_REGISTRATION_LINK_SET_ENABLED="/counter/registrationLink/setEnabled";
|
||||
public static final String API_REST_COUNTER_REGISTRATION_LINK_MINE="/counter/registrationLink/mine";
|
||||
public static final String API_REST_COUNTER_REGISTRATION_REGISTER="/counter/registration/register";
|
||||
}
|
||||
+1
@@ -99,6 +99,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_COMPANY_FIND_BY_ID = "/company/findById/{id}";
|
||||
public static final String API_REST_COMPANY_SAVE = "/company/save";
|
||||
public static final String API_REST_COMPANY_RENAME_CODE = "/company/{id}/code";
|
||||
public static final String API_REST_COMPANY_PRIVACY_NOTICE = "/company/{id}/privacyNotice";
|
||||
|
||||
//LoginSecurity (admin sign-in lock check and history)
|
||||
public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}";
|
||||
|
||||
+16
-1
@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -59,15 +60,29 @@ public class AdminCompanyController {
|
||||
return ResponseEntity.ok(companies.renameCode(id, body.get("code")));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/{id}/privacy-notice")
|
||||
public ResponseEntity<Map<String, Object>> privacyNotice(@PathVariable Long id) {
|
||||
requireSuper();
|
||||
return ResponseEntity.ok(companies.privacyNotice(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PutMapping("/{id}/privacy-notice")
|
||||
public ResponseEntity<Map<String, Object>> savePrivacyNotice(@PathVariable Long id, @RequestBody Map<String, Object> body) {
|
||||
return ResponseEntity.ok(companies.savePrivacyNotice(id, body, requireSuper().getUsername()));
|
||||
}
|
||||
|
||||
/** Portal body is just {"message"}; the exception still reaches AppAccessAspect first, so the audit has the real status. */
|
||||
@ExceptionHandler(CodedResponseStatusException.class)
|
||||
public ResponseEntity<Map<String, String>> upstream(CodedResponseStatusException e) {
|
||||
return ResponseEntity.status(e.getStatusCode()).body(Map.of("message", String.valueOf(e.getReason())));
|
||||
}
|
||||
|
||||
private void requireSuper() {
|
||||
private User requireSuper() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
scope.requireSuper(caller);
|
||||
return caller;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.service.RegistrationLinkService;
|
||||
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.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** QR registration links for the admin portal. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@RequiredArgsConstructor
|
||||
public class AdminRegistrationLinkController {
|
||||
public record Toggle(Boolean enabled) {}
|
||||
|
||||
private final RegistrationLinkService links;
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
@GetMapping("/events/{uuid}/registration-links")
|
||||
public ResponseEntity<Map<String, Object>> links(@PathVariable String uuid) {
|
||||
return ResponseEntity.ok(links.links(uuid));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_EVENTS")
|
||||
@Audited(targetVariable = "uuid")
|
||||
@PutMapping("/events/{uuid}/registration-links/{token}")
|
||||
public ResponseEntity<Map<String, Object>> setEnabled(@PathVariable String uuid, @PathVariable String token, @RequestBody Toggle body) {
|
||||
return ResponseEntity.ok(links.setEnabled(uuid, token, body.enabled()));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminModule.ANY_ADMIN)
|
||||
@GetMapping("/my-registration-links")
|
||||
public ResponseEntity<List<Map<String, Object>>> mine() {
|
||||
return ResponseEntity.ok(links.mine());
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
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 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.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** QR self-registration for walk-in visitors: no sign-in. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/public/registration")
|
||||
@RequiredArgsConstructor
|
||||
public class PublicRegistrationController {
|
||||
private final PublicRegistrationService registration;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/{token}")
|
||||
public ResponseEntity<Map<String, Object>> page(@PathVariable String token) {
|
||||
return ResponseEntity.ok(registration.page(token));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/{token}")
|
||||
public ResponseEntity<Map<String, Object>> register(@PathVariable String token, @RequestBody PublicRegistrationRequest request) {
|
||||
return ResponseEntity.ok(registration.register(token, request));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.solvway.mobile.api.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** A visitor's self-registration. {@code website} is the honeypot: real visitors never see or fill it. */
|
||||
public record PublicRegistrationRequest(String name, String mobile, String email, String companyName, String jobTitle,
|
||||
List<Long> interestIds, Boolean consent, String website) {
|
||||
}
|
||||
+12
@@ -46,6 +46,18 @@ public class AdminCompanyService {
|
||||
Map.of("code", code)).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> privacyNotice(Long id) {
|
||||
return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> savePrivacyNotice(Long id, Map<String, Object> notice, String doneBy) {
|
||||
Map<String, Object> body = new java.util.LinkedHashMap<>();
|
||||
body.put("textEn", notice.get("textEn"));
|
||||
body.put("textMs", notice.get("textMs"));
|
||||
body.put("doneBy", doneBy);
|
||||
return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE).replace("{id}", String.valueOf(id)), MAP, body).getBody());
|
||||
}
|
||||
|
||||
private static <T> T call(Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
|
||||
+7
-7
@@ -291,7 +291,7 @@ public class AdminEventLeadService {
|
||||
}
|
||||
|
||||
/** Ids must be the company's interests; one newly added must be active, one already on the lead may stay. */
|
||||
private static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
static List<Long> checkedInterests(Map<Long, Map<String, Object>> known, List<Long> requested, List<Long> current) {
|
||||
List<Long> ids = requested == null ? List.of() : new ArrayList<>(new LinkedHashSet<>(requested.stream().filter(Objects::nonNull).toList()));
|
||||
for (Long id : ids) {
|
||||
Map<String, Object> interest = known.get(id);
|
||||
@@ -365,7 +365,7 @@ public class AdminEventLeadService {
|
||||
}
|
||||
|
||||
/** id -> {id, name, active}, in the counter's order (sort order, then name). Interests are one shared list: the counter ignores the path company. */
|
||||
private Map<Long, Map<String, Object>> interests(Long companyId) {
|
||||
Map<Long, Map<String, Object>> interests(Long companyId) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_INTEREST_FIND_BY_COMPANY), MAP_LIST, companyId == null ? 0L : companyId).getBody(); // ponytail: 0 when no company is known; drop the path variable when the counter does
|
||||
Map<Long, Map<String, Object>> out = new LinkedHashMap<>();
|
||||
@@ -376,18 +376,18 @@ public class AdminEventLeadService {
|
||||
return out;
|
||||
}
|
||||
|
||||
private List<Long> teamIds(long eventUuid) {
|
||||
List<Long> teamIds(long eventUuid) {
|
||||
List<Map<String, Object>> rows = restTemplateUtil.getForEntity(
|
||||
url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID), MAP_LIST, eventUuid).getBody();
|
||||
return rows == null ? List.of() : rows.stream().map(m -> ((Number) m.get("userId")).longValue()).toList();
|
||||
}
|
||||
|
||||
private Map<String, Object> user(Long id) {
|
||||
Map<String, Object> user(Long id) {
|
||||
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, id).getBody();
|
||||
}
|
||||
|
||||
/** The event, or 404 when it is missing or outside the caller's scope (staff: own company; super: the requested one, or any). */
|
||||
private CompanyEvent loadEvent(String uuid, Long requestedCompanyId) {
|
||||
CompanyEvent loadEvent(String uuid, Long requestedCompanyId) {
|
||||
long id = parseOr(uuid, AdminEventLeadService::eventNotFound);
|
||||
CompanyEvent event = restTemplateUtil.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, id).getBody();
|
||||
if (event == null) throw eventNotFound();
|
||||
@@ -396,7 +396,7 @@ public class AdminEventLeadService {
|
||||
return event;
|
||||
}
|
||||
|
||||
private User caller() {
|
||||
User caller() {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED", null);
|
||||
return caller;
|
||||
@@ -416,7 +416,7 @@ public class AdminEventLeadService {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isActiveAdminOf(Map<String, Object> user, Long companyId) {
|
||||
static boolean isActiveAdminOf(Map<String, Object> user, Long companyId) {
|
||||
return isActiveAdmin(user) && user.get("companyId") instanceof Number n && companyId != null && n.longValue() == companyId;
|
||||
}
|
||||
|
||||
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
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.util.RestTemplateCustomUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.maxLength;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.parseOr;
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.trimmed;
|
||||
|
||||
/**
|
||||
* Public QR self-registration: no sign-in, so every answer about a code that cannot be used is the same 404.
|
||||
* Validation is the staff capture's (AdminEventLeadService helpers). Never log a visitor's name, mobile or email, or the token.
|
||||
*/
|
||||
@Service
|
||||
@SuppressWarnings("unchecked")
|
||||
public class PublicRegistrationService {
|
||||
static final ZoneId MALAYSIA = ZoneId.of("Asia/Kuala_Lumpur");
|
||||
private static final int LOAD_LIMIT = 120;
|
||||
private static final int SUBMIT_LIMIT = 60;
|
||||
private static final long WINDOW_MINUTES = 10;
|
||||
|
||||
private static final ParameterizedTypeReference<CompanyEvent> EVENT = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final AdminEventLeadService leads;
|
||||
private final RedisTemplate<String, Object> redis;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate<String, Object> redis) {
|
||||
this(rest, leads, redis, Clock.systemUTC());
|
||||
}
|
||||
|
||||
PublicRegistrationService(RestTemplateCustomUtil rest, AdminEventLeadService leads, RedisTemplate<String, Object> redis, Clock clock) {
|
||||
this.rest = rest;
|
||||
this.leads = leads;
|
||||
this.redis = redis;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/** What a valid code is for: the usable link, its event, the company's name and its current notice. */
|
||||
private record Open(Map<String, Object> link, CompanyEvent event, String companyName, Map<String, Object> notice) {}
|
||||
|
||||
public Map<String, Object> page(String token) {
|
||||
limit("reg:load:" + ip(), LOAD_LIMIT);
|
||||
Open o = open(token);
|
||||
CompanyEvent e = o.event();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("eventName", e.getName());
|
||||
out.put("startDate", e.getDateStart() == null ? null : e.getDateStart().toLocalDate().toString());
|
||||
out.put("endDate", e.getDateEnd().toLocalDate().toString());
|
||||
out.put("location", e.getLocation());
|
||||
out.put("companyName", o.companyName());
|
||||
out.put("notice", Map.of("id", o.notice().get("id"), "textEn", String.valueOf(o.notice().get("textEn")), "textMs", String.valueOf(o.notice().get("textMs"))));
|
||||
out.put("interests", leads.interests(e.getCompanyId()).values().stream()
|
||||
.filter(i -> Boolean.TRUE.equals(i.get("active"))).map(i -> Map.of("id", i.get("id"), "name", i.get("name"))).toList());
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> register(String token, PublicRegistrationRequest r) {
|
||||
limit("reg:load:" + ip(), LOAD_LIMIT); // counts token guessing by POST too
|
||||
Open o = open(token);
|
||||
CompanyEvent e = o.event();
|
||||
Map<String, Object> done = Map.of("eventName", String.valueOf(e.getName()));
|
||||
if (r.website() != null && !r.website().isBlank()) return done; // honeypot: look like success, store nothing
|
||||
limit("reg:submit:" + e.getUuid() + ":" + ip(), SUBMIT_LIMIT);
|
||||
|
||||
String name = trimmed(r.name());
|
||||
String mobile = AdminEventLeadService.mobile(r.mobile());
|
||||
String email = AdminEventLeadService.email(r.email());
|
||||
List<String> missing = new ArrayList<>();
|
||||
if (name == null) missing.add("name");
|
||||
if (mobile == null && email == null) { missing.add("mobile"); missing.add("email"); }
|
||||
if (!missing.isEmpty()) throw AdminEventLeadService.required(missing);
|
||||
maxLength("name", name, 100);
|
||||
maxLength("email", email, 254);
|
||||
String companyName = maxLength("companyName", trimmed(r.companyName()), 150);
|
||||
String jobTitle = maxLength("jobTitle", trimmed(r.jobTitle()), 100);
|
||||
List<Long> interestIds = AdminEventLeadService.checkedInterests(leads.interests(e.getCompanyId()), r.interestIds(), List.of());
|
||||
if (!Boolean.TRUE.equals(r.consent())) throw error(HttpStatus.BAD_REQUEST, "Please agree to the privacy notice", "CONSENT_REQUIRED", "consent");
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", e.getCompanyId());
|
||||
body.put("eventUuid", e.getUuid());
|
||||
body.put("salespersonUserId", salesperson(o.link(), e));
|
||||
body.put("name", name);
|
||||
body.put("mobileE164", mobile);
|
||||
body.put("email", email);
|
||||
body.put("companyName", companyName);
|
||||
body.put("jobTitle", jobTitle);
|
||||
body.put("interestIds", interestIds);
|
||||
body.put("consentNoticeId", o.notice().get("id"));
|
||||
body.put("consentAt", LocalDateTime.now(clock.withZone(MALAYSIA)).toString());
|
||||
rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_REGISTER), MAP, body);
|
||||
return done;
|
||||
}
|
||||
|
||||
/** The link's salesperson only while still on the event's team and an active admin of the company, else the event code's null. */
|
||||
private Long salesperson(Map<String, Object> link, CompanyEvent e) {
|
||||
if (!(link.get("salespersonUserId") instanceof Number n)) return null;
|
||||
long id = n.longValue();
|
||||
return leads.teamIds(e.getUuid()).contains(id) && AdminEventLeadService.isActiveAdminOf(found(() -> leads.user(id)), e.getCompanyId()) ? id : null;
|
||||
}
|
||||
|
||||
private Open open(String token) {
|
||||
Map<String, Object> link = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_FIND_BY_TOKEN), MAP, token).getBody());
|
||||
if (link == null || !Boolean.TRUE.equals(link.get("enabled")) || !(link.get("eventUuid") instanceof Number uuid)) throw inactive();
|
||||
CompanyEvent e = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID), EVENT, uuid.longValue()).getBody());
|
||||
LocalDate today = LocalDate.now(clock.withZone(MALAYSIA));
|
||||
if (e == null || e.getEnabled() != GeneralEnum.FlagYesNo.Y || e.getDateEnd() == null || e.getDateEnd().toLocalDate().isBefore(today)
|
||||
|| e.getCompanyId() == null || !(link.get("companyId") instanceof Number c) || c.longValue() != e.getCompanyId()) throw inactive();
|
||||
Map<String, Object> company = found(() -> rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID), MAP, e.getCompanyId()).getBody());
|
||||
if (company == null || !"A".equals(company.get("status"))) throw inactive();
|
||||
Map<String, Object> notice = found(() -> rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_PRIVACY_NOTICE), MAP, e.getCompanyId()).getBody());
|
||||
if (notice == null || notice.get("id") == null) throw inactive();
|
||||
return new Open(link, e, String.valueOf(company.get("name")), notice);
|
||||
}
|
||||
|
||||
/** A backend 404 and an empty body both mean "not there". */
|
||||
private static <T> T found(Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fixed-window counter per key. ponytail: INCR then EXPIRE is not atomic; a crash between them leaves a key without expiry, move to a Lua script if that bites. */
|
||||
private void limit(String key, int max) {
|
||||
Long n = redis.opsForValue().increment(key);
|
||||
if (n != null && n == 1) redis.expire(key, WINDOW_MINUTES, TimeUnit.MINUTES);
|
||||
if (n != null && n > max) throw error(HttpStatus.TOO_MANY_REQUESTS, "Too many registrations from this device. Try again later.", "TOO_MANY", null);
|
||||
}
|
||||
|
||||
private static String ip() {
|
||||
return HttpReqRespUtils.getClientIpAddressIfServletRequestExist();
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException inactive() {
|
||||
return error(HttpStatus.NOT_FOUND, "This code is no longer active.", "CODE_INACTIVE", null);
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.dto.admin.CompanyEvent;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
|
||||
/** Admin side of QR registration: an event's links (event code and one per team member), switching one off, and a salesperson's own links. */
|
||||
@Service
|
||||
public class RegistrationLinkService {
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<Map<String, Object>>> MAP_LIST = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final AdminEventLeadService leads;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public RegistrationLinkService(RestTemplateCustomUtil rest, AdminEventLeadService leads) {
|
||||
this(rest, leads, Clock.systemUTC());
|
||||
}
|
||||
|
||||
RegistrationLinkService(RestTemplateCustomUtil rest, AdminEventLeadService leads, Clock clock) {
|
||||
this.rest = rest;
|
||||
this.leads = leads;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Map<String, Object> links(String eventUuid) {
|
||||
CompanyEvent event = leads.loadEvent(eventUuid, null);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", event.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("salespersonUserIds", leads.teamIds(event.getUuid()));
|
||||
List<Map<String, Object>> rows = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_ENSURE), MAP_LIST, body).getBody();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
List<Map<String, Object>> members = new ArrayList<>();
|
||||
out.put("members", members);
|
||||
for (Map<String, Object> row : rows == null ? List.<Map<String, Object>>of() : rows) {
|
||||
if (!(row.get("salespersonUserId") instanceof Number id)) {
|
||||
out.put("event", Map.of("token", row.get("token"), "enabled", row.get("enabled")));
|
||||
continue;
|
||||
}
|
||||
Map<String, Object> u = leads.user(id.longValue());
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("userId", id.longValue());
|
||||
m.put("name", u == null ? String.valueOf(id) : String.valueOf(u.get("name")));
|
||||
m.put("token", row.get("token"));
|
||||
m.put("enabled", row.get("enabled"));
|
||||
members.add(m);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> setEnabled(String eventUuid, String token, Boolean enabled) {
|
||||
if (enabled == null) throw AdminEventLeadService.required(List.of("enabled"));
|
||||
User caller = leads.caller();
|
||||
CompanyEvent event = leads.loadEvent(eventUuid, null);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", event.getCompanyId());
|
||||
body.put("eventUuid", event.getUuid());
|
||||
body.put("token", token);
|
||||
body.put("enabled", enabled);
|
||||
body.put("doneBy", caller.getUsername());
|
||||
try {
|
||||
return rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_SET_ENABLED), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
throw error(HttpStatus.NOT_FOUND, "Registration link not found", "LINK_NOT_FOUND", null);
|
||||
}
|
||||
}
|
||||
|
||||
/** The caller's own links for events still running; a user with no company (super admin) has none. */
|
||||
public List<Map<String, Object>> mine() {
|
||||
User caller = leads.caller();
|
||||
if (caller.getCompanyId() == null) return List.of();
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", caller.getCompanyId());
|
||||
body.put("userId", caller.getId());
|
||||
body.put("today", LocalDate.now(clock.withZone(PublicRegistrationService.MALAYSIA)).toString());
|
||||
List<Map<String, Object>> rows = rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_LINK_MINE), MAP_LIST, body).getBody();
|
||||
return rows == null ? List.of() : rows;
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -187,7 +187,11 @@ public class AppAccessAspect {
|
||||
&& request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE) instanceof Map<?, ?> vars
|
||||
&& !vars.isEmpty()) {
|
||||
Object last = null;
|
||||
for (Object v : vars.values()) last = v;
|
||||
if (audited != null && StringUtils.hasText(audited.targetVariable())) {
|
||||
last = vars.get(audited.targetVariable());
|
||||
} else {
|
||||
for (Object v : vars.values()) last = v;
|
||||
}
|
||||
event.setTargetId(String.valueOf(last));
|
||||
}
|
||||
event.setHttpStatus(status);
|
||||
|
||||
@@ -22,4 +22,7 @@ public @interface Audited {
|
||||
|
||||
/** False when the path variable is free text a person typed (e.g. a username from a failed sign-in): no target is recorded. */
|
||||
boolean target() default true;
|
||||
|
||||
/** Path variable to record as the target; empty means the last one. Set it when the last variable is a secret (e.g. a registration token). */
|
||||
String targetVariable() default "";
|
||||
}
|
||||
+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