feat: public invite and check-in endpoints with abuse limits
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
c700e12865
commit
2f15b117d9
7 files changed
+901
-21
No files matched your search
+5
@@ -40,6 +40,11 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_EVENT_GUEST_REMOVE = "/counter/eventGuest/remove";
|
||||
public static final String API_REST_COUNTER_EVENT_GUEST_MARK_SENT = "/counter/eventGuest/markSent";
|
||||
public static final String API_REST_COUNTER_CHECKIN_ENSURE_TOKEN = "/counter/checkin/ensureToken";
|
||||
public static final String API_REST_COUNTER_EVENT_GUEST_FIND_BY_TOKEN = "/counter/eventGuest/findByToken/{token}";
|
||||
public static final String API_REST_COUNTER_EVENT_GUEST_REGISTER = "/counter/eventGuest/register";
|
||||
public static final String API_REST_COUNTER_CHECKIN_FIND_EVENT = "/counter/checkin/findEvent/{token}";
|
||||
public static final String API_REST_COUNTER_CHECKIN_LOOKUP = "/counter/checkin/lookup";
|
||||
public static final String API_REST_COUNTER_CHECKIN_BY_GUEST = "/counter/checkin/byGuest";
|
||||
public static final String API_REST_COUNTER_EVENT_ATTENDANCE = "/counter/event/attendance";
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_FIND_BY_EVENT_UUID="/counter/eventSalesperson/findByEventUuid/{eventUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_SALESPERSON_REPLACE="/counter/eventSalesperson/replace";
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.solvway.mobile.api.controller.publicapi;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.PublicCheckinLookupRequest;
|
||||
import com.solvway.mobile.api.dto.PublicRegistrationRequest;
|
||||
import com.solvway.mobile.api.service.PublicInviteService;
|
||||
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;
|
||||
|
||||
/** Guest invitations and event check-in: no sign-in. Must stay under {@code controller..} for AppAccessAspect. */
|
||||
@RestController
|
||||
@RequestMapping("/api/public")
|
||||
@RequiredArgsConstructor
|
||||
public class PublicInviteController {
|
||||
private final PublicInviteService invites;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/invite/{token}")
|
||||
public ResponseEntity<Map<String, Object>> invite(@PathVariable String token) {
|
||||
return ResponseEntity.ok(invites.invite(token));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/invite/{token}")
|
||||
public ResponseEntity<Map<String, Object>> register(@PathVariable String token, @RequestBody PublicRegistrationRequest request) {
|
||||
return ResponseEntity.ok(invites.inviteRegister(token, request));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/invite/{token}/checkin")
|
||||
public ResponseEntity<Map<String, Object>> inviteCheckin(@PathVariable String token) {
|
||||
return ResponseEntity.ok(invites.inviteCheckin(token));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/checkin/{token}")
|
||||
public ResponseEntity<Map<String, Object>> checkin(@PathVariable String token) {
|
||||
return ResponseEntity.ok(invites.checkin(token));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/checkin/{token}/lookup")
|
||||
public ResponseEntity<Map<String, Object>> lookup(@PathVariable String token, @RequestBody PublicCheckinLookupRequest request) {
|
||||
return ResponseEntity.ok(invites.lookup(token, request));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/checkin/{token}/register")
|
||||
public ResponseEntity<Map<String, Object>> walkIn(@PathVariable String token, @RequestBody PublicRegistrationRequest request) {
|
||||
return ResponseEntity.ok(invites.walkIn(token, request));
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.solvway.mobile.api.dto;
|
||||
|
||||
/** The check-in page's one box: an email when it contains '@', else a mobile. */
|
||||
public record PublicCheckinLookupRequest(String value) {
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.dto.PublicCheckinLookupRequest;
|
||||
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.service.PublicRegistrationService.Open;
|
||||
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.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import static com.solvway.mobile.api.service.AdminEventLeadService.error;
|
||||
import static com.solvway.mobile.api.service.PublicRegistrationService.found;
|
||||
import static com.solvway.mobile.api.service.PublicRegistrationService.ip;
|
||||
|
||||
/**
|
||||
* Public guest-invite and event check-in pages: no sign-in, so every unusable token is the same 404.
|
||||
* Shares the QR registration's loading, validation and rate-limit helpers. Never log a visitor's details or a token.
|
||||
*/
|
||||
@Service
|
||||
@SuppressWarnings("unchecked")
|
||||
public class PublicInviteService {
|
||||
private static final int INVITE_LOAD_LIMIT = 120;
|
||||
private static final int INVITE_SUBMIT_LIMIT = 60;
|
||||
private static final int CHECKIN_LIMIT = 300;
|
||||
private static final String TOO_MANY = "Too many attempts. Try again later.";
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final PublicRegistrationService reg;
|
||||
|
||||
@Autowired
|
||||
public PublicInviteService(RestTemplateCustomUtil rest, PublicRegistrationService reg) {
|
||||
this.rest = rest;
|
||||
this.reg = reg;
|
||||
}
|
||||
|
||||
// --- invite ---
|
||||
|
||||
/** An invitation's guest row and its usable event. */
|
||||
private record Invite(Map<String, Object> guest, Open open) {}
|
||||
|
||||
public Map<String, Object> invite(String token) {
|
||||
reg.limit("inv:load:" + ip(), INVITE_LOAD_LIMIT, TOO_MANY);
|
||||
Invite i = openInvite(token);
|
||||
Map<String, Object> g = i.guest();
|
||||
Map<String, Object> out = new LinkedHashMap<>(reg.eventView(i.open()));
|
||||
Map<String, Object> guest = new LinkedHashMap<>();
|
||||
guest.put("name", g.get("name"));
|
||||
guest.put("mobile", g.get("mobileE164"));
|
||||
guest.put("email", g.get("email"));
|
||||
guest.put("companyName", g.get("companyName"));
|
||||
out.put("guest", guest);
|
||||
out.put("state", !Boolean.TRUE.equals(g.get("registered")) ? "OPEN" : Boolean.TRUE.equals(g.get("attended")) ? "CHECKED_IN"
|
||||
: reg.eventDay(i.open().event()) ? "CHECKIN" : "REGISTERED");
|
||||
return out;
|
||||
}
|
||||
|
||||
public Map<String, Object> inviteRegister(String token, PublicRegistrationRequest r) {
|
||||
reg.limit("inv:load:" + ip(), INVITE_LOAD_LIMIT, TOO_MANY); // counts token guessing by POST too
|
||||
Invite i = openInvite(token);
|
||||
CompanyEvent e = i.open().event();
|
||||
Map<String, Object> done = PublicRegistrationService.done(e);
|
||||
if (PublicRegistrationService.honeypot(r)) return done;
|
||||
reg.limit("inv:submit:" + e.getUuid() + ":" + ip(), INVITE_SUBMIT_LIMIT, TOO_MANY);
|
||||
Map<String, Object> body = reg.form(i.open(), r);
|
||||
body.put("guestToken", token);
|
||||
post(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_REGISTER, body);
|
||||
return done;
|
||||
}
|
||||
|
||||
public Map<String, Object> inviteCheckin(String token) {
|
||||
reg.limit("inv:load:" + ip(), INVITE_LOAD_LIMIT, TOO_MANY);
|
||||
Invite i = openInvite(token);
|
||||
CompanyEvent e = i.open().event();
|
||||
reg.limit("inv:submit:" + e.getUuid() + ":" + ip(), INVITE_SUBMIT_LIMIT, TOO_MANY);
|
||||
return Map.of("firstName", firstName(post(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_BY_GUEST, Map.of("companyId", e.getCompanyId(), "guestToken", token))));
|
||||
}
|
||||
|
||||
private Invite openInvite(String token) {
|
||||
if (!PublicRegistrationService.TOKEN_SHAPE.matcher(String.valueOf(token)).matches()) throw inviteInactive();
|
||||
Map<String, Object> guest = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GUEST_FIND_BY_TOKEN), MAP, token).getBody());
|
||||
if (guest == null) throw inviteInactive();
|
||||
Open o = reg.load(guest, true);
|
||||
if (o == null) throw inviteInactive();
|
||||
return new Invite(guest, o);
|
||||
}
|
||||
|
||||
// --- check-in ---
|
||||
|
||||
public Map<String, Object> checkin(String token) {
|
||||
Open o = openCheckin(token);
|
||||
CompanyEvent e = o.event();
|
||||
if (reg.eventDay(e)) {
|
||||
Map<String, Object> out = new LinkedHashMap<>(reg.eventView(o));
|
||||
out.put("state", "OPEN");
|
||||
return out;
|
||||
}
|
||||
return Map.of("state", reg.ended(e) ? "ENDED" : "NOT_YET", "startDate", String.valueOf(startDate(e)));
|
||||
}
|
||||
|
||||
public Map<String, Object> lookup(String token, PublicCheckinLookupRequest r) {
|
||||
Open o = openCheckin(token);
|
||||
String value = AdminEventLeadService.trimmed(r.value());
|
||||
if (value == null) throw AdminEventLeadService.required(List.of("value"));
|
||||
boolean email = value.contains("@");
|
||||
String normalised = onValue(() -> email ? AdminEventLeadService.email(value) : AdminEventLeadService.mobile(value));
|
||||
if (normalised == null) throw AdminEventLeadService.required(List.of("value"));
|
||||
eventDay(o);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("companyId", o.event().getCompanyId());
|
||||
body.put("eventUuid", o.event().getUuid());
|
||||
body.put(email ? "email" : "mobileE164", normalised);
|
||||
Map<String, Object> out = post(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_LOOKUP, body);
|
||||
if (out != null && "CHECKED_IN".equals(out.get("result"))) return Map.of("result", "CHECKED_IN", "firstName", firstName(out));
|
||||
return Map.of("result", "FORM");
|
||||
}
|
||||
|
||||
public Map<String, Object> walkIn(String token, PublicRegistrationRequest r) {
|
||||
Open o = openCheckin(token);
|
||||
Map<String, Object> done = PublicRegistrationService.done(o.event());
|
||||
eventDay(o); // before the honeypot: a bot never gets the event name from a closed code
|
||||
if (PublicRegistrationService.honeypot(r)) return done;
|
||||
Map<String, Object> body = reg.form(o, r);
|
||||
body.put("eventUuid", o.event().getUuid());
|
||||
body.put("attend", true);
|
||||
post(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_REGISTER, body); // no salesperson: a walk-in has none
|
||||
return done;
|
||||
}
|
||||
|
||||
private Open openCheckin(String token) {
|
||||
if (!PublicRegistrationService.TOKEN_SHAPE.matcher(String.valueOf(token)).matches()) throw codeInactive();
|
||||
reg.limit("chk:load:" + ip(), CHECKIN_LIMIT, TOO_MANY); // counts unknown tokens too, before the lookup
|
||||
Map<String, Object> link = found(() -> rest.getForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CHECKIN_FIND_EVENT), MAP, token).getBody());
|
||||
if (link == null || !(link.get("eventUuid") instanceof Number uuid)) throw codeInactive();
|
||||
reg.limit("chk:" + uuid + ":" + ip(), CHECKIN_LIMIT, TOO_MANY);
|
||||
Open o = reg.load(link, false);
|
||||
if (o == null) throw codeInactive();
|
||||
return o;
|
||||
}
|
||||
|
||||
private void eventDay(Open o) {
|
||||
if (!reg.eventDay(o.event())) throw error(HttpStatus.CONFLICT, "Check-in opens on the event day", "NOT_EVENT_DAY", null);
|
||||
}
|
||||
|
||||
private static Object startDate(CompanyEvent e) {
|
||||
return (e.getDateStart() == null ? e.getDateEnd() : e.getDateStart()).toLocalDate();
|
||||
}
|
||||
|
||||
// --- shared ---
|
||||
|
||||
private static String onValue(Supplier<String> normalise) {
|
||||
try {
|
||||
return normalise.get();
|
||||
} catch (CodedResponseStatusException e) {
|
||||
throw error((HttpStatus) e.getStatusCode(), e.getReason(), e.getCode(), "value");
|
||||
}
|
||||
}
|
||||
|
||||
/** A counter 409 (EVENT_FULL, NOT_REGISTERED, NOT_EVENT_DAY) goes to the visitor with its own code. */
|
||||
private Map<String, Object> post(String api, Object body) {
|
||||
try {
|
||||
return rest.postForEntity(url(api), MAP, body).getBody();
|
||||
} catch (HttpClientErrorException.Conflict e) {
|
||||
String code = counterCode(e);
|
||||
throw error(HttpStatus.CONFLICT, switch (code) {
|
||||
case "EVENT_FULL" -> "This event is full";
|
||||
case "NOT_REGISTERED" -> "Register before checking in";
|
||||
case "NOT_EVENT_DAY" -> "Check-in opens on the event day";
|
||||
default -> "This could not be completed";
|
||||
}, code, null);
|
||||
}
|
||||
}
|
||||
|
||||
private static String counterCode(HttpClientErrorException e) {
|
||||
try {
|
||||
String v = new ObjectMapper().readTree(e.getResponseBodyAsString()).path("code").asText();
|
||||
return v.isEmpty() ? "CONFLICT" : v;
|
||||
} catch (Exception ex) {
|
||||
return "CONFLICT";
|
||||
}
|
||||
}
|
||||
|
||||
private static String firstName(Map<String, Object> out) {
|
||||
return out == null || out.get("firstName") == null ? "" : String.valueOf(out.get("firstName"));
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException inviteInactive() {
|
||||
return error(HttpStatus.NOT_FOUND, "This invitation is no longer active.", "INVITE_INACTIVE", null);
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException codeInactive() {
|
||||
return error(HttpStatus.NOT_FOUND, "This code is no longer active.", "CODE_INACTIVE", null);
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+68
-21
@@ -66,11 +66,15 @@ public class PublicRegistrationService {
|
||||
}
|
||||
|
||||
/** 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) {}
|
||||
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);
|
||||
return eventView(open(token));
|
||||
}
|
||||
|
||||
/** The event, company, notice and active interests a public form shows. */
|
||||
Map<String, Object> eventView(Open o) {
|
||||
CompanyEvent e = o.event();
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("eventName", e.getName());
|
||||
@@ -88,10 +92,28 @@ public class PublicRegistrationService {
|
||||
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
|
||||
Map<String, Object> done = done(e);
|
||||
if (honeypot(r)) return done; // look like success, store nothing
|
||||
limit("reg:submit:" + e.getUuid() + ":" + ip(), SUBMIT_LIMIT);
|
||||
|
||||
Map<String, Object> body = form(o, r);
|
||||
body.put("eventUuid", e.getUuid());
|
||||
body.put("salespersonUserId", salesperson(o.link(), e));
|
||||
rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_REGISTRATION_REGISTER), MAP, body);
|
||||
return done;
|
||||
}
|
||||
|
||||
static Map<String, Object> done(CompanyEvent e) {
|
||||
return Map.of("eventName", String.valueOf(e.getName()));
|
||||
}
|
||||
|
||||
static boolean honeypot(PublicRegistrationRequest r) {
|
||||
return r.website() != null && !r.website().isBlank();
|
||||
}
|
||||
|
||||
/** Validates and normalises a visitor's form like staff capture; the body the counter takes, minus event, guest and salesperson. */
|
||||
Map<String, Object> form(Open o, PublicRegistrationRequest r) {
|
||||
CompanyEvent e = o.event();
|
||||
String name = trimmed(r.name());
|
||||
String mobile = AdminEventLeadService.mobile(r.mobile());
|
||||
String email = AdminEventLeadService.email(r.email());
|
||||
@@ -108,8 +130,6 @@ public class PublicRegistrationService {
|
||||
|
||||
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);
|
||||
@@ -118,8 +138,7 @@ public class PublicRegistrationService {
|
||||
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;
|
||||
return body;
|
||||
}
|
||||
|
||||
/** 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. */
|
||||
@@ -139,25 +158,49 @@ public class PublicRegistrationService {
|
||||
}
|
||||
|
||||
/** The gateway lets only this token shape through unsigned; anything else would come back 401 and surface as a 500. */
|
||||
private static final java.util.regex.Pattern TOKEN_SHAPE = java.util.regex.Pattern.compile("[A-Za-z0-9_-]{22}");
|
||||
static final java.util.regex.Pattern TOKEN_SHAPE = java.util.regex.Pattern.compile("[A-Za-z0-9_-]{22}");
|
||||
|
||||
private Open open(String token) {
|
||||
if (token == null || !TOKEN_SHAPE.matcher(token).matches()) throw inactive();
|
||||
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();
|
||||
if (link == null || !Boolean.TRUE.equals(link.get("enabled"))) throw inactive();
|
||||
Open o = load(link, true);
|
||||
if (o == null) throw inactive();
|
||||
return o;
|
||||
}
|
||||
|
||||
/** The link's (or guest's) enabled event with its company and notice, or null when anything is missing. activeOnly also rejects an ended event, before the company and notice fetches. */
|
||||
Open load(Map<String, Object> link, boolean activeOnly) {
|
||||
if (!(link.get("eventUuid") instanceof Number uuid)) return null;
|
||||
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();
|
||||
if (e == null || e.getEnabled() != GeneralEnum.FlagYesNo.Y || e.getDateEnd() == null
|
||||
|| e.getCompanyId() == null || !(link.get("companyId") instanceof Number c) || c.longValue() != e.getCompanyId()
|
||||
|| activeOnly && ended(e)) return null;
|
||||
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();
|
||||
if (company == null || !"A".equals(company.get("status"))) return null;
|
||||
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();
|
||||
if (notice == null || notice.get("id") == null) return null;
|
||||
return new Open(link, e, String.valueOf(company.get("name")), notice);
|
||||
}
|
||||
|
||||
LocalDate today() {
|
||||
return LocalDate.now(clock.withZone(MALAYSIA));
|
||||
}
|
||||
|
||||
boolean ended(CompanyEvent e) {
|
||||
return e.getDateEnd().toLocalDate().isBefore(today());
|
||||
}
|
||||
|
||||
/** Malaysia dates from the start (the end when none) through the end, inclusive. */
|
||||
boolean eventDay(CompanyEvent e) {
|
||||
LocalDate end = e.getDateEnd().toLocalDate();
|
||||
LocalDate start = e.getDateStart() == null ? end : e.getDateStart().toLocalDate();
|
||||
LocalDate t = today();
|
||||
return !t.isBefore(start) && !t.isAfter(end);
|
||||
}
|
||||
|
||||
/** A backend 404 and an empty body both mean "not there". */
|
||||
private static <T> T found(Supplier<T> call) {
|
||||
static <T> T found(Supplier<T> call) {
|
||||
try {
|
||||
return call.get();
|
||||
} catch (HttpClientErrorException.NotFound e) {
|
||||
@@ -167,12 +210,16 @@ public class PublicRegistrationService {
|
||||
|
||||
/** 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);
|
||||
limit(key, max, "Too many registrations from this device. Try again later.");
|
||||
}
|
||||
|
||||
private static String ip() {
|
||||
void limit(String key, int max, String message) {
|
||||
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, message, "TOO_MANY", null);
|
||||
}
|
||||
|
||||
static String ip() {
|
||||
return HttpReqRespUtils.getClientIpAddressIfServletRequestExist();
|
||||
}
|
||||
|
||||
@@ -180,7 +227,7 @@ public class PublicRegistrationService {
|
||||
return error(HttpStatus.NOT_FOUND, "This code is no longer active.", "CODE_INACTIVE", null);
|
||||
}
|
||||
|
||||
private String url(String api) {
|
||||
String url(String api) {
|
||||
return rest.getURLforApiService(api);
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.solvway.mobile.api.controller.publicapi;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.PublicCheckinLookupRequest;
|
||||
import com.solvway.mobile.api.dto.PublicRegistrationRequest;
|
||||
import com.solvway.mobile.api.service.PublicInviteService;
|
||||
import com.solvway.mobile.api.service.PublicRegistrationService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
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 PublicInviteControllerTest {
|
||||
|
||||
private final PublicInviteService service = mock(PublicInviteService.class);
|
||||
private final MockMvc mvc = MockMvcBuilders.standaloneSetup(new PublicInviteController(service)).build();
|
||||
|
||||
@Test
|
||||
void everyHandlerSkipsSignIn() {
|
||||
Method[] handlers = Arrays.stream(PublicInviteController.class.getDeclaredMethods())
|
||||
.filter(m -> !m.isSynthetic() && Modifier.isPublic(m.getModifiers())).toArray(Method[]::new);
|
||||
assertThat(handlers).hasSize(6);
|
||||
for (Method m : handlers) assertThat(m.getAnnotation(AppAuth.class).skipValidate()).as(m.getName()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void routes() throws Exception {
|
||||
when(service.invite("t")).thenReturn(Map.of("state", "OPEN"));
|
||||
when(service.inviteRegister(eq("t"), any())).thenReturn(Map.of("eventName", "Fair"));
|
||||
when(service.inviteCheckin("t")).thenReturn(Map.of("firstName", "A"));
|
||||
when(service.checkin("t")).thenReturn(Map.of("state", "OPEN"));
|
||||
when(service.lookup(eq("t"), any())).thenReturn(Map.of("result", "FORM"));
|
||||
when(service.walkIn(eq("t"), any())).thenReturn(Map.of("eventName", "Fair"));
|
||||
mvc.perform(get("/api/public/invite/t")).andExpect(status().isOk()).andExpect(jsonPath("$.state").value("OPEN"));
|
||||
mvc.perform(post("/api/public/invite/t").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"A\",\"consent\":true}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair"));
|
||||
mvc.perform(post("/api/public/invite/t/checkin")).andExpect(status().isOk()).andExpect(jsonPath("$.firstName").value("A"));
|
||||
mvc.perform(get("/api/public/checkin/t")).andExpect(status().isOk()).andExpect(jsonPath("$.state").value("OPEN"));
|
||||
mvc.perform(post("/api/public/checkin/t/lookup").contentType(MediaType.APPLICATION_JSON).content("{\"value\":\"a@x.com\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.result").value("FORM"));
|
||||
mvc.perform(post("/api/public/checkin/t/register").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"A\",\"consent\":true}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.eventName").value("Fair"));
|
||||
ArgumentCaptor<PublicCheckinLookupRequest> c = ArgumentCaptor.forClass(PublicCheckinLookupRequest.class);
|
||||
verify(service).lookup(eq("t"), c.capture());
|
||||
assertThat(c.getValue().value()).isEqualTo("a@x.com");
|
||||
}
|
||||
|
||||
@Test
|
||||
void qrRegistration_ignoresAClientSentAttend() throws Exception {
|
||||
PublicRegistrationService qr = mock(PublicRegistrationService.class);
|
||||
when(qr.register(eq("abc"), any())).thenReturn(Map.of("eventName", "Fair"));
|
||||
MockMvcBuilders.standaloneSetup(new PublicRegistrationController(qr)).build()
|
||||
.perform(post("/api/public/registration/abc").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"A\",\"mobile\":\"0123\",\"consent\":true,\"attend\":true}"))
|
||||
.andExpect(status().isOk());
|
||||
assertThat(Arrays.stream(PublicRegistrationRequest.class.getRecordComponents()).map(rc -> rc.getName())).doesNotContain("attend");
|
||||
}
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.dto.PublicCheckinLookupRequest;
|
||||
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 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.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class PublicInviteServiceTest {
|
||||
|
||||
private static final String GUEST = "/counter/eventGuest/findByToken/{token}";
|
||||
private static final String GUEST_REGISTER = "/counter/eventGuest/register";
|
||||
private static final String FIND_EVENT = "/counter/checkin/findEvent/{token}";
|
||||
private static final String LOOKUP = "/counter/checkin/lookup";
|
||||
private static final String BY_GUEST = "/counter/checkin/byGuest";
|
||||
private static final String REGISTER = "/counter/registration/register";
|
||||
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 INTERESTS = "/counter/interest/findByCompany/{companyId}";
|
||||
private static final long EV = 3312726793093644288L;
|
||||
private static final long COMPANY = 5L;
|
||||
private static final String GT = "abcDEF123_-abcDEF123_-";
|
||||
private static final String CK = "ZYXwvu987_-ZYXwvu987_-";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private RedisTemplate<String, Object> redis;
|
||||
private ValueOperations<String, Object> ops;
|
||||
private MockedStatic<HttpReqRespUtils> http;
|
||||
private PublicInviteService service;
|
||||
|
||||
private static Clock at(String utc) { return Clock.fixed(Instant.parse(utc), ZoneOffset.UTC); }
|
||||
|
||||
private PublicInviteService svc(String utc) {
|
||||
AdminEventLeadService leads = new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope());
|
||||
return new PublicInviteService(rest, new PublicRegistrationService(rest, leads, redis, at(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");
|
||||
service = svc("2027-01-16T04:00:00Z"); // 16 Jan 12:00 Malaysia: an event day
|
||||
stubGuest(false, false);
|
||||
stub(FIND_EVENT, CK, Map.of("companyId", COMPANY, "eventUuid", EV));
|
||||
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(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)));
|
||||
post(GUEST_REGISTER, Map.of("outcome", "REGISTERED", "eventLeadUuid", 7L));
|
||||
post(REGISTER, Map.of());
|
||||
post(BY_GUEST, Map.of("firstName", "Aisyah"));
|
||||
post(LOOKUP, Map.of("result", "FORM"));
|
||||
}
|
||||
|
||||
@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 post(String url, Object body) {
|
||||
when(rest.postForEntity(eq(url), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(body));
|
||||
}
|
||||
|
||||
private void postConflict(String url, String code) {
|
||||
when(rest.postForEntity(eq(url), any(ParameterizedTypeReference.class), any())).thenThrow(
|
||||
HttpClientErrorException.create(HttpStatus.CONFLICT, "c", null, ("{\"code\":\"" + code + "\"}").getBytes(), null));
|
||||
}
|
||||
|
||||
private void stubGuest(boolean registered, boolean attended) {
|
||||
Map<String, Object> g = new HashMap<>();
|
||||
g.put("companyId", COMPANY);
|
||||
g.put("eventUuid", EV);
|
||||
g.put("guestId", 11L);
|
||||
g.put("name", "Aisyah");
|
||||
g.put("mobileE164", "+60123456789");
|
||||
g.put("email", "a@x.com");
|
||||
g.put("companyName", "Acme");
|
||||
g.put("salespersonUserId", 21L);
|
||||
g.put("registered", registered);
|
||||
g.put("attended", attended);
|
||||
stub(GUEST, GT, g);
|
||||
}
|
||||
|
||||
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 static PublicRegistrationRequest req(String website, Boolean consent) {
|
||||
return new PublicRegistrationRequest("Aisyah", "012-345 6789", "a@x.com", "Acme", "Chef", List.of(3L), consent, website);
|
||||
}
|
||||
|
||||
private static PublicRegistrationRequest ok() { return req(null, true); }
|
||||
|
||||
private void assertCoded(Runnable r, HttpStatus status, String code) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(status);
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", code);
|
||||
});
|
||||
}
|
||||
|
||||
private void assertInvite(Runnable r) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
assertThat(e.getReason()).isEqualTo("This invitation is no longer active.");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "INVITE_INACTIVE");
|
||||
});
|
||||
}
|
||||
|
||||
private void assertCode(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");
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, Object> sent(String url) {
|
||||
ArgumentCaptor<Object> c = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), c.capture());
|
||||
return (Map<String, Object>) c.getValue();
|
||||
}
|
||||
|
||||
private void tooMany(String key, long over, Runnable r) {
|
||||
when(ops.increment(key)).thenReturn(over);
|
||||
assertCoded(r, HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
|
||||
}
|
||||
|
||||
// --- bad shape ---
|
||||
|
||||
@Test
|
||||
void badTokenShape_404_withoutBackendCall() {
|
||||
for (String bad : List.of("x", "short-link", GT.substring(1), GT + "A", GT.substring(1) + "!")) {
|
||||
assertInvite(() -> service.invite(bad));
|
||||
assertInvite(() -> service.inviteRegister(bad, ok()));
|
||||
assertInvite(() -> service.inviteCheckin(bad));
|
||||
assertCode(() -> service.checkin(bad));
|
||||
assertCode(() -> service.lookup(bad, new PublicCheckinLookupRequest("a@x.com")));
|
||||
assertCode(() -> service.walkIn(bad, ok()));
|
||||
}
|
||||
verifyNoInteractions(rest);
|
||||
}
|
||||
|
||||
// --- inactive ---
|
||||
|
||||
@Test
|
||||
void invite_unknownGuestToken_inactive() {
|
||||
when(rest.getForEntity(eq(GUEST), any(ParameterizedTypeReference.class), eq(GT)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertInvite(() -> service.invite(GT));
|
||||
assertInvite(() -> service.inviteRegister(GT, ok()));
|
||||
assertInvite(() -> service.inviteCheckin(GT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invite_eventDisabled_endDatePassed_noNotice_inactive() {
|
||||
stubEvent(false, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
assertInvite(() -> service.invite(GT));
|
||||
stubEvent(true, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
assertThat(service.invite(GT)).containsKey("eventName");
|
||||
assertInvite(() -> svc("2027-01-17T16:00:00Z").invite(GT)); // 18 Jan Malaysia, end passed
|
||||
when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertInvite(() -> service.invite(GT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkin_unknownTokenDisabledEventOrNoNotice_inactive() {
|
||||
when(rest.getForEntity(eq(FIND_EVENT), any(ParameterizedTypeReference.class), eq("AAAAAAAAAAAAAAAAAAAAAA")))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertCode(() -> service.checkin("AAAAAAAAAAAAAAAAAAAAAA"));
|
||||
stubEvent(false, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
assertCode(() -> service.checkin(CK));
|
||||
stubEvent(true, LocalDateTime.of(2027, 1, 17, 23, 59, 59));
|
||||
when(rest.getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), eq(COMPANY)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertCode(() -> service.checkin(CK));
|
||||
}
|
||||
|
||||
// --- invite GET ---
|
||||
|
||||
@Test
|
||||
void invite_returnsEventNoticeInterestsAndTheGuestsOwnDetails() {
|
||||
Map<String, Object> out = service.invite(GT);
|
||||
assertThat(out).containsEntry("eventName", "KL Food Fair 2027").containsEntry("startDate", "2027-01-15")
|
||||
.containsEntry("endDate", "2027-01-17").containsEntry("location", "MITEC").containsEntry("companyName", "INS")
|
||||
.containsEntry("state", "OPEN");
|
||||
assertThat(out.get("interests")).isEqualTo(List.of(Map.of("id", 3L, "name", "Cookware")));
|
||||
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L).containsEntry("textEn", "English notice");
|
||||
assertThat(out.get("guest")).isEqualTo(Map.of("name", "Aisyah", "mobile", "+60123456789", "email", "a@x.com", "companyName", "Acme"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invite_states() {
|
||||
assertThat(service.invite(GT)).containsEntry("state", "OPEN");
|
||||
stubGuest(true, false);
|
||||
assertThat(service.invite(GT)).containsEntry("state", "CHECKIN"); // event day
|
||||
assertThat(svc("2027-01-10T04:00:00Z").invite(GT)).containsEntry("state", "REGISTERED"); // before the event
|
||||
stubGuest(true, true);
|
||||
assertThat(service.invite(GT)).containsEntry("state", "CHECKED_IN");
|
||||
}
|
||||
|
||||
// --- invite POST ---
|
||||
|
||||
@Test
|
||||
void inviteRegister_honeypot_looksLikeSuccess_registersNothing() {
|
||||
assertThat(service.inviteRegister(GT, req("http://spam", true))).containsEntry("eventName", "KL Food Fair 2027");
|
||||
verify(rest, never()).postForEntity(eq(GUEST_REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteRegister_consentMissing_400() {
|
||||
for (Boolean c : new Boolean[]{null, false}) assertCoded(() -> service.inviteRegister(GT, req(null, c)), HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(GUEST_REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteRegister_validatesLikeQr() {
|
||||
PublicRegistrationRequest noContact = new PublicRegistrationRequest("Aisyah", " ", null, null, null, List.of(), true, null);
|
||||
assertCoded(() -> service.inviteRegister(GT, noContact), HttpStatus.BAD_REQUEST, "REQUIRED_FIELD");
|
||||
PublicRegistrationRequest inactiveInterest = new PublicRegistrationRequest("Aisyah", "0123456789", null, null, null, List.of(5L), true, null);
|
||||
assertThatThrownBy(() -> service.inviteRegister(GT, inactiveInterest)).isInstanceOf(CodedResponseStatusException.class);
|
||||
verify(rest, never()).postForEntity(eq(GUEST_REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteRegister_happy_sendsNormalisedBody_neverAttend() {
|
||||
assertThat(service.inviteRegister(GT, ok())).isEqualTo(Map.of("eventName", "KL Food Fair 2027"));
|
||||
Map<String, Object> b = sent(GUEST_REGISTER);
|
||||
assertThat(b).containsEntry("companyId", COMPANY).containsEntry("guestToken", GT).containsEntry("name", "Aisyah")
|
||||
.containsEntry("email", "a@x.com").containsEntry("companyName", "Acme").containsEntry("jobTitle", "Chef")
|
||||
.containsEntry("interestIds", List.of(3L)).containsEntry("consentNoticeId", 9L).containsEntry("mobileE164", "+60123456789")
|
||||
.containsEntry("consentAt", "2027-01-16T12:00").doesNotContainKey("attend");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteRegister_alreadyRegistered_isStill200() {
|
||||
post(GUEST_REGISTER, Map.of("outcome", "ALREADY_REGISTERED"));
|
||||
assertThat(service.inviteRegister(GT, ok())).isEqualTo(Map.of("eventName", "KL Food Fair 2027"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteRegister_eventFull_409() {
|
||||
postConflict(GUEST_REGISTER, "EVENT_FULL");
|
||||
assertThatThrownBy(() -> service.inviteRegister(GT, ok())).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getReason()).isEqualTo("This event is full");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("code", "EVENT_FULL");
|
||||
});
|
||||
}
|
||||
|
||||
// --- invite check-in ---
|
||||
|
||||
@Test
|
||||
void inviteCheckin_callsByGuest_returnsFirstName() {
|
||||
assertThat(service.inviteCheckin(GT)).isEqualTo(Map.of("firstName", "Aisyah"));
|
||||
assertThat(sent(BY_GUEST)).isEqualTo(Map.of("companyId", COMPANY, "guestToken", GT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteCheckin_conflictCodesPassThrough() {
|
||||
for (String code : List.of("NOT_REGISTERED", "NOT_EVENT_DAY")) {
|
||||
postConflict(BY_GUEST, code);
|
||||
assertCoded(() -> service.inviteCheckin(GT), HttpStatus.CONFLICT, code);
|
||||
}
|
||||
}
|
||||
|
||||
// --- check-in page ---
|
||||
|
||||
@Test
|
||||
void checkin_onEventDay_open_withEventNoticeAndInterests() {
|
||||
Map<String, Object> out = service.checkin(CK);
|
||||
assertThat(out).containsEntry("state", "OPEN").containsEntry("eventName", "KL Food Fair 2027").containsEntry("startDate", "2027-01-15")
|
||||
.containsEntry("endDate", "2027-01-17").containsEntry("location", "MITEC").containsEntry("companyName", "INS");
|
||||
assertThat(out.get("interests")).isEqualTo(List.of(Map.of("id", 3L, "name", "Cookware")));
|
||||
assertThat((Map<String, Object>) out.get("notice")).containsEntry("id", 9L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkin_beforeAndAfter_carryOnlyStateAndStartDate() {
|
||||
assertThat(svc("2027-01-10T04:00:00Z").checkin(CK)).isEqualTo(Map.of("state", "NOT_YET", "startDate", "2027-01-15"));
|
||||
assertThat(svc("2027-01-17T16:00:00Z").checkin(CK)).isEqualTo(Map.of("state", "ENDED", "startDate", "2027-01-15"));
|
||||
}
|
||||
|
||||
// --- lookup ---
|
||||
|
||||
@Test
|
||||
void lookup_detectsEmailVsMobile() {
|
||||
service.lookup(CK, new PublicCheckinLookupRequest(" A@X.com "));
|
||||
assertThat(sent(LOOKUP)).isEqualTo(Map.of("companyId", COMPANY, "eventUuid", EV, "email", "a@x.com"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookup_mobile_normalised() {
|
||||
service.lookup(CK, new PublicCheckinLookupRequest("012-345 6789"));
|
||||
assertThat(sent(LOOKUP)).isEqualTo(Map.of("companyId", COMPANY, "eventUuid", EV, "mobileE164", "+60123456789"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookup_firstNameOnlyForCheckedIn() {
|
||||
post(LOOKUP, Map.of("result", "CHECKED_IN", "firstName", "Aisyah"));
|
||||
assertThat(service.lookup(CK, new PublicCheckinLookupRequest("a@x.com"))).isEqualTo(Map.of("result", "CHECKED_IN", "firstName", "Aisyah"));
|
||||
post(LOOKUP, Map.of("result", "FORM", "firstName", "Leak", "name", "Leak"));
|
||||
assertThat(service.lookup(CK, new PublicCheckinLookupRequest("a@x.com"))).isEqualTo(Map.of("result", "FORM"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookup_invalidValue_400_andNothingSent() {
|
||||
for (String v : new String[]{"nonsense", "a@", " ", null}) {
|
||||
assertThatThrownBy(() -> service.lookup(CK, new PublicCheckinLookupRequest(v))).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST));
|
||||
}
|
||||
verify(rest, never()).postForEntity(eq(LOOKUP), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookup_andWalkIn_onlyOnEventDays_409() {
|
||||
PublicInviteService before = svc("2027-01-10T04:00:00Z");
|
||||
assertCoded(() -> before.lookup(CK, new PublicCheckinLookupRequest("a@x.com")), HttpStatus.CONFLICT, "NOT_EVENT_DAY");
|
||||
assertCoded(() -> before.walkIn(CK, ok()), HttpStatus.CONFLICT, "NOT_EVENT_DAY");
|
||||
verify(rest, never()).postForEntity(eq(LOOKUP), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
// --- walk-in ---
|
||||
|
||||
@Test
|
||||
void walkIn_callsRegisterWithAttendTrue_noSalesperson() {
|
||||
assertThat(service.walkIn(CK, ok())).isEqualTo(Map.of("eventName", "KL Food Fair 2027"));
|
||||
Map<String, Object> b = sent(REGISTER);
|
||||
assertThat(b).containsEntry("attend", true).containsEntry("companyId", COMPANY).containsEntry("eventUuid", EV)
|
||||
.containsEntry("name", "Aisyah").containsEntry("mobileE164", "+60123456789").containsEntry("consentNoticeId", 9L)
|
||||
.containsEntry("interestIds", List.of(3L)).doesNotContainKey("guestToken");
|
||||
assertThat(b.get("salespersonUserId")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void walkIn_honeypotAndConsent() {
|
||||
assertThat(service.walkIn(CK, req("spam", true))).containsEntry("eventName", "KL Food Fair 2027");
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
assertCoded(() -> service.walkIn(CK, req(null, false)), HttpStatus.BAD_REQUEST, "CONSENT_REQUIRED");
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
// --- QR guard ---
|
||||
|
||||
@Test
|
||||
void qrRegistration_neverPassesAttend() {
|
||||
stub("/counter/registrationLink/findByToken/{token}", GT, Map.of("enabled", true, "eventUuid", EV, "companyId", COMPANY));
|
||||
stub("/counter/eventSalesperson/findByEventUuid/{eventUuid}", EV, List.of());
|
||||
new PublicRegistrationService(rest, new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()),
|
||||
redis, at("2027-01-16T04:00:00Z")).register(GT, ok());
|
||||
assertThat(sent(REGISTER)).doesNotContainKey("attend");
|
||||
}
|
||||
|
||||
// --- limits ---
|
||||
|
||||
@Test
|
||||
void inviteLoadLimit_120_countsGetsAndPosts() {
|
||||
tooMany("inv:load:1.2.3.4", 121L, () -> service.invite(GT));
|
||||
tooMany("inv:load:1.2.3.4", 121L, () -> service.inviteRegister(GT, ok()));
|
||||
tooMany("inv:load:1.2.3.4", 121L, () -> service.inviteCheckin(GT));
|
||||
when(ops.increment("inv:load:1.2.3.4")).thenReturn(120L);
|
||||
assertThat(service.invite(GT)).containsKey("eventName");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inviteSubmitLimit_60_perEventAndIp_forRegisterAndCheckin() {
|
||||
tooMany("inv:submit:" + EV + ":1.2.3.4", 61L, () -> service.inviteRegister(GT, ok()));
|
||||
tooMany("inv:submit:" + EV + ":1.2.3.4", 61L, () -> service.inviteCheckin(GT));
|
||||
verify(rest, never()).postForEntity(eq(GUEST_REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, never()).postForEntity(eq(BY_GUEST), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkinLimit_300_everyCall_andNeverCountsRegLoad() {
|
||||
String key = "chk:" + EV + ":1.2.3.4";
|
||||
tooMany(key, 301L, () -> service.checkin(CK));
|
||||
tooMany(key, 301L, () -> service.lookup(CK, new PublicCheckinLookupRequest("a@x.com")));
|
||||
tooMany(key, 301L, () -> service.walkIn(CK, ok()));
|
||||
when(ops.increment(key)).thenReturn(300L);
|
||||
service.checkin(CK);
|
||||
service.lookup(CK, new PublicCheckinLookupRequest("a@x.com"));
|
||||
service.walkIn(CK, ok());
|
||||
verify(ops, never()).increment("reg:load:1.2.3.4");
|
||||
}
|
||||
|
||||
// --- review minors ---
|
||||
|
||||
@Test
|
||||
void walkIn_honeypot_onNotYetOrEndedCode_409_neverEchoesTheEventName() {
|
||||
for (String now : List.of("2027-01-10T04:00:00Z", "2027-01-20T04:00:00Z")) {
|
||||
PublicInviteService off = svc(now);
|
||||
assertCoded(() -> off.walkIn(CK, req("spam", true)), HttpStatus.CONFLICT, "NOT_EVENT_DAY");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingFirstName_isEmptyNotTheStringNull() {
|
||||
post(BY_GUEST, Map.of());
|
||||
assertThat(service.inviteCheckin(GT)).isEqualTo(Map.of("firstName", ""));
|
||||
post(LOOKUP, Map.of("result", "CHECKED_IN"));
|
||||
assertThat(service.lookup(CK, new PublicCheckinLookupRequest("a@x.com"))).isEqualTo(Map.of("result", "CHECKED_IN", "firstName", ""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkinLoadLimit_300_perIp_countsUnknownTokens_beforeTheLookup() {
|
||||
String unknown = "AAAAAAAAAAAAAAAAAAAAAA";
|
||||
when(rest.getForEntity(eq(FIND_EVENT), any(ParameterizedTypeReference.class), eq(unknown)))
|
||||
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
|
||||
assertCode(() -> service.checkin(unknown));
|
||||
when(ops.increment("chk:load:1.2.3.4")).thenReturn(301L);
|
||||
assertCoded(() -> service.checkin(unknown), HttpStatus.TOO_MANY_REQUESTS, "TOO_MANY");
|
||||
verify(rest, never()).getForEntity(eq(FIND_EVENT), any(ParameterizedTypeReference.class), eq("BBBBBBBBBBBBBBBBBBBBBB"));
|
||||
verify(ops, never()).increment("reg:load:1.2.3.4");
|
||||
}
|
||||
|
||||
@Test
|
||||
void endedQrCode_fetchesNeitherCompanyNorNotice() {
|
||||
stub("/counter/registrationLink/findByToken/{token}", GT, Map.of("enabled", true, "eventUuid", EV, "companyId", COMPANY));
|
||||
PublicRegistrationService qr = new PublicRegistrationService(rest, new AdminEventLeadService(rest, mock(AdminAuthenticationService.class), new AdminCompanyScope()),
|
||||
redis, at("2027-01-20T04:00:00Z"));
|
||||
assertThatThrownBy(() -> qr.page(GT)).isInstanceOf(CodedResponseStatusException.class);
|
||||
verify(rest, never()).getForEntity(eq(COMPANY_URL), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, never()).getForEntity(eq(NOTICE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user