From d525e3a3cdcdb071feb10db164b49d2f641b74ce Mon Sep 17 00:00:00 2001 From: ElisKina-dev Date: Thu, 9 Jan 2025 14:36:51 +0100 Subject: [PATCH] fixes --- helm/values.yaml | 2 + .../client/OrganizationSearchClient.java | 14 +- .../user/IamUserInfoDTO2UserInfoMapper.java | 28 +- .../auth/service/user/UserServiceImpl.java | 31 +-- src/main/resources/application.yml | 5 + .../auth/connector/BaseApiHolderTest.java | 70 +++++ .../client/OrganizationSearchClientTest.java | 102 ++++++++ .../config/OrganizationApiHolderTest.java | 61 +++++ .../IamUserInfoDTO2UserInfoMapperTest.java | 246 +++++++++--------- 9 files changed, 407 insertions(+), 152 deletions(-) create mode 100644 src/test/java/it/gov/pagopa/payhub/auth/connector/BaseApiHolderTest.java create mode 100644 src/test/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClientTest.java create mode 100644 src/test/java/it/gov/pagopa/payhub/auth/connector/config/OrganizationApiHolderTest.java diff --git a/helm/values.yaml b/helm/values.yaml index 4ec0d561..0aeea491 100644 --- a/helm/values.yaml +++ b/helm/values.yaml @@ -68,6 +68,8 @@ microservice-chart: JWT_TOKEN_EXPIRATION_SECONDS: "14400" # 4 HOURS ACCESS_ORGANIZATION_MODE_ENABLED: "true" + ORGANIZATION_BASE_URL: "http://p4pa-organization-microservice-chart:8080" + envSecret: APPLICATIONINSIGHTS_CONNECTION_STRING: appinsights-connection-string diff --git a/src/main/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClient.java b/src/main/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClient.java index a8f80765..5c478bd4 100644 --- a/src/main/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClient.java +++ b/src/main/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClient.java @@ -21,17 +21,23 @@ public OrganizationSearchClient(OrganizationApisHolder organizationApisHolder) { public Broker getBrokerById(Long id, String accessToken) { try { - return organizationApisHolder.getBrokerEntityControllerApi(accessToken).getItemResourceBrokerGet(String.valueOf(id)); + return organizationApisHolder.getBrokerEntityControllerApi(accessToken).crudGetBroker(String.valueOf(id)); + } catch (HttpClientErrorException e) { + if (e.getStatusCode() == HttpStatus.NOT_FOUND) { + log.info("Broker with ID {} not found.", id); + return null; + } + throw e; } catch (Exception e) { - log.error(String.valueOf(e.getCause())); - return null; + log.error("An unexpected error occurred: {}", e.getMessage(), e); + throw e; } } public Organization getOrganizationByIpaCode(String ipaCode, String accessToken) { try { return organizationApisHolder.getOrganizationSearchControllerApi(accessToken) - .executeSearchOrganizationGet(ipaCode); + .crudOrganizationsFindByIpaCode(ipaCode); } catch (HttpClientErrorException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { log.warn("Organization with IPA code {} not found", ipaCode); diff --git a/src/main/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapper.java b/src/main/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapper.java index 0815d007..e366e6fc 100644 --- a/src/main/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapper.java +++ b/src/main/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapper.java @@ -1,6 +1,8 @@ package it.gov.pagopa.payhub.auth.service.user; +import it.gov.pagopa.payhub.auth.connector.client.OrganizationSearchClient; import it.gov.pagopa.payhub.auth.dto.IamUserInfoDTO; +import it.gov.pagopa.payhub.auth.dto.IamUserOrganizationRolesDTO; import it.gov.pagopa.payhub.auth.exception.custom.UserNotFoundException; import it.gov.pagopa.payhub.auth.model.Operator; import it.gov.pagopa.payhub.auth.model.User; @@ -9,24 +11,28 @@ import it.gov.pagopa.payhub.auth.utils.Constants; import it.gov.pagopa.payhub.dto.generated.UserInfo; import it.gov.pagopa.payhub.dto.generated.UserOrganizationRoles; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Optional; import java.util.function.Function; @Service public class IamUserInfoDTO2UserInfoMapper implements Function { public static final String WS_USER_SUFFIX = "-WS_USER"; - private final UsersRepository usersRepository; private final OperatorsRepository operatorsRepository; + private final OrganizationSearchClient organizationSearchClient; - public IamUserInfoDTO2UserInfoMapper(UsersRepository usersRepository, OperatorsRepository operatorsRepository) { + public IamUserInfoDTO2UserInfoMapper(UsersRepository usersRepository, OperatorsRepository operatorsRepository, OrganizationSearchClient organizationSearchClient) { this.usersRepository = usersRepository; this.operatorsRepository = operatorsRepository; + this.organizationSearchClient = organizationSearchClient; } @Override @@ -60,6 +66,19 @@ public static String buildSystemMappedExternalUserId(String organizationIpaCode) private UserInfo userInfoMapper(IamUserInfoDTO iamUserInfoDTO) { User user = usersRepository.findById(iamUserInfoDTO.getInnerUserId()).orElseThrow(() -> new UserNotFoundException("Cannot found user having inner id:" + iamUserInfoDTO.getInnerUserId())); List userRoles = operatorsRepository.findAllByUserId(iamUserInfoDTO.getInnerUserId()); + + String orgIpaCode = Optional.ofNullable(iamUserInfoDTO.getOrganizationAccess()) + .map(IamUserOrganizationRolesDTO::getOrganizationIpaCode) + .orElseGet(() -> !userRoles.isEmpty() ? userRoles.get(0).getOrganizationIpaCode() : null); + + Broker brokerInfo = null; + if (orgIpaCode != null) { + Organization organization = organizationSearchClient.getOrganizationByIpaCode(orgIpaCode, String.valueOf(iamUserInfoDTO.getOrganizationAccess())); + if (organization != null && organization.getBrokerId() != null) { + brokerInfo = organizationSearchClient.getBrokerById(organization.getBrokerId(), String.valueOf(iamUserInfoDTO.getOrganizationAccess())); + } + } + UserInfo userInfo = UserInfo.builder() .userId(user.getUserId()) .mappedExternalUserId(user.getMappedExternalUserId()) @@ -80,6 +99,11 @@ private UserInfo userInfoMapper(IamUserInfoDTO iamUserInfoDTO) { if(iamUserInfoDTO.getOrganizationAccess() != null){ userInfo.setOrganizationAccess(iamUserInfoDTO.getOrganizationAccess().getOrganizationIpaCode()); } + if (brokerInfo != null) { + userInfo.setBrokerId(brokerInfo.getBrokerId()); + userInfo.setBrokerFiscalCode(brokerInfo.getBrokerFiscalCode()); + } return userInfo; } + } diff --git a/src/main/java/it/gov/pagopa/payhub/auth/service/user/UserServiceImpl.java b/src/main/java/it/gov/pagopa/payhub/auth/service/user/UserServiceImpl.java index 657ce7cd..e837c955 100644 --- a/src/main/java/it/gov/pagopa/payhub/auth/service/user/UserServiceImpl.java +++ b/src/main/java/it/gov/pagopa/payhub/auth/service/user/UserServiceImpl.java @@ -1,6 +1,5 @@ package it.gov.pagopa.payhub.auth.service.user; -import it.gov.pagopa.payhub.auth.connector.client.OrganizationSearchClient; import it.gov.pagopa.payhub.auth.dto.IamUserInfoDTO; import it.gov.pagopa.payhub.auth.exception.custom.InvalidAccessTokenException; import it.gov.pagopa.payhub.auth.model.Operator; @@ -11,8 +10,6 @@ import it.gov.pagopa.payhub.auth.service.user.retrieve.OrganizationOperatorRetrieverService; import it.gov.pagopa.payhub.dto.generated.OperatorDTO; import it.gov.pagopa.payhub.dto.generated.UserInfo; -import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker; -import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; @@ -25,7 +22,6 @@ @Slf4j public class UserServiceImpl implements UserService { - private OrganizationSearchClient organizationSearchClient; private final TokenStoreService tokenStoreService; private final UserRegistrationService userRegistrationService; private final OperatorRegistrationService operatorRegistrationService; @@ -61,35 +57,12 @@ public UserInfo getUserInfo(String accessToken) { throw new InvalidAccessTokenException("AccessToken not found"); } - Broker brokerInfo = null; - - if (Boolean.TRUE.equals(organizationAccessMode) && userInfo.getOrganizationAccess() != null) { - log.debug("SelfCare mode enabled. Using organizationAccess: {}", userInfo.getOrganizationAccess()); - - String organizationIpaCode = userInfo.getOrganizationAccess().getOrganizationIpaCode(); - if (organizationIpaCode != null) { - Organization organization = organizationSearchClient.getOrganizationByIpaCode(organizationIpaCode, accessToken); - - if (organization != null && organization.getBrokerId() != null) { - log.info("Organization found. Fetching broker details for brokerId: {}", organization.getBrokerId()); - brokerInfo = organizationSearchClient.getBrokerById(organization.getBrokerId(), accessToken); - } else { - log.warn("No valid organization or brokerId found for IPA Code: {}", organizationIpaCode); - } - } - } else { - log.debug("SelfCare mode disabled or organizationAccess not provided. Cannot fetch organization."); - } - UserInfo result = userInfoMapper.apply(userInfo); + result.setCanManageUsers(!organizationAccessMode); - if (brokerInfo != null) { - result.setBrokerId(brokerInfo.getBrokerId()); - result.setBrokerFiscalCode(brokerInfo.getBrokerFiscalCode()); - } log.debug("User info retrieved successfully with brokerId: {}", - brokerInfo != null ? brokerInfo.getBrokerId() : "N/A"); + result.getBrokerId() != null ? result.getBrokerId() : "N/A"); return result; } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 33e8de70..ea338bf8 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -66,6 +66,11 @@ app: # Thus it will register te relation between the operator and the relation with the provided roles. # If disabled, the admin should register the associations using the provided API (otherwise they will be disabled) enable-access-organization-mode: "\${ACCESS_ORGANIZATION_MODE_ENABLED:true}" + +rest: + default-timeout: + connect-millis: "\${DEFAULT_REST_CONNECT_TIMEOUT_MILLIS:120000}" + read-millis: "\${DEFAULT_REST_READ_TIMEOUT_MILLIS:120000}" organization: base-url: "\${ORGANIZATION_BASE_URL:}" diff --git a/src/test/java/it/gov/pagopa/payhub/auth/connector/BaseApiHolderTest.java b/src/test/java/it/gov/pagopa/payhub/auth/connector/BaseApiHolderTest.java new file mode 100644 index 00000000..174a581f --- /dev/null +++ b/src/test/java/it/gov/pagopa/payhub/auth/connector/BaseApiHolderTest.java @@ -0,0 +1,70 @@ +package it.gov.pagopa.payhub.auth.connector; + +import org.apache.commons.lang3.tuple.Pair; +import org.junit.jupiter.api.Assertions; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Function; +import java.util.stream.IntStream; + +public abstract class BaseApiHolderTest { + + @Mock + protected RestTemplate restTemplateMock; + + protected void assertAuthenticationShouldBeSetInThreadSafeMode(Function apiInvoke, Class apiReturnedType, Runnable apiUnloader) throws InterruptedException { + // Configuring useCases in a single thread + List> useCases = IntStream.rangeClosed(0, 100) + .mapToObj(i -> { + try { + String accessToken = "accessToken" + i; + T expectedResult = apiReturnedType.getConstructor().newInstance(); + + Mockito.doReturn(ResponseEntity.ok(expectedResult)) + .when(restTemplateMock) + .exchange( + Mockito.argThat(req -> + req.getHeaders().getOrDefault(HttpHeaders.AUTHORIZATION, Collections.emptyList()).getFirst() + .equals("Bearer " + accessToken)), + Mockito.eq(apiReturnedType)); + return Pair.of(accessToken, expectedResult); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }) + .toList(); + + try (ExecutorService executorService = Executors.newFixedThreadPool(10)) { + executorService.invokeAll(useCases.stream() + .map(p -> (Callable) () -> { + // Given + String accessToken = p.getKey(); + T expectedResult = p.getValue(); + + // When + T result = apiInvoke.apply(accessToken); + + // Then + Assertions.assertSame(expectedResult, result); + return true; + }) + .toList()); + } + + apiUnloader.run(); + + Mockito.verify(restTemplateMock, Mockito.times(useCases.size())) + .exchange(Mockito.any(), Mockito.>any()); + } + +} diff --git a/src/test/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClientTest.java b/src/test/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClientTest.java new file mode 100644 index 00000000..3e670488 --- /dev/null +++ b/src/test/java/it/gov/pagopa/payhub/auth/connector/client/OrganizationSearchClientTest.java @@ -0,0 +1,102 @@ +package it.gov.pagopa.payhub.auth.connector.client; + +import it.gov.pagopa.payhub.auth.connector.client.OrganizationSearchClient; +import it.gov.pagopa.payhub.auth.connector.config.OrganizationApisHolder; +import it.gov.pagopa.pu.p4pa_organization.controller.generated.OrganizationSearchControllerApi; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; + +@ExtendWith(MockitoExtension.class) +class OrganizationSearchClientTest { + @Mock + private OrganizationApisHolder organizationApisHolder; + @Mock + private OrganizationSearchControllerApi organizationSearchControllerApiMock; + + private OrganizationSearchClient organizationSearchClient; + + @BeforeEach + void setUp() { + organizationSearchClient = new OrganizationSearchClient(organizationApisHolder); + } + + @AfterEach + void verifyNoMoreInteractions() { + Mockito.verifyNoMoreInteractions( + organizationApisHolder + ); + } + + @Test + void whenGetOrganizationByIpaCodeThenInvokeWithAccessToken() { + String orgIpaCode = "ORGIPACODE"; + String accessToken = "ACCESSTOKEN"; + Organization expectedResult = new Organization(); + + Mockito.when(organizationApisHolder.getOrganizationSearchControllerApi(accessToken)) + .thenReturn(organizationSearchControllerApiMock); + Mockito.when(organizationSearchControllerApiMock.crudOrganizationsFindByIpaCode(orgIpaCode)) + .thenReturn(expectedResult); + + Organization result = organizationSearchClient.getOrganizationByIpaCode(orgIpaCode, accessToken); + + Assertions.assertSame(expectedResult, result); + } + + @Test + void givenNoExistentIpaCodeWhenGetOrganizationByIpaCodeThenNull() { + String orgIpaCode = "ORGIPACODE"; + String accessToken = "ACCESSTOKEN"; + + Mockito.when(organizationApisHolder.getOrganizationSearchControllerApi(accessToken)) + .thenReturn(organizationSearchControllerApiMock); + Mockito.when(organizationSearchControllerApiMock.crudOrganizationsFindByIpaCode(orgIpaCode)) + .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + + Organization result = organizationSearchClient.getOrganizationByIpaCode(orgIpaCode, accessToken); + + Assertions.assertNull(result); + } + + @Test + void givenGenericHttpExceptionWhenGetOrganizationByIpaCodeThenThrowIt() { + String orgIpaCode = "ORGIPACODE"; + String accessToken = "ACCESSTOKEN"; + HttpClientErrorException expectedException = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR); + + Mockito.when(organizationApisHolder.getOrganizationSearchControllerApi(accessToken)) + .thenReturn(organizationSearchControllerApiMock); + Mockito.when(organizationSearchControllerApiMock.crudOrganizationsFindByIpaCode(orgIpaCode)) + .thenThrow(expectedException); + + HttpClientErrorException result = Assertions.assertThrows(expectedException.getClass(), () -> organizationSearchClient.getOrganizationByIpaCode(orgIpaCode, accessToken)); + + Assertions.assertSame(expectedException, result); + } + + @Test + void givenGenericExceptionWhenGetOrganizationByIpaCodeThenThrowIt() { + String orgIpaCode = "ORGIPACODE"; + String accessToken = "ACCESSTOKEN"; + RuntimeException expectedException = new RuntimeException(); + + Mockito.when(organizationApisHolder.getOrganizationSearchControllerApi(accessToken)) + .thenReturn(organizationSearchControllerApiMock); + Mockito.when(organizationSearchControllerApiMock.crudOrganizationsFindByIpaCode(orgIpaCode)) + .thenThrow(expectedException); + + RuntimeException result = Assertions.assertThrows(expectedException.getClass(), () -> organizationSearchClient.getOrganizationByIpaCode(orgIpaCode, accessToken)); + + Assertions.assertSame(expectedException, result); + } + +} diff --git a/src/test/java/it/gov/pagopa/payhub/auth/connector/config/OrganizationApiHolderTest.java b/src/test/java/it/gov/pagopa/payhub/auth/connector/config/OrganizationApiHolderTest.java new file mode 100644 index 00000000..eb4e1522 --- /dev/null +++ b/src/test/java/it/gov/pagopa/payhub/auth/connector/config/OrganizationApiHolderTest.java @@ -0,0 +1,61 @@ +package it.gov.pagopa.payhub.auth.connector.config; + +import it.gov.pagopa.payhub.auth.connector.BaseApiHolderTest; +import it.gov.pagopa.payhub.auth.connector.config.OrganizationApisHolder; +import it.gov.pagopa.pu.p4pa_organization.controller.ApiClient; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Broker; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; + +@ExtendWith(MockitoExtension.class) +class OrganizationApiHolderTest extends BaseApiHolderTest { + @Mock + private RestTemplateBuilder restTemplateBuilderMock; + + private OrganizationApisHolder organizationApisHolder; + + @BeforeEach + void setUp() { + Mockito.when(restTemplateBuilderMock.build()).thenReturn(restTemplateMock); + Mockito.when(restTemplateMock.getUriTemplateHandler()).thenReturn(new DefaultUriBuilderFactory()); + ApiClient apiClient = new ApiClient(restTemplateMock); + String baseUrl = "http://example.com"; + apiClient.setBasePath(baseUrl); + organizationApisHolder = new OrganizationApisHolder(baseUrl, restTemplateBuilderMock); + } + + @AfterEach + void verifyNoMoreInteractions() { + Mockito.verifyNoMoreInteractions( + restTemplateBuilderMock, + restTemplateMock + ); + } + + @Test + void whenGetOrganizationSearchControllerApiThenAuthenticationShouldBeSetInThreadSafeMode() throws InterruptedException { + assertAuthenticationShouldBeSetInThreadSafeMode( + accessToken -> organizationApisHolder.getOrganizationSearchControllerApi(accessToken) + .crudOrganizationsFindByIpaCode("IPACODE"), + Organization.class, + organizationApisHolder::unload); + } + + @Test + void whenGetAuthnApiThenAuthenticationShouldBeSetInThreadSafeMode() throws InterruptedException { + assertAuthenticationShouldBeSetInThreadSafeMode( + accessToken -> organizationApisHolder.getBrokerEntityControllerApi(accessToken) + .crudGetBroker("BROKERID"), + Broker.class, + organizationApisHolder::unload); + } + +} \ No newline at end of file diff --git a/src/test/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapperTest.java b/src/test/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapperTest.java index a7c17b2c..77574ef2 100644 --- a/src/test/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapperTest.java +++ b/src/test/java/it/gov/pagopa/payhub/auth/service/user/IamUserInfoDTO2UserInfoMapperTest.java @@ -1,5 +1,6 @@ package it.gov.pagopa.payhub.auth.service.user; +import it.gov.pagopa.payhub.auth.connector.client.OrganizationSearchClient; import it.gov.pagopa.payhub.auth.dto.IamUserInfoDTO; import it.gov.pagopa.payhub.auth.dto.IamUserOrganizationRolesDTO; import it.gov.pagopa.payhub.auth.exception.custom.UserNotFoundException; @@ -10,16 +11,21 @@ import it.gov.pagopa.payhub.auth.utils.Constants; import it.gov.pagopa.payhub.dto.generated.UserInfo; import it.gov.pagopa.payhub.dto.generated.UserOrganizationRoles; +import it.gov.pagopa.pu.p4pa_organization.dto.generated.Organization; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; @ExtendWith(MockitoExtension.class) class IamUserInfoDTO2UserInfoMapperTest { @@ -29,12 +35,16 @@ class IamUserInfoDTO2UserInfoMapperTest { @Mock private OperatorsRepository operatorsRepositoryMock; + @Mock + private OrganizationSearchClient organizationSearchClientMock; + + @InjectMocks private IamUserInfoDTO2UserInfoMapper mapper; @BeforeEach void init() { - mapper = new IamUserInfoDTO2UserInfoMapper(usersRepositoryMock, operatorsRepositoryMock); + mapper = new IamUserInfoDTO2UserInfoMapper(usersRepositoryMock, operatorsRepositoryMock, organizationSearchClientMock); } @AfterEach @@ -43,12 +53,12 @@ void verifyNotMoreInteractions() { } @Test - void givenNotUserWhenApplyThenUserNotFoundException(){ + void givenNotUserWhenApplyThenUserNotFoundException() { // Given IamUserInfoDTO iamUserInfo = IamUserInfoDTO.builder() - .userId("EXTERNALUSERID") - .innerUserId("INNERUSERID") - .build(); + .userId("EXTERNALUSERID") + .innerUserId("INNERUSERID") + .build(); Mockito.when(usersRepositoryMock.findById(iamUserInfo.getInnerUserId())).thenReturn(Optional.empty()); @@ -57,51 +67,53 @@ void givenNotUserWhenApplyThenUserNotFoundException(){ } @Test - void givenCompleteDataWhenApplyThenOk(){ + void givenCompleteDataWhenApplyThenOk() { // Given IamUserInfoDTO iamUserInfo = IamUserInfoDTO.builder() - .userId("EXTERNALUSERID") - .innerUserId("INNERUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .organizationAccess(IamUserOrganizationRolesDTO.builder() - .organizationIpaCode("ORG") - .email("EMAIL") - .build()) - .build(); + .userId("EXTERNALUSERID") + .innerUserId("INNERUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .organizationAccess(IamUserOrganizationRolesDTO.builder() + .organizationIpaCode("ORG") + .email("EMAIL") + .build()) + .build(); User user = User.builder() - .userId(iamUserInfo.getInnerUserId()) - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .build(); + .userId(iamUserInfo.getInnerUserId()) + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .build(); List organizationRoles = List.of(Operator.builder() - .operatorId("OPERATORID") - .organizationIpaCode("ORG") - .roles(Set.of("ROLE")) - .email("EMAIL") - .build()); + .operatorId("OPERATORID") + .organizationIpaCode("ORG") + .roles(Set.of("ROLE")) + .email("EMAIL") + .build()); UserInfo expected = UserInfo.builder() - .userId("INNERUSERID") - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .organizationAccess("ORG") - .organizations(List.of(UserOrganizationRoles.builder() - .operatorId("OPERATORID") - .organizationIpaCode("ORG") - .roles(List.of("ROLE")) - .email("EMAIL") - .build())) - .build(); + .userId("INNERUSERID") + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .organizationAccess("ORG") + .organizations(List.of(UserOrganizationRoles.builder() + .operatorId("OPERATORID") + .organizationIpaCode("ORG") + .roles(List.of("ROLE")) + .email("EMAIL") + .build())) + .build(); Mockito.when(usersRepositoryMock.findById(iamUserInfo.getInnerUserId())).thenReturn(Optional.of(user)); Mockito.when(operatorsRepositoryMock.findAllByUserId(user.getUserId())).thenReturn(organizationRoles); + Mockito.when(organizationSearchClientMock.getOrganizationByIpaCode(Mockito.eq("ORG"), Mockito.anyString())) + .thenReturn(new Organization()); // When UserInfo result = mapper.apply(iamUserInfo); @@ -111,36 +123,36 @@ void givenCompleteDataWhenApplyThenOk(){ } @Test - void givenNotOperatorsWhenApplyThenOk(){ + void givenNotOperatorsWhenApplyThenOk() { // Given IamUserInfoDTO iamUserInfo = IamUserInfoDTO.builder() - .userId("EXTERNALUSERID") - .innerUserId("INNERUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .organizationAccess(IamUserOrganizationRolesDTO.builder() - .organizationIpaCode("ORG") - .email("EMAIL") - .build()) - .build(); + .userId("EXTERNALUSERID") + .innerUserId("INNERUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .organizationAccess(IamUserOrganizationRolesDTO.builder() + .organizationIpaCode("ORG") + .email("EMAIL") + .build()) + .build(); User user = User.builder() - .userId(iamUserInfo.getInnerUserId()) - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .build(); + .userId(iamUserInfo.getInnerUserId()) + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .build(); UserInfo expected = UserInfo.builder() - .userId("INNERUSERID") - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .organizationAccess("ORG") - .organizations(Collections.emptyList()) - .build(); + .userId("INNERUSERID") + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .organizationAccess("ORG") + .organizations(Collections.emptyList()) + .build(); Mockito.when(usersRepositoryMock.findById(iamUserInfo.getInnerUserId())).thenReturn(Optional.of(user)); Mockito.when(operatorsRepositoryMock.findAllByUserId(user.getUserId())).thenReturn(Collections.emptyList()); @@ -153,43 +165,43 @@ void givenNotOperatorsWhenApplyThenOk(){ } @Test - void givenNoOrganizationAccessWhenApplyThenOk(){ + void givenNoOrganizationAccessWhenApplyThenOk() { // Given IamUserInfoDTO iamUserInfo = IamUserInfoDTO.builder() - .userId("EXTERNALUSERID") - .innerUserId("INNERUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .build(); + .userId("EXTERNALUSERID") + .innerUserId("INNERUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .build(); User user = User.builder() - .userId(iamUserInfo.getInnerUserId()) - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .build(); + .userId(iamUserInfo.getInnerUserId()) + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .build(); List organizationRoles = List.of(Operator.builder() - .operatorId("OPERATORID") - .organizationIpaCode("ORG") - .roles(Set.of("ROLE")) - .email("EMAIL") - .build()); + .operatorId("OPERATORID") + .organizationIpaCode("ORG") + .roles(Set.of("ROLE")) + .email("EMAIL") + .build()); UserInfo expected = UserInfo.builder() - .userId("INNERUSERID") - .mappedExternalUserId("MAPPEDEXTERNALUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("ISSUER") - .organizations(List.of(UserOrganizationRoles.builder() - .operatorId("OPERATORID") - .organizationIpaCode("ORG") - .roles(List.of("ROLE")) - .email("EMAIL") - .build())) - .build(); + .userId("INNERUSERID") + .mappedExternalUserId("MAPPEDEXTERNALUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("ISSUER") + .organizations(List.of(UserOrganizationRoles.builder() + .operatorId("OPERATORID") + .organizationIpaCode("ORG") + .roles(List.of("ROLE")) + .email("EMAIL") + .build())) + .build(); Mockito.when(usersRepositoryMock.findById(iamUserInfo.getInnerUserId())).thenReturn(Optional.of(user)); Mockito.when(operatorsRepositoryMock.findAllByUserId(user.getUserId())).thenReturn(organizationRoles); @@ -202,34 +214,34 @@ void givenNoOrganizationAccessWhenApplyThenOk(){ } @Test - void givenSystemUserWhenApplyThenOk(){ + void givenSystemUserWhenApplyThenOk() { // Given IamUserInfoDTO iamUserInfo = IamUserInfoDTO.builder() - .systemUser(Boolean.TRUE) - .userId("EXTERNALUSERID") - .innerUserId("INNERUSERID") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("IPA_CODE") - .organizationAccess(IamUserOrganizationRolesDTO.builder() - .organizationIpaCode("IPA_CODE") - .roles(Collections.singletonList(Constants.ROLE_ADMIN)) - .build()) - .build(); + .systemUser(Boolean.TRUE) + .userId("EXTERNALUSERID") + .innerUserId("INNERUSERID") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("IPA_CODE") + .organizationAccess(IamUserOrganizationRolesDTO.builder() + .organizationIpaCode("IPA_CODE") + .roles(Collections.singletonList(Constants.ROLE_ADMIN)) + .build()) + .build(); UserInfo expected = UserInfo.builder() - .userId("EXTERNALUSERID") - .mappedExternalUserId("IPA_CODE-WS_USER") - .fiscalCode("FISCALCODE") - .familyName("FAMILYNAME") - .name("NAME") - .issuer("IPA_CODE") - .organizations(Collections.singletonList(UserOrganizationRoles.builder() - .organizationIpaCode("IPA_CODE") - .roles(List.of(Constants.ROLE_ADMIN)) - .build())) - .build(); + .userId("EXTERNALUSERID") + .mappedExternalUserId("IPA_CODE-WS_USER") + .fiscalCode("FISCALCODE") + .familyName("FAMILYNAME") + .name("NAME") + .issuer("IPA_CODE") + .organizations(Collections.singletonList(UserOrganizationRoles.builder() + .organizationIpaCode("IPA_CODE") + .roles(List.of(Constants.ROLE_ADMIN)) + .build())) + .build(); // When UserInfo result = mapper.apply(iamUserInfo);