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

fix: P4ADEV-635 storing operator when login #36

Merged
merged 3 commits into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion helm/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ microservice-chart:
REDIS_SSL_ENABLED: "true"

JWT_TOKEN_EXPIRATION_SECONDS: "14400" # 4 HOURS
ENABLE_ACCESS_ORGANIZATION_MODE: "true"
ACCESS_ORGANIZATION_MODE_ENABLED: "true"

envSecret:
APPLICATIONINSIGHTS_CONNECTION_STRING: appinsights-connection-string
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package it.gov.pagopa.payhub.auth.exception.custom;

public class InvalidOrganizationAccessDataException extends RuntimeException {
public InvalidOrganizationAccessDataException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
import it.gov.pagopa.payhub.auth.model.Operator;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface OperatorsRepository extends MongoRepository<Operator, String> {
public interface OperatorsRepository extends OperatorsRepositoryExt, MongoRepository<Operator, String> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package it.gov.pagopa.payhub.auth.repository;

import it.gov.pagopa.payhub.auth.model.Operator;

import java.util.Set;

public interface OperatorsRepositoryExt {
Operator registerOperator(String userId, String organizationIpaCode, Set<String> roles);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package it.gov.pagopa.payhub.auth.repository;

import it.gov.pagopa.payhub.auth.model.Operator;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Set;

public class OperatorsRepositoryExtImpl implements OperatorsRepositoryExt{
private final MongoTemplate mongoTemplate;

public OperatorsRepositoryExtImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}

@Override
public Operator registerOperator(String userId, String organizationIpaCode, Set<String> roles) {
return mongoTemplate.findAndModify(
Query.query(Criteria
.where(Operator.Fields.userId).is(userId)
.and(Operator.Fields.organizationIpaCode).is(organizationIpaCode)),
new Update()
.set(Operator.Fields.roles, roles),
FindAndModifyOptions.options()
.returnNew(true)
.upsert(true),
Operator.class
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import com.auth0.jwt.interfaces.Claim;
import io.jsonwebtoken.Claims;
import it.gov.pagopa.payhub.auth.exception.custom.InvalidOrganizationAccessDataException;
import it.gov.pagopa.payhub.auth.exception.custom.InvalidTokenException;
import it.gov.pagopa.payhub.model.generated.UserInfo;
import it.gov.pagopa.payhub.model.generated.UserOrganizationRoles;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
Expand All @@ -14,26 +16,48 @@

@Service
public class IDTokenClaims2UserInfoMapper implements Function<Map<String, Claim>, UserInfo> {

private final boolean organizationAccessMode;

public IDTokenClaims2UserInfoMapper(
@Value("${app.enable-access-organization-mode}") boolean organizationAccessMode) {
this.organizationAccessMode = organizationAccessMode;
}

@Override
public UserInfo apply(Map<String, Claim> claims) {
try {
UserOrganizationRoles organizationRoles = buildUserOrganizationRoles(claims);
return UserInfo.builder()
UserInfo userInfo = UserInfo.builder()
.issuer(claims.get(Claims.ISSUER).asString())
.userId(claims.get("uid").asString())
.name(claims.get("name").asString())
.familyName(claims.get("family_name").asString())
.fiscalCode(claims.get("fiscal_number").asString())
.organizationAccess(organizationRoles.getIpaCode())
.organizations(List.of(organizationRoles))
.build();

UserOrganizationRoles organizationRoles = buildUserOrganizationRoles(claims);
if(organizationRoles!=null){
userInfo.setOrganizationAccess(organizationRoles.getIpaCode());
userInfo.setOrganizations(List.of(organizationRoles));
}

return userInfo;
} catch (Exception e){
throw new InvalidTokenException("Unexpected IDToken structure", e);
}
}

private UserOrganizationRoles buildUserOrganizationRoles(Map<String, Claim> claims) {
Map<String, Object> organizationClaim = claims.get("organization").asMap();
Claim organization = claims.get("organization");
if(organization==null){
if(organizationAccessMode){
throw new InvalidOrganizationAccessDataException("No organizationAccess information");
} else {
return null;
}
}

Map<String, Object> organizationClaim = organization.asMap();

List<String> roles = readUserOrganizationRoles(organizationClaim);
return UserOrganizationRoles.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package it.gov.pagopa.payhub.auth.service.exchange;

import it.gov.pagopa.payhub.auth.exception.custom.InvalidOrganizationAccessDataException;
import it.gov.pagopa.payhub.auth.model.User;
import it.gov.pagopa.payhub.auth.service.user.UserService;
import it.gov.pagopa.payhub.model.generated.UserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

@Service
public class IamUserRegistrationService {

Expand All @@ -22,10 +28,19 @@ public IamUserRegistrationService(
}

void registerUser(UserInfo userInfo){
userService.registerUser(userInfo.getUserId(), userInfo.getFiscalCode(), userInfo.getIssuer());
User user = userService.registerUser(userInfo.getUserId(), userInfo.getFiscalCode(), userInfo.getIssuer());

if(organizationAccessMode){
//store Operators
Optional<Set<String>> roles = userInfo.getOrganizations().stream()
.filter(r -> userInfo.getOrganizationAccess().equals(r.getIpaCode()))
.findFirst()
.map(userOrganizationRoles -> new HashSet<>(userOrganizationRoles.getRoles()));

if(roles.isEmpty()){
throw new InvalidOrganizationAccessDataException("No roles configured for organizationAccess " + userInfo.getOrganizationAccess() + "; organizations: " + userInfo.getOrganizations());
}

userService.registerOperator(user.getUserId(), userInfo.getOrganizationAccess(), roles.get());
}
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package it.gov.pagopa.payhub.auth.service.user;

import it.gov.pagopa.payhub.auth.model.Operator;
import it.gov.pagopa.payhub.auth.model.User;
import it.gov.pagopa.payhub.model.generated.UserInfo;

import java.util.Set;

public interface UserService {
User registerUser(String externalUserId, String fiscalCode, String iamIssuer);
Operator registerOperator(String userId, String organizationIpaCode, Set<String> roles);
UserInfo getUserInfo(String accessToken);
}
Original file line number Diff line number Diff line change
@@ -1,28 +1,39 @@
package it.gov.pagopa.payhub.auth.service.user;

import it.gov.pagopa.payhub.auth.exception.custom.InvalidAccessTokenException;
import it.gov.pagopa.payhub.auth.model.Operator;
import it.gov.pagopa.payhub.auth.model.User;
import it.gov.pagopa.payhub.auth.service.TokenStoreService;
import it.gov.pagopa.payhub.auth.service.user.registration.OperatorRegistrationService;
import it.gov.pagopa.payhub.auth.service.user.registration.UserRegistrationService;
import it.gov.pagopa.payhub.model.generated.UserInfo;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class UserServiceImpl implements UserService{

private final TokenStoreService tokenStoreService;
private final UserRegistrationService userRegistrationService;
private final OperatorRegistrationService operatorRegistrationService;

public UserServiceImpl(TokenStoreService tokenStoreService, UserRegistrationService userRegistrationService) {
public UserServiceImpl(TokenStoreService tokenStoreService, UserRegistrationService userRegistrationService, OperatorRegistrationService operatorRegistrationService) {
this.tokenStoreService = tokenStoreService;
this.userRegistrationService = userRegistrationService;
this.operatorRegistrationService = operatorRegistrationService;
}

@Override
public User registerUser(String externalUserId, String fiscalCode, String iamIssuer) {
return userRegistrationService.registerUser(externalUserId, fiscalCode, iamIssuer);
}

@Override
public Operator registerOperator(String userId, String organizationIpaCode, Set<String> roles) {
return operatorRegistrationService.registerOperator(userId, organizationIpaCode, roles);
}

@Override
public UserInfo getUserInfo(String accessToken) {
UserInfo userInfo = tokenStoreService.load(accessToken);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package it.gov.pagopa.payhub.auth.service.user.registration;

import it.gov.pagopa.payhub.auth.model.Operator;
import it.gov.pagopa.payhub.auth.repository.OperatorsRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@Slf4j
public class OperatorRegistrationService {

private final OperatorsRepository operatorsRepository;

public OperatorRegistrationService(OperatorsRepository operatorsRepository) {
this.operatorsRepository = operatorsRepository;
}

public Operator registerOperator(String userId, String organizationIpaCode, Set<String> roles){
log.info("Registering relationship between userId {} and organization {} setting roles {}",
userId, organizationIpaCode, roles);

return operatorsRepository.registerOperator(userId, organizationIpaCode, roles);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import it.gov.pagopa.payhub.auth.model.User;
import it.gov.pagopa.payhub.auth.repository.UsersRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserRegistrationService {

private final ExternalUserIdObfuscatorService externalUserIdObfuscatorService;
Expand All @@ -19,6 +21,7 @@ public UserRegistrationService(ExternalUserIdObfuscatorService externalUserIdObf

public User registerUser(String externalUserId, String fiscalCode, String iamIssuer){
User user = buildUser(externalUserId, fiscalCode, iamIssuer);
log.info("Registering user having mappedExternalUserId {}", user.getMappedExternalUserId());
return usersRepository.registerUser(user);
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ app:
# If true, it will expect the presence of the access organization inside the ID Token.
# 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: "\${ENABLE_ACCESS_ORGANIZATION_MODE:true}"
enable-access-organization-mode: "\${ACCESS_ORGANIZATION_MODE_ENABLED:true}"
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package it.gov.pagopa.payhub.auth.repository;

import it.gov.pagopa.payhub.auth.model.Operator;
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.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Set;

@ExtendWith(MockitoExtension.class)
class OperatorsRepositoryExtImplTest {

@Mock
private MongoTemplate mongoTemplateMock;

private OperatorsRepositoryExt repository;

@BeforeEach
void init() {
repository = new OperatorsRepositoryExtImpl(mongoTemplateMock);
}

@AfterEach
void verifyNotMoreInvocation() {
Mockito.verifyNoMoreInteractions(mongoTemplateMock);
}

@Test
void whenRegisterUserThenReturnStoredUser() {
// Given
String userId="USERID";
String organizationIpaCode="ORGANIZATIONIPACODE";
Set<String> roles = Set.of("ROLE");
Operator storedOperator = new Operator();

Mockito.when(mongoTemplateMock.findAndModify(
Mockito.eq(Query.query(Criteria
.where(Operator.Fields.userId).is(userId)
.and(Operator.Fields.organizationIpaCode).is(organizationIpaCode))),
Mockito.eq(new Update()
.set(Operator.Fields.roles, roles)),
Mockito.argThat(opt -> opt.isReturnNew() && opt.isUpsert() && !opt.isRemove()),
Mockito.eq(Operator.class)
)).thenReturn(storedOperator);

// When
Operator result = repository.registerOperator(userId, organizationIpaCode, roles);

// Then
Assertions.assertSame(storedOperator, result);
}
}
Loading