diff --git a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java index 68dba3e..0944b3d 100644 --- a/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java +++ b/solvway-api-gateway/src/main/java/com/solvway/gateway/filter/JWTAuthFilter.java @@ -19,6 +19,7 @@ import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.stereotype.Component; @@ -28,6 +29,9 @@ import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; @Component public class JWTAuthFilter implements GlobalFilter, Ordered { @@ -36,6 +40,21 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { private static final String WWW_AUTH_HEADER = "WWW-Authenticate"; + /** Public QR registration page: mobile-api reads these for a visitor with no user token. Anchored, exact method and path. */ + private static final List> PUBLIC_REGISTRATION = List.of( + publicPath(HttpMethod.GET, "/counter/registrationLink/findByToken/[A-Za-z0-9_-]{22}"), + publicPath(HttpMethod.GET, "/counter/event/findByUuid/\\d+"), + publicPath(HttpMethod.GET, "/counter/interest/findByCompany/\\d+"), + publicPath(HttpMethod.GET, "/counter/eventSalesperson/findByEventUuid/\\d+"), + publicPath(HttpMethod.GET, "/company/findById/\\d+"), + publicPath(HttpMethod.GET, "/company/\\d+/privacyNotice"), + publicPath(HttpMethod.GET, "/user/\\d+/activeAdminOf/\\d+"), + publicPath(HttpMethod.POST, "/counter/registration/register")); + + private static Map.Entry publicPath(HttpMethod method, String regex) { + return Map.entry(method, Pattern.compile(regex)); + } + @Value("${auth.api-key.third-party-api-key:''}") private String thirdPartyApiKey; @@ -136,6 +155,7 @@ public class JWTAuthFilter implements GlobalFilter, Ordered { // Co-Lite admin sign-in: lock check and its recording run before the user has a token || (url.matches("/loginSecurity/isLocked/[^/]+") && !url.contains("..")) || url.equals("/loginSecurity/record") + || PUBLIC_REGISTRATION.stream().anyMatch(p -> p.getKey().equals(exchange.getRequest().getMethod()) && p.getValue().matcher(url).matches()) || url.contains("/geoLocationHierarchy/findByFirstLevelLocation") || url.contains("/geoLocationHierarchy/findAllByParentId") // public content - no JWT required diff --git a/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java new file mode 100644 index 0000000..bea7a77 --- /dev/null +++ b/solvway-api-gateway/src/test/java/com/solvway/gateway/filter/JWTAuthFilterPublicRegistrationPathTest.java @@ -0,0 +1,95 @@ +package com.solvway.gateway.filter; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.gateway.model.AuthAppKey; +import com.solvway.gateway.model.AuthAppKeyMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import org.springframework.test.util.ReflectionTestUtils; +import reactor.core.publisher.Mono; + +import java.net.InetSocketAddress; +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.assertj.core.api.Assertions.assertThat; + +/** The public QR registration page reads a few things and posts one registration without a user token; nothing else opens. */ +class JWTAuthFilterPublicRegistrationPathTest { + + private static final String KEY = "gateway-test-key"; + private static final String TOKEN = "2lvFUDqc0zSu5X-6qvZE1g"; + + private JWTAuthFilter filter; + + @BeforeEach + void setUp() throws Exception { + AuthAppKey key = new ObjectMapper().readValue( + "{\"key\":\"" + KEY + "\",\"type\":\"BO\",\"ipList\":[\"0.0.0.0/0\"],\"allowList\":[\"/\"]}", + AuthAppKey.class); + AuthAppKeyMap map = new AuthAppKeyMap(); + map.add(KEY, key); + filter = new JWTAuthFilter(); + ReflectionTestUtils.setField(filter, "authAppKeyMap", map); + } + + private MockServerWebExchange call(HttpMethod method, String path) { + return MockServerWebExchange.from(MockServerHttpRequest.method(method, path) + .header("api-key", KEY) + .remoteAddress(new InetSocketAddress("127.0.0.1", 40000))); + } + + private boolean passes(MockServerWebExchange exchange) { + AtomicBoolean called = new AtomicBoolean(false); + GatewayFilterChain chain = ex -> { + called.set(true); + return Mono.empty(); + }; + filter.filter(exchange, chain).block(); + return called.get(); + } + + @Test + void publicRegistrationPathsNeedNoUserToken() { + for (String[] c : new String[][] { + {"GET", "/counter/registrationLink/findByToken/" + TOKEN}, + {"GET", "/counter/event/findByUuid/3312726793093644288"}, + {"GET", "/counter/interest/findByCompany/5"}, + {"GET", "/counter/eventSalesperson/findByEventUuid/3312726793093644288"}, + {"GET", "/company/findById/2"}, + {"GET", "/company/2/privacyNotice"}, + {"GET", "/user/21/activeAdminOf/5"}, + {"POST", "/counter/registration/register"} }) { + assertThat(passes(call(HttpMethod.valueOf(c[0]), c[1]))).as(c[0] + " " + c[1]).isTrue(); + } + } + + @Test + void everythingElseStillNeedsAToken() { + for (String[] c : new String[][] { + {"POST", "/company/1/privacyNotice"}, + {"GET", "/user/findById/1"}, + {"POST", "/counter/registrationLink/ensure"}, + {"GET", "/counter/registrationLink/findByToken/" + TOKEN + "/x"}, + {"GET", "/counter/registrationLink/findByToken/short"}, + {"GET", "/counter/registrationLink/findByToken/" + TOKEN + "a"}, + {"GET", "/counter/registrationLink/findByToken/../x/" + TOKEN}, + {"POST", "/counter/event/findByUuid/1"}, + {"GET", "/counter/event/findByUuid/1/x"}, + {"GET", "/counter/event/findByUuid/abc"}, + {"GET", "/x/company/findById/2"}, + {"GET", "/company/findById/2/x"}, + {"GET", "/user/1/activeAdminOf/2/x"}, + {"POST", "/user/1/activeAdminOf/2"}, + {"GET", "/counter/registration/register"}, + {"POST", "/counter/registration/register/x"} }) { + MockServerWebExchange ex = call(HttpMethod.valueOf(c[0]), c[1]); + assertThat(passes(ex)).as(c[0] + " " + c[1]).isFalse(); + assertThat(ex.getResponse().getStatusCode()).as(c[0] + " " + c[1]).isEqualTo(HttpStatus.UNAUTHORIZED); + } + } +} diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java index 37b2d89..942cf85 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/constant/api/RestApiSystemServiceConstants.java @@ -6,6 +6,7 @@ public class RestApiSystemServiceConstants { public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}"; public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}"; + public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}"; public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}"; diff --git a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java index 70ed776..adc8568 100644 --- a/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java +++ b/solvway-mobile-api/src/main/java/com/solvway/mobile/api/service/PublicRegistrationService.java @@ -14,6 +14,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; import java.time.Clock; import java.time.LocalDate; @@ -44,6 +45,7 @@ public class PublicRegistrationService { private static final long WINDOW_MINUTES = 10; private static final ParameterizedTypeReference EVENT = new ParameterizedTypeReference<>() {}; + private static final ParameterizedTypeReference BOOL = new ParameterizedTypeReference<>() {}; private static final ParameterizedTypeReference> MAP = new ParameterizedTypeReference<>() {}; private final RestTemplateCustomUtil rest; @@ -124,7 +126,16 @@ public class PublicRegistrationService { private Long salesperson(Map 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; + return leads.teamIds(e.getUuid()).contains(id) && Boolean.TRUE.equals(activeAdminOf(id, e.getCompanyId())) ? id : null; + } + + /** The user record is closed to visitors, so ask the one yes/no endpoint. Any failure means "no salesperson", never a 500. */ + private Boolean activeAdminOf(long userId, Long companyId) { + try { + return rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF), BOOL, userId, companyId).getBody(); + } catch (RestClientException e) { + return false; + } } private Open open(String token) { diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java new file mode 100644 index 0000000..1e5e42e --- /dev/null +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationSalespersonTest.java @@ -0,0 +1,121 @@ +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.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.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; + +/** The visitor has no token, so the salesperson check must use the open activeAdminOf call, never the closed findById. */ +@SuppressWarnings({"unchecked", "rawtypes"}) +class PublicRegistrationSalespersonTest { + + private static final String ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}"; + private static final String FIND_BY_ID = "/user/findById/{id}"; + private static final long EV = 3312726793093644288L; + private static final long COMPANY = 5L; + private static final String TOKEN = "abc123"; + + private RestTemplateCustomUtil rest; + private MockedStatic http; + private PublicRegistrationService service; + + @BeforeEach + void setUp() { + rest = mock(RestTemplateCustomUtil.class); + RedisTemplate redis = mock(RedisTemplate.class); + ValueOperations 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, Clock.fixed(Instant.parse("2027-01-16T04:00:00Z"), ZoneOffset.UTC)); + + Map link = new HashMap<>(Map.of("token", TOKEN, "enabled", true, "eventUuid", EV, "companyId", COMPANY, "salespersonUserId", 21L)); + stub("/counter/registrationLink/findByToken/{token}", TOKEN, link); + CompanyEvent e = new CompanyEvent(); + e.setCompanyId(COMPANY); + e.setUuid(EV); + e.setName("KL Food Fair 2027"); + e.setDateEnd(LocalDateTime.of(2027, 1, 17, 23, 59, 59)); + e.setEnabled(GeneralEnum.FlagYesNo.Y); + stub("/counter/event/findByUuid/{uuid}", EV, e); + stub("/company/findById/{id}", COMPANY, new HashMap<>(Map.of("id", COMPANY, "name", "INS", "status", "A"))); + stub("/company/{id}/privacyNotice", COMPANY, Map.of("id", 9L, "textEn", "en", "textMs", "ms")); + stub("/counter/eventSalesperson/findByEventUuid/{eventUuid}", EV, List.of(Map.of("userId", 21L))); + stub("/counter/interest/findByCompany/{companyId}", COMPANY, List.of(Map.of("id", 3L, "companyId", COMPANY, "name", "Cookware", "active", true, "sortOrder", 0))); + when(rest.postForEntity(eq("/counter/registration/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 Object registeredSalesperson() { + service.register(TOKEN, new PublicRegistrationRequest("Aisyah", "012-345 6789", "a@x.com", "Acme", "Chef", List.of(3L), true, null)); + ArgumentCaptor body = ArgumentCaptor.forClass(Object.class); + verify(rest).postForEntity(eq("/counter/registration/register"), any(ParameterizedTypeReference.class), body.capture()); + verify(rest, never()).getForEntity(eq(FIND_BY_ID), any(ParameterizedTypeReference.class), any()); + return ((Map) body.getValue()).get("salespersonUserId"); + } + + @Test + void activeAdminOf_true_keepsTheSalesperson() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))).thenReturn(ResponseEntity.ok(true)); + assertThat(registeredSalesperson()).isEqualTo(21L); + } + + @Test + void activeAdminOf_false_isNull() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))).thenReturn(ResponseEntity.ok(false)); + assertThat(registeredSalesperson()).isNull(); + } + + @Test + void activeAdminOf_404_isNull_not500() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) + .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); + assertThat(registeredSalesperson()).isNull(); + } + + @Test + void activeAdminOf_otherFailure_isNull_not500() { + when(rest.getForEntity(eq(ACTIVE_ADMIN_OF), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) + .thenThrow(HttpClientErrorException.create(HttpStatus.UNAUTHORIZED, "no", null, null, null)); + assertThat(registeredSalesperson()).isNull(); + } +} diff --git a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java index 1910476..1ff5a11 100644 --- a/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java +++ b/solvway-mobile-api/src/test/java/com/solvway/mobile/api/service/PublicRegistrationServiceTest.java @@ -46,7 +46,7 @@ class PublicRegistrationServiceTest { 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 USER = "/user/{id}/activeAdminOf/{companyId}"; private static final String INTERESTS = "/counter/interest/findByCompany/{companyId}"; private static final String REGISTER = "/counter/registration/register"; private static final long EV = 3312726793093644288L; @@ -116,13 +116,7 @@ class PublicRegistrationServiceTest { } private void stubUser(long id, boolean enabled) { - Map 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); + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(id), eq(COMPANY))).thenReturn(ResponseEntity.ok(enabled)); } private static PublicRegistrationRequest req(String website, Boolean consent, List interests) { @@ -308,7 +302,7 @@ class PublicRegistrationServiceTest { @Test void register_deletedSalesperson_isNull_not500() { - when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L))) + when(rest.getForEntity(eq(USER), any(ParameterizedTypeReference.class), eq(21L), eq(COMPANY))) .thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null)); service.register(TOKEN, ok()); assertThat(registered().get("salespersonUserId")).isNull(); diff --git a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java index 03de28c..b7febbb 100644 --- a/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java +++ b/solvway-services-system/src/main/java/com/solvway/services/system/controller/UserController.java @@ -225,6 +225,14 @@ public class UserController { return user.isPresent() ? user.get() : null; } + /** True only for an enabled admin of that company; open to the public registration page, so it exposes nothing else of the user. */ + @GetMapping("/{id}/activeAdminOf/{companyId}") + public boolean activeAdminOf(@PathVariable("id") Long id, @PathVariable("companyId") Long companyId) { + return userService.findById(id) + .filter(u -> u.getType() == UserType.A && u.isEnabled() && companyId.equals(u.getCompanyId())) + .isPresent(); + } + @RequestMapping("/findByEmail/{email}") public User findByEmail(@PathVariable("email") String email) { User user = userService.findByEmail(email); diff --git a/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java new file mode 100644 index 0000000..ef84331 --- /dev/null +++ b/solvway-services-system/src/test/java/com/solvway/services/system/controller/UserControllerActiveAdminOfTest.java @@ -0,0 +1,69 @@ +package com.solvway.services.system.controller; + +import com.solvway.core.enums.UserEnum.UserType; +import com.solvway.services.system.model.User; +import com.solvway.services.system.service.UserService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class UserControllerActiveAdminOfTest { + + @Mock private UserService userService; + @InjectMocks private UserController controller; + + private void stored(UserType type, Long companyId, boolean enabled) { + User u = new User(); + u.setType(type); + u.setCompanyId(companyId); + u.setEnabled(enabled); + when(userService.findById(7L)).thenReturn(Optional.of(u)); + } + + @Test + void enabledAdminOfTheCompany_isTrue() { + stored(UserType.A, 2L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isTrue(); + } + + @Test + void otherCompany_isFalse() { + stored(UserType.A, 3L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void companylessAdmin_isFalse() { + stored(UserType.A, null, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void disabled_isFalse() { + stored(UserType.A, 2L, false); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void nonAdminType_isFalse() { + stored(UserType.D, 2L, true); + assertThat(controller.activeAdminOf(7L, 2L)).isFalse(); + } + + @Test + void unknownUser_isFalse() { + when(userService.findById(8L)).thenReturn(Optional.empty()); + assertThat(controller.activeAdminOf(8L, 2L)).isFalse(); + } +}