Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: P4ADEV-1752 added brokerId and brokerFiscalCode to UserInfo #123

Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ RUN apk add --no-cache \
wget \
unzip \
bash \
shadow
shadow \
git

# Create Gradle user
RUN groupadd --system --gid 1000 ${APP_GROUP} && \
Expand Down Expand Up @@ -93,6 +94,7 @@ WORKDIR /build
COPY --chown=${APP_USER}:${APP_GROUP} build.gradle.kts settings.gradle.kts ./
COPY --chown=${APP_USER}:${APP_GROUP} gradle.lockfile ./
COPY --chown=${APP_USER}:${APP_GROUP} openapi openapi/
COPY .git .git

# Generate OpenAPI stubs and download dependencies
RUN mkdir -p src/main/java && \
Expand All @@ -101,7 +103,9 @@ RUN mkdir -p src/main/java && \

USER ${APP_USER}

RUN gradle openApiGenerate dependencies --no-daemon
RUN gradle openApiGenerateP4PAAUTH dependencies --no-daemon

RUN gradle openApiGenerateOrganization dependencies --no-daemon

#
# 🏗️ Build Stage
Expand Down
35 changes: 33 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ plugins {
id("org.sonarqube") version "6.0.1.5171"
id("com.github.ben-manes.versions") version "0.51.0"
id("org.openapi.generator") version "7.10.0"
id("org.ajoberstar.grgit") version "5.3.0"
}

group = "it.gov.pagopa.payhub"
Expand Down Expand Up @@ -108,7 +109,7 @@ configurations {
}

tasks.compileJava {
dependsOn("openApiGenerate")
dependsOn("openApiGenerateP4PAAUTH","openApiGenerateOrganization")
}

configure<SourceSetContainer> {
Expand All @@ -121,7 +122,10 @@ springBoot {
mainClass.value("it.gov.pagopa.payhub.auth.PayhubAuthApplication")
}

openApiGenerate {
tasks.register<org.openapitools.generator.gradle.plugin.tasks.GenerateTask>("openApiGenerateP4PAAUTH") {
group = "openapi"
description = "description"

generatorName.set("spring")
inputSpec.set("$rootDir/openapi/p4pa-auth.openapi.yaml")
outputDir.set("$projectDir/build/generated")
Expand All @@ -137,4 +141,31 @@ openApiGenerate {
"generatedConstructorWithRequiredArgs" to "true",
"additionalModelTypeAnnotations" to "@lombok.Data @lombok.Builder @lombok.AllArgsConstructor"
))
}

var targetEnv = when (grgit.branch.current().name) {
"uat" -> "uat"
"main" -> "main"
else -> "develop"
}

tasks.register<org.openapitools.generator.gradle.plugin.tasks.GenerateTask>("openApiGenerateOrganization") {
group = "openapi"
description = "description"

generatorName.set("java")
remoteInputSpec.set("https://raw.githubusercontent.com/pagopa/p4pa-organization/refs/heads/$targetEnv/openapi/generated.openapi.json")
outputDir.set("$projectDir/build/generated")
apiPackage.set("it.gov.pagopa.pu.p4pa-organization.controller.generated")
modelPackage.set("it.gov.pagopa.pu.p4pa-organization.dto.generated")
configOptions.set(mapOf(
"swaggerAnnotations" to "false",
"openApiNullable" to "false",
"dateLibrary" to "java17",
"useSpringBoot3" to "true",
"useJakartaEe" to "true",
"serializationLibrary" to "jackson",
"generateSupportingFiles" to "true"
))
library.set("resttemplate")
}
10 changes: 10 additions & 0 deletions openapi/p4pa-auth.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,9 @@ components:
- email
- issuer
- organizations
- brokerId
- brokerFiscalCode
- canManageUsers
properties:
userId:
type: string
Expand All @@ -572,6 +575,13 @@ components:
type: array
items:
$ref: '#/components/schemas/UserOrganizationRoles'
brokerId:
type: integer
format: int64
brokerFiscalCode:
type: string
canManageUsers:
type: boolean
UserOrganizationRoles:
type: object
required:
Expand Down
11 changes: 7 additions & 4 deletions postman/p4pa-auth-E2E.postman_collection.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"info": {
"_postman_id": "5b798cd0-2e20-45a4-88bb-08a0b26c6158",
"_postman_id": "cc929f09-50c0-4887-bf81-b41f8c297554",
"name": "p4pa-auth-E2E",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "15747968",
"_collection_link": "https://warped-astronaut-141685.postman.co/workspace/P4PA~9a8b7dd5-97b6-4dd0-b3f5-95f25fd0b455/collection/15747968-5b798cd0-2e20-45a4-88bb-08a0b26c6158?action=share&source=collection_link&creator=15747968"
"_exporter_id": "29647564",
"_collection_link": "https://galactic-eclipse-948669.postman.co/workspace/New-Team-Workspace~be56c5f1-de0c-4252-95d0-ee80f35e2474/collection/29647564-cc929f09-50c0-4887-bf81-b41f8c297554?action=share&source=collection_link&creator=29647564"
},
"item": [
{
Expand Down Expand Up @@ -279,8 +279,11 @@
" pm.expect(jsonResponse).have.property(\"fiscalCode\").to.eq(\"DMEMPY15L21L736U\")\r",
" pm.expect(jsonResponse).have.property(\"issuer\").to.eq(pm.environment.get(\"tokenExchange_issuer\"))\r",
" pm.expect(jsonResponse).have.property(\"organizationAccess\").to.eq(\"IPA_TEST\")\r",
" pm.expect(jsonResponse).to.have.property(\"brokerId\").that.is.a(\"number\");\r",
" pm.expect(jsonResponse).to.have.property(\"brokerFiscalCode\").that.is.a(\"string\");\r",
" pm.expect(jsonResponse).to.have.property(\"canManageUsers\").that.is.a(\"boolean\");\r",
"\r",
" pm.expect(jsonResponse.organizations).have.property(\"length\").to.gte(3)\r",
" pm.expect(jsonResponse.organizations).to.have.property(\"length\").to.gte(3);\r",
" \r",
" pm.collectionVariables.set(\"mappedExternalUserId\",jsonResponse.mappedExternalUserId)\r",
" pm.collectionVariables.set(\"organizationIpaCode\",jsonResponse.organizationAccess)\r",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"info": {
"_postman_id": "c1508e85-2efa-460b-8f3a-ff7ee32007a0",
"_postman_id": "4cce1599-b728-41d3-8dab-bfa5f589956c",
"name": "p4pa-auth-NoAccessModeOrganization",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "36568841"
"_exporter_id": "29647564",
"_collection_link": "https://galactic-eclipse-948669.postman.co/workspace/New-Team-Workspace~be56c5f1-de0c-4252-95d0-ee80f35e2474/collection/29647564-4cce1599-b728-41d3-8dab-bfa5f589956c?action=share&source=collection_link&creator=29647564"
},
"item": [
{
Expand Down Expand Up @@ -231,6 +232,9 @@
" pm.expect(jsonResponse).have.property(\"fiscalCode\").to.eq(\"DMEMPY15L21L736U\")\r",
" pm.expect(jsonResponse).have.property(\"issuer\").to.eq(pm.environment.get(\"tokenExchange_issuer\"))\r",
" pm.expect(jsonResponse).have.property(\"organizationAccess\").to.eq(\"IPA_TEST\")\r",
" pm.expect(jsonResponse).to.have.property(\"brokerId\").that.is.a(\"number\");\r",
" pm.expect(jsonResponse).to.have.property(\"brokerFiscalCode\").that.is.a(\"string\");\r",
" pm.expect(jsonResponse).to.have.property(\"canManageUsers\").that.is.a(\"boolean\");\r",
"\r",
" pm.expect(jsonResponse.organizations).have.property(\"length\").to.gte(3)\r",
" \r",
Expand Down
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package it.gov.pagopa.payhub.auth.connector.client;

import it.gov.pagopa.payhub.auth.connector.config.OrganizationApisHolder;
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.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;

@Service
@Slf4j
public class OrganizationSearchClient {

private final OrganizationApisHolder organizationApisHolder;

public OrganizationSearchClient(OrganizationApisHolder organizationApisHolder) {
this.organizationApisHolder = organizationApisHolder;
}


public Broker getBrokerById(Long id, String accessToken) {
try {
return organizationApisHolder.getBrokerEntityControllerApi(accessToken).getItemResourceBrokerGet(String.valueOf(id));
} catch (Exception e) {
log.error(String.valueOf(e.getCause()));
return null;
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
}
}

public Organization getOrganizationByIpaCode(String ipaCode, String accessToken) {
try {
return organizationApisHolder.getOrganizationSearchControllerApi(accessToken)
.executeSearchOrganizationGet(ipaCode);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
log.warn("Organization with IPA code {} not found", ipaCode);
return null;
}
log.error("Error retrieving organization by IPA code: {}", ipaCode, e);
throw e;
} catch (Exception e) {
log.error("Unexpected error while retrieving organization by IPA code: {}", ipaCode, e);
throw e;
}
}

}
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package it.gov.pagopa.payhub.auth.connector.config;

import it.gov.pagopa.pu.p4pa_organization.controller.ApiClient;
import it.gov.pagopa.pu.p4pa_organization.controller.BaseApi;
import it.gov.pagopa.pu.p4pa_organization.controller.generated.BrokerEntityControllerApi;
import it.gov.pagopa.pu.p4pa_organization.controller.generated.OrganizationSearchControllerApi;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Lazy
@Service
public class OrganizationApisHolder {

private final BrokerEntityControllerApi brokerEntityControllerApi;
private final OrganizationSearchControllerApi organizationSearchControllerApi;

private final ThreadLocal<String> bearerTokenHolder = new ThreadLocal<>();

public OrganizationApisHolder(
@Value("${rest.organization.base-url}") String baseUrl,

RestTemplateBuilder restTemplateBuilder) {
RestTemplate restTemplate = restTemplateBuilder.build();
ApiClient apiClient = new ApiClient(restTemplate);
apiClient.setBasePath(baseUrl);
apiClient.setBearerToken(bearerTokenHolder::get);

this.organizationSearchControllerApi = new OrganizationSearchControllerApi(apiClient);
this.brokerEntityControllerApi = new BrokerEntityControllerApi(apiClient);
}

@PreDestroy
public void unload() {
bearerTokenHolder.remove();
}

/**
* It will return a {@link OrganizationSearchControllerApi} instrumented with the provided accessToken. Use null if auth is not required
*/
public OrganizationSearchControllerApi getOrganizationSearchControllerApi(String accessToken) {
return getApi(accessToken, organizationSearchControllerApi);
}

/**
* It will return a {@link BrokerEntityControllerApi} instrumented with the provided accessToken. Use null if auth is not required
*/
public BrokerEntityControllerApi getBrokerEntityControllerApi(String accessToken) {
return getApi(accessToken, brokerEntityControllerApi);
}

private <T extends BaseApi> T getApi(String accessToken, T api) {
bearerTokenHolder.set(accessToken);
return api;
}

}
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -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.exception.custom.InvalidAccessTokenException;
import it.gov.pagopa.payhub.auth.model.Operator;
Expand All @@ -10,7 +11,10 @@
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;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -21,11 +25,15 @@
@Slf4j
public class UserServiceImpl implements UserService {

private OrganizationSearchClient organizationSearchClient;
private final TokenStoreService tokenStoreService;
private final UserRegistrationService userRegistrationService;
private final OperatorRegistrationService operatorRegistrationService;
private final IamUserInfoDTO2UserInfoMapper userInfoMapper;
private final OrganizationOperatorRetrieverService organizationOperatorRetrieverService;
@Value("${app.enable-access-organization-mode}")
private boolean organizationAccessMode;


public UserServiceImpl(TokenStoreService tokenStoreService, UserRegistrationService userRegistrationService, OperatorRegistrationService operatorRegistrationService, IamUserInfoDTO2UserInfoMapper userInfoMapper, OrganizationOperatorRetrieverService organizationOperatorRetrieverService) {
this.tokenStoreService = tokenStoreService;
Expand All @@ -51,14 +59,44 @@ public UserInfo getUserInfo(String accessToken) {
IamUserInfoDTO userInfo = tokenStoreService.load(accessToken);
if (userInfo == null) {
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 {
return userInfoMapper.apply(userInfo);
log.debug("SelfCare mode disabled or organizationAccess not provided. Cannot fetch organization.");
}

UserInfo result = userInfoMapper.apply(userInfo);
result.setCanManageUsers(!organizationAccessMode);
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
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");
return result;
}

@Override
public Page<OperatorDTO> retrieveOrganizationOperators(String organizationIpaCode, Pageable pageable) {
log.info("Retrieving organization {} operators", organizationIpaCode);
return organizationOperatorRetrieverService.retrieveOrganizationOperators(organizationIpaCode, pageable);
}

}
2 changes: 2 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ 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}"
organization:
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved
base-url: "\${ORGANIZATION_BASE_URL:}"
antonioT90 marked this conversation as resolved.
Show resolved Hide resolved

data-cipher:
p4pa-auth-hash-key: "\${DATA_CIPHER_P4PA_AUTH_HASH_KEY:PEPPER}"
Expand Down
Loading