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 "";
|
||||
}
|
||||
Reference in new issue
Block a user