diff --git a/src/Portal.Backend.sln b/src/Portal.Backend.sln index cd6bb760b7..31bf09a121 100644 --- a/src/Portal.Backend.sln +++ b/src/Portal.Backend.sln @@ -240,6 +240,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Registration.Common", "regi EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Keycloak.Authentication.Tests", "..\tests\keycloak\Keycloak.Authentication.Tests\Keycloak.Authentication.Tests.csproj", "{C7ACF748-DEF4-4646-A791-F1DA437CC965}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Framework.ProcessIdentity.Tests", "..\tests\framework\Framework.ProcessIdentity.Tests\Framework.ProcessIdentity.Tests.csproj", "{996CAB8C-B43A-4E76-B906-034A395C1429}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1522,6 +1524,18 @@ Global {C7ACF748-DEF4-4646-A791-F1DA437CC965}.Release|x64.Build.0 = Release|Any CPU {C7ACF748-DEF4-4646-A791-F1DA437CC965}.Release|x86.ActiveCfg = Release|Any CPU {C7ACF748-DEF4-4646-A791-F1DA437CC965}.Release|x86.Build.0 = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|Any CPU.Build.0 = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|x64.ActiveCfg = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|x64.Build.0 = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|x86.ActiveCfg = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Debug|x86.Build.0 = Debug|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|Any CPU.ActiveCfg = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|Any CPU.Build.0 = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|x64.ActiveCfg = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|x64.Build.0 = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|x86.ActiveCfg = Release|Any CPU + {996CAB8C-B43A-4E76-B906-034A395C1429}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1530,6 +1544,7 @@ Global SolutionGuid = {2EB6265F-323A-4BF3-969E-003D64A14B64} EndGlobalSection GlobalSection(NestedProjects) = preSolution + {996CAB8C-B43A-4E76-B906-034A395C1429} = {323C198D-A8C6-4EB0-8B79-72624275E35F} {146865E5-7DFF-4CC2-8521-9E22CFCEEA20} = {323C198D-A8C6-4EB0-8B79-72624275E35F} {A43B5ACA-1209-46E9-84DB-A48553ED623E} = {323C198D-A8C6-4EB0-8B79-72624275E35F} {1EAF34DA-6D16-4F5E-86F4-344185F53942} = {323C198D-A8C6-4EB0-8B79-72624275E35F} diff --git a/src/administration/Administration.Service/BusinessLogic/CompanyDataBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/CompanyDataBusinessLogic.cs index 80eb0cb1f1..6b039be9b4 100644 --- a/src/administration/Administration.Service/BusinessLogic/CompanyDataBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/CompanyDataBusinessLogic.cs @@ -48,7 +48,7 @@ public class CompanyDataBusinessLogic : ICompanyDataBusinessLogic private readonly IMailingService _mailingService; private readonly ICustodianService _custodianService; private readonly IDateTimeProvider _dateTimeProvider; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly CompanyDataSettings _settings; /// @@ -66,14 +66,14 @@ public CompanyDataBusinessLogic(IPortalRepositories portalRepositories, IMailing _mailingService = mailingService; _custodianService = custodianService; _dateTimeProvider = dateTimeProvider; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = options.Value; } /// public async Task GetCompanyDetailsAsync() { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetCompanyDetailsAsync(companyId).ConfigureAwait(false); if (result == null) { @@ -84,12 +84,12 @@ public async Task GetCompanyDetailsAsync() /// public IAsyncEnumerable GetCompanyAssigendUseCaseDetailsAsync() => - _portalRepositories.GetInstance().GetCompanyAssigendUseCaseDetailsAsync(_identityService.IdentityData.CompanyId); + _portalRepositories.GetInstance().GetCompanyAssigendUseCaseDetailsAsync(_identityData.CompanyId); /// public async Task CreateCompanyAssignedUseCaseDetailsAsync(Guid useCaseId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var companyRepositories = _portalRepositories.GetInstance(); var useCaseDetails = await companyRepositories.GetCompanyStatusAndUseCaseIdAsync(companyId, useCaseId).ConfigureAwait(false); if (!useCaseDetails.IsActiveCompanyStatus) @@ -108,7 +108,7 @@ public async Task CreateCompanyAssignedUseCaseDetailsAsync(Guid useCaseId) /// public async Task RemoveCompanyAssignedUseCaseDetailsAsync(Guid useCaseId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var companyRepositories = _portalRepositories.GetInstance(); var useCaseDetails = await companyRepositories.GetCompanyStatusAndUseCaseIdAsync(companyId, useCaseId).ConfigureAwait(false); if (!useCaseDetails.IsActiveCompanyStatus) @@ -125,7 +125,7 @@ public async Task RemoveCompanyAssignedUseCaseDetailsAsync(Guid useCaseId) public async IAsyncEnumerable GetCompanyRoleAndConsentAgreementDetailsAsync(string? languageShortName) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; if (languageShortName != null && !await _portalRepositories.GetInstance().IsValidLanguageCode(languageShortName).ConfigureAwait(false)) { throw new ControllerArgumentException($"language {languageShortName} is not a valid languagecode"); @@ -168,12 +168,11 @@ public async Task CreateCompanyRoleAndConsentAgreementDetailsAsync(IEnumerable(); - var result = await companyRepositories.GetCompanyRolesDataAsync(identity.CompanyId, companyRoleConsentDetails.Select(x => x.CompanyRole)).ConfigureAwait(false); + var result = await companyRepositories.GetCompanyRolesDataAsync(_identityData.CompanyId, companyRoleConsentDetails.Select(x => x.CompanyRole)).ConfigureAwait(false); if (!result.IsValidCompany) { - throw new ConflictException($"company {identity.CompanyId} does not exist"); + throw new ConflictException($"company {_identityData.CompanyId} does not exist"); } if (!result.IsCompanyActive) { @@ -219,14 +218,14 @@ public async Task CreateCompanyRoleAndConsentAgreementDetailsAsync(IEnumerable().AddAttachAndModifyConsents( result.ConsentStatusDetails, joined.SelectMany(x => x.Agreements).DistinctBy(active => active.AgreementId).Select(active => (active.AgreementId, active.ConsentStatus)).ToList(), - identity.CompanyId, - identity.UserId, + _identityData.CompanyId, + _identityData.IdentityId, _dateTimeProvider.OffsetNow); var companyRolesRepository = _portalRepositories.GetInstance(); - companyRolesRepository.CreateCompanyAssignedRoles(identity.CompanyId, joined.Where(j => j.AllActiveAgreements && !result.CompanyRoleIds.Contains(j.CompanyRoleId)).Select(x => x.CompanyRoleId)); - companyRolesRepository.RemoveCompanyAssignedRoles(identity.CompanyId, joined.Where(j => j.AllInActiveAgreements && result.CompanyRoleIds.Contains(j.CompanyRoleId)).Select(x => x.CompanyRoleId)); + companyRolesRepository.CreateCompanyAssignedRoles(_identityData.CompanyId, joined.Where(j => j.AllActiveAgreements && !result.CompanyRoleIds.Contains(j.CompanyRoleId)).Select(x => x.CompanyRoleId)); + companyRolesRepository.RemoveCompanyAssignedRoles(_identityData.CompanyId, joined.Where(j => j.AllInActiveAgreements && result.CompanyRoleIds.Contains(j.CompanyRoleId)).Select(x => x.CompanyRoleId)); await _portalRepositories.SaveAsync(); } @@ -235,7 +234,7 @@ public async Task CreateCompanyRoleAndConsentAgreementDetailsAsync(IEnumerable> GetUseCaseParticipationAsync(string? language) => await _portalRepositories .GetInstance() - .GetUseCaseParticipationForCompany(_identityService.IdentityData.CompanyId, language ?? Constants.DefaultLanguage) + .GetUseCaseParticipationForCompany(_identityData.CompanyId, language ?? Constants.DefaultLanguage) .Select(x => new UseCaseParticipationData( x.UseCase, x.Description, @@ -261,7 +260,7 @@ await _portalRepositories public async Task> GetSsiCertificatesAsync() => await _portalRepositories .GetInstance() - .GetSsiCertificates(_identityService.IdentityData.CompanyId) + .GetSsiCertificates(_identityData.CompanyId) .Select(x => new SsiCertificateData( x.CredentialType, x.SsiDetailData.Select(d => new CompanySsiDetailData( @@ -310,8 +309,7 @@ private async Task HandleSsiCreationAsync( ICompanySsiDetailsRepository companyCredentialDetailsRepository, CancellationToken cancellationToken) { - var identity = _identityService.IdentityData; - if (await companyCredentialDetailsRepository.CheckSsiDetailsExistsForCompany(identity.CompanyId, credentialTypeId, kindId, verifiedCredentialExternalTypeDetailId).ConfigureAwait(false)) + if (await companyCredentialDetailsRepository.CheckSsiDetailsExistsForCompany(_identityData.CompanyId, credentialTypeId, kindId, verifiedCredentialExternalTypeDetailId).ConfigureAwait(false)) { throw new ControllerArgumentException("Credential request already existing"); } @@ -320,11 +318,11 @@ private async Task HandleSsiCreationAsync( var doc = _portalRepositories.GetInstance().CreateDocument(document.FileName, documentContent, hash, mediaTypeId, DocumentTypeId.PRESENTATION, x => { - x.CompanyUserId = identity.UserId; + x.CompanyUserId = _identityData.IdentityId; x.DocumentStatusId = DocumentStatusId.PENDING; }); - companyCredentialDetailsRepository.CreateSsiDetails(identity.CompanyId, credentialTypeId, doc.Id, CompanySsiDetailStatusId.PENDING, identity.UserId, details => + companyCredentialDetailsRepository.CreateSsiDetails(_identityData.CompanyId, credentialTypeId, doc.Id, CompanySsiDetailStatusId.PENDING, _identityData.IdentityId, details => { if (verifiedCredentialExternalTypeDetailId != null) { @@ -381,7 +379,7 @@ private async Task HandleSsiCreationAsync( public async Task ApproveCredential(Guid credentialId, CancellationToken cancellationToken) { var companySsiRepository = _portalRepositories.GetInstance(); - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; var (exists, data) = await companySsiRepository.GetSsiApprovalData(credentialId).ConfigureAwait(false); if (!exists) { @@ -455,7 +453,7 @@ public async Task ApproveCredential(Guid credentialId, CancellationToken cancell public async Task RejectCredential(Guid credentialId) { var companySsiRepository = _portalRepositories.GetInstance(); - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; var (exists, status, type, requesterId, requesterEmail, requesterFirstname, requesterLastname) = await companySsiRepository.GetSsiRejectionData(credentialId).ConfigureAwait(false); if (!exists) { @@ -501,5 +499,5 @@ public async Task RejectCredential(Guid credentialId) /// public IAsyncEnumerable GetCertificateTypes() => - _portalRepositories.GetInstance().GetCertificateTypes(_identityService.IdentityData.CompanyId); + _portalRepositories.GetInstance().GetCertificateTypes(_identityData.CompanyId); } diff --git a/src/administration/Administration.Service/BusinessLogic/ConnectorsBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/ConnectorsBusinessLogic.cs index 689a88be67..385fcfb4fe 100644 --- a/src/administration/Administration.Service/BusinessLogic/ConnectorsBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/ConnectorsBusinessLogic.cs @@ -42,7 +42,7 @@ public class ConnectorsBusinessLogic : IConnectorsBusinessLogic { private readonly IPortalRepositories _portalRepositories; private readonly ISdFactoryBusinessLogic _sdFactoryBusinessLogic; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly ILogger _logger; private readonly ConnectorsSettings _settings; private static readonly Regex bpnRegex = new(@"(\w|\d){16}", RegexOptions.None, TimeSpan.FromSeconds(1)); @@ -60,7 +60,7 @@ public ConnectorsBusinessLogic(IPortalRepositories portalRepositories, IOptions< _portalRepositories = portalRepositories; _settings = options.Value; _sdFactoryBusinessLogic = sdFactoryBusinessLogic; - _identityService = identityService; + _identityData = identityService.IdentityData; _logger = logger; } @@ -70,7 +70,7 @@ public ConnectorsBusinessLogic(IPortalRepositories portalRepositories, IOptions< page, size, _settings.MaxPageSize, - _portalRepositories.GetInstance().GetAllCompanyConnectorsForCompanyId(_identityService.IdentityData.CompanyId)); + _portalRepositories.GetInstance().GetAllCompanyConnectorsForCompanyId(_identityData.CompanyId)); /// public Task> GetManagedConnectorForCompany(int page, int size) => @@ -78,11 +78,11 @@ public ConnectorsBusinessLogic(IPortalRepositories portalRepositories, IOptions< page, size, _settings.MaxPageSize, - _portalRepositories.GetInstance().GetManagedConnectorsForCompany(_identityService.IdentityData.CompanyId)); + _portalRepositories.GetInstance().GetManagedConnectorsForCompany(_identityData.CompanyId)); public async Task GetCompanyConnectorData(Guid connectorId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetConnectorByIdForCompany(connectorId, companyId).ConfigureAwait(false); if (result == default) { @@ -104,7 +104,7 @@ public Task CreateManagedConnectorAsync(ManagedConnectorInputModel connect private async Task CreateConnectorInternalAsync(ConnectorInputModel connectorInputModel, CancellationToken cancellationToken) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (name, connectorUrl, location, technicalUserId) = connectorInputModel; await CheckLocationExists(location); @@ -135,7 +135,7 @@ private async Task CreateConnectorInternalAsync(ConnectorInputModel connec private async Task CreateManagedConnectorInternalAsync(ManagedConnectorInputModel connectorInputModel, CancellationToken cancellationToken) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (name, connectorUrl, location, subscriptionId, technicalUserId) = connectorInputModel; await CheckLocationExists(location).ConfigureAwait(false); @@ -252,7 +252,7 @@ await _sdFactoryBusinessLogic /// public async Task DeleteConnectorAsync(Guid connectorId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var connectorsRepository = _portalRepositories.GetInstance(); var result = await connectorsRepository.GetConnectorDeleteDataAsync(connectorId, companyId).ConfigureAwait(false) ?? throw new NotFoundException($"Connector {connectorId} does not exist"); if (!result.IsProvidingOrHostCompany) @@ -369,7 +369,7 @@ public async Task ProcessClearinghouseSelfDescription(SelfDescriptionResponseDat throw new ConflictException($"Connector {data.ExternalId} already has a document assigned"); } - await _sdFactoryBusinessLogic.ProcessFinishSelfDescriptionLpForConnector(data, _identityService.IdentityId, cancellationToken).ConfigureAwait(false); + await _sdFactoryBusinessLogic.ProcessFinishSelfDescriptionLpForConnector(data, _identityData.IdentityId, cancellationToken).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); } @@ -382,11 +382,10 @@ public Task UpdateConnectorUrl(Guid connectorId, ConnectorUpdateRequest data) private async Task UpdateConnectorUrlInternal(Guid connectorId, ConnectorUpdateRequest data) { - var identity = _identityService.IdentityData; var connectorsRepository = _portalRepositories .GetInstance(); var connector = await connectorsRepository - .GetConnectorUpdateInformation(connectorId, identity.CompanyId) + .GetConnectorUpdateInformation(connectorId, _identityData.CompanyId) .ConfigureAwait(false); if (connector == null) @@ -401,7 +400,7 @@ private async Task UpdateConnectorUrlInternal(Guid connectorId, ConnectorUpdateR if (!connector.IsHostCompany) { - throw new ForbiddenException($"Company {identity.CompanyId} is not the connectors host company"); + throw new ForbiddenException($"Company {_identityData.CompanyId} is not the connectors host company"); } if (connector.Status == ConnectorStatusId.INACTIVE) @@ -412,7 +411,7 @@ private async Task UpdateConnectorUrlInternal(Guid connectorId, ConnectorUpdateR var bpn = connector.Type == ConnectorTypeId.CONNECTOR_AS_A_SERVICE ? connector.Bpn : await _portalRepositories.GetInstance() - .GetCompanyBpnForIamUserAsync(identity.UserId) + .GetCompanyBpnForIamUserAsync(_identityData.IdentityId) .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(bpn)) { @@ -430,5 +429,5 @@ private async Task UpdateConnectorUrlInternal(Guid connectorId, ConnectorUpdateR /// public IAsyncEnumerable GetConnectorOfferSubscriptionData(bool? connectorIdSet) => _portalRepositories.GetInstance() - .GetConnectorOfferSubscriptionData(connectorIdSet, _identityService.IdentityData.CompanyId); + .GetConnectorOfferSubscriptionData(connectorIdSet, _identityData.CompanyId); } diff --git a/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs index 2419844c03..e0f7b59cb9 100644 --- a/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs @@ -36,7 +36,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public class DocumentsBusinessLogic : IDocumentsBusinessLogic { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly DocumentSettings _settings; /// @@ -45,7 +45,7 @@ public class DocumentsBusinessLogic : IDocumentsBusinessLogic public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IOptions options) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = options.Value; } @@ -53,7 +53,7 @@ public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IIdentityS public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentAsync(Guid documentId) { var documentDetails = await _portalRepositories.GetInstance() - .GetDocumentDataAndIsCompanyUserAsync(documentId, _identityService.IdentityData.CompanyId) + .GetDocumentDataAndIsCompanyUserAsync(documentId, _identityData.CompanyId) .ConfigureAwait(false); if (documentDetails == default) { @@ -90,7 +90,7 @@ public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IIdentityS public async Task DeleteDocumentAsync(Guid documentId) { var documentRepository = _portalRepositories.GetInstance(); - var details = await documentRepository.GetDocumentDetailsForIdUntrackedAsync(documentId, _identityService.IdentityId).ConfigureAwait(false); + var details = await documentRepository.GetDocumentDetailsForIdUntrackedAsync(documentId, _identityData.IdentityId).ConfigureAwait(false); if (details.DocumentId == Guid.Empty) { diff --git a/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs index a4163be04e..0c715c0795 100644 --- a/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -58,7 +57,6 @@ public interface ISubscriptionConfigurationBusinessLogic /// /// Gets the service provider company details /// - /// Id of the users company /// The detail data Task GetProviderCompanyDetailsAsync(); @@ -66,6 +64,5 @@ public interface ISubscriptionConfigurationBusinessLogic /// Sets service provider company details /// /// Detail data for the service provider - /// Id of the users company Task SetProviderCompanyDetailsAsync(ProviderDetailData data); } diff --git a/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs index fc20062ff8..4e264eaabe 100644 --- a/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional diff --git a/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs index 0ba794393e..cea1132430 100644 --- a/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs @@ -42,7 +42,7 @@ public class IdentityProviderBusinessLogic : IIdentityProviderBusinessLogic { private readonly IPortalRepositories _portalRepositories; private readonly IProvisioningManager _provisioningManager; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IErrorMessageService _errorMessageService; private readonly ILogger _logger; private readonly IdentityProviderSettings _settings; @@ -53,7 +53,7 @@ public IdentityProviderBusinessLogic(IPortalRepositories portalRepositories, IPr { _portalRepositories = portalRepositories; _provisioningManager = provisioningManager; - _identityService = identityService; + _identityData = identityService.IdentityData; _errorMessageService = errorMessageService; _settings = options.Value; _logger = logger; @@ -61,7 +61,7 @@ public IdentityProviderBusinessLogic(IPortalRepositories portalRepositories, IPr public async IAsyncEnumerable GetOwnCompanyIdentityProvidersAsync() { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; await foreach (var identityProviderData in _portalRepositories.GetInstance().GetCompanyIdentityProviderCategoryDataUntracked(companyId).ConfigureAwait(false)) { yield return identityProviderData.CategoryId switch @@ -109,7 +109,7 @@ private static void ValidateDisplayName(string displayName) private async ValueTask CreateOwnCompanyIdentityProviderInternalAsync(IdentityProviderCategoryId identityProviderCategory, IamIdentityProviderProtocol protocol, IdentityProviderTypeId typeId, string? displayName, IEnumerable requiredCompanyRoles) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var identityProviderRepository = _portalRepositories.GetInstance(); var result = await _portalRepositories.GetInstance().CheckCompanyAndCompanyRolesAsync(companyId, requiredCompanyRoles).ConfigureAwait(false); if (!result.IsValidCompany) @@ -153,7 +153,7 @@ public async ValueTask GetOwnCompanyIdentityProviderAsy private async ValueTask<(string Alias, IdentityProviderCategoryId Category, IdentityProviderTypeId TypeId)> ValidateGetOwnCompanyIdentityProviderArguments(Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (alias, category, isOwnOrOwnerCompany, typeId) = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderAliasUntrackedAsync(identityProviderId, companyId).ConfigureAwait(false); if (!isOwnOrOwnerCompany) { @@ -195,7 +195,7 @@ public async ValueTask SetOwnCompanyIdentityProviderSta private async ValueTask<(IdentityProviderCategoryId Category, string Alias, IdentityProviderTypeId TypeId)> ValidateSetOwnCompanyIdentityProviderStatusArguments(Guid identityProviderId, bool enabled) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(identityProviderId, companyId, true).ConfigureAwait(false); if (result == default) { @@ -242,7 +242,7 @@ public async ValueTask UpdateOwnCompanyIdentityProvider private async ValueTask<(IdentityProviderCategoryId Category, string Alias, IdentityProviderTypeId TypeId)> ValidateUpdateOwnCompanyIdentityProviderArguments(Guid identityProviderId, IdentityProviderEditableDetails details) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; ValidateDisplayName(details.displayName); var result = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(identityProviderId, companyId, false).ConfigureAwait(false); @@ -325,7 +325,7 @@ private async ValueTask ValidateOtherActiveIdentityProvider(string? alias, public async ValueTask DeleteCompanyIdentityProviderAsync(Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (alias, typeId) = await ValidateDeleteOwnCompanyIdentityProviderArguments(identityProviderId).ConfigureAwait(false); _portalRepositories.Remove(new CompanyIdentityProvider(companyId, identityProviderId)); @@ -346,7 +346,7 @@ public async ValueTask DeleteCompanyIdentityProviderAsync(Guid identityProviderI private async ValueTask<(string? Alias, IdentityProviderTypeId TypeId)> ValidateDeleteOwnCompanyIdentityProviderArguments(Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(identityProviderId, companyId, true).ConfigureAwait(false); if (result == default) { @@ -476,13 +476,13 @@ private async ValueTask GetIdentityProviderDetailsSaml( public async ValueTask CreateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, UserIdentityProviderLinkData identityProviderLinkData) { - var companyId = _identityService.IdentityData.CompanyId; - var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderLinkData.identityProviderId, companyId).ConfigureAwait(false); + var companyId = _identityData.CompanyId; + var (iamUserId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderLinkData.identityProviderId, companyId).ConfigureAwait(false); try { await _provisioningManager.AddProviderUserLinkToCentralUserAsync( - userEntityId, + iamUserId, new IdentityProviderLink( alias, identityProviderLinkData.userId, @@ -502,19 +502,19 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync( public async ValueTask CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, UserLinkData userLinkData) { - var companyId = _identityService.IdentityData.CompanyId; - var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + var companyId = _identityData.CompanyId; + var (iamUserId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); try { - await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId, alias); + await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, alias); } catch (KeycloakEntityNotFoundException) { // for create-and-update semantics this is expected and not an error } await _provisioningManager.AddProviderUserLinkToCentralUserAsync( - userEntityId, + iamUserId, new IdentityProviderLink( alias, userLinkData.userId, @@ -529,10 +529,10 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync( public async ValueTask GetOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; - var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + var companyId = _identityData.CompanyId; + var (iamUserId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); - var result = await _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId).FirstOrDefaultAsync(identityProviderLink => identityProviderLink.Alias == alias).ConfigureAwait(false); + var result = await _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId).FirstOrDefaultAsync(identityProviderLink => identityProviderLink.Alias == alias).ConfigureAwait(false); if (result == default) { @@ -546,11 +546,11 @@ public async ValueTask GetOwnCompanyUserIdentityPr public async ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid companyUserId, Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; - var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + var companyId = _identityData.CompanyId; + var (iamUserId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); try { - await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId, alias).ConfigureAwait(false); + await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, alias).ConfigureAwait(false); } catch (KeycloakEntityNotFoundException e) { @@ -560,7 +560,7 @@ public async ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid compan public async ValueTask GetOwnIdentityProviderWithConnectedCompanies(Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (alias, category, isOwnerCompany, typeId, connectedCompanies) = await _portalRepositories.GetInstance().GetOwnIdentityProviderWithConnectedCompanies(identityProviderId, companyId).ConfigureAwait(false); if (!isOwnerCompany) @@ -590,7 +590,7 @@ public async ValueTask GetOwnIden public async IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync(IEnumerable identityProviderIds, bool unlinkedUsersOnly) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var identityProviderAliasDatas = await GetOwnCompanyUsersIdentityProviderAliasDataInternalAsync(identityProviderIds, companyId).ConfigureAwait(false); var idPerAlias = identityProviderAliasDatas.ToDictionary(item => item.Alias, item => item.IdentityProviderId); var aliase = identityProviderAliasDatas.Select(item => item.Alias).ToList(); @@ -618,7 +618,7 @@ public async IAsyncEnumerable GetOwnCompanyUsersIdenti public (Stream FileStream, string ContentType, string FileName, Encoding Encoding) GetOwnCompanyUsersIdentityProviderLinkDataStream(IEnumerable identityProviderIds, bool unlinkedUsersOnly) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var csvSettings = _settings.CsvSettings; return (new AsyncEnumerableStringStream(GetOwnCompanyUsersIdentityProviderDataLines(identityProviderIds, unlinkedUsersOnly, companyId), csvSettings.Encoding), csvSettings.ContentType, csvSettings.FileName, csvSettings.Encoding); } @@ -635,7 +635,7 @@ public ValueTask UploadOwnCompanyUsersIdentityProvi private async ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataInternalAsync(IFormFile document, CancellationToken cancellationToken) { var userRepository = _portalRepositories.GetInstance(); - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (sharedIdpAlias, existingAliase) = await GetCompanyAliasDataAsync(companyId).ConfigureAwait(false); using var stream = document.OpenReadStream(); @@ -684,7 +684,7 @@ private UserUpdateError CreateUserUpdateError(int line, Exception error) => var success = false; try { - var (userEntityId, existingProfile, links) = await GetExistingUserAndLinkDataAsync(userRepository, companyUserId, companyId).ConfigureAwait(false); + var (iamUserId, existingProfile, links) = await GetExistingUserAndLinkDataAsync(userRepository, companyUserId, companyId).ConfigureAwait(false); var existingLinks = await links.ToListAsync(cancellationToken).ConfigureAwait(false); var updated = false; @@ -692,12 +692,12 @@ private UserUpdateError CreateUserUpdateError(int line, Exception error) => foreach (var identityProviderLink in identityProviderLinks) { - updated |= await UpdateIdentityProviderLinksAsync(userEntityId, companyUserId, identityProviderLink, existingLinks, sharedIdpAlias).ConfigureAwait(false); + updated |= await UpdateIdentityProviderLinksAsync(iamUserId, companyUserId, identityProviderLink, existingLinks, sharedIdpAlias).ConfigureAwait(false); } if (existingProfile != profile) { - await UpdateUserProfileAsync(userRepository, userEntityId, companyUserId, profile, existingLinks, sharedIdpAlias).ConfigureAwait(false); + await UpdateUserProfileAsync(userRepository, iamUserId, companyUserId, profile, existingLinks, sharedIdpAlias).ConfigureAwait(false); updated = true; } success = updated; @@ -726,23 +726,25 @@ private UserUpdateError CreateUserUpdateError(int line, Exception error) => return (sharedIdpAlias, validAliase); } - private async ValueTask<(string UserEntityId, UserProfile ExistingProfile, IAsyncEnumerable ExistingLinks)> GetExistingUserAndLinkDataAsync(IUserRepository userRepository, Guid companyUserId, Guid companyId) + private async ValueTask<(string IamUserId, UserProfile ExistingProfile, IAsyncEnumerable ExistingLinks)> GetExistingUserAndLinkDataAsync(IUserRepository userRepository, Guid companyUserId, Guid companyId) { var userEntityData = await userRepository.GetUserEntityDataAsync(companyUserId, companyId).ConfigureAwait(false); if (userEntityData == default) { throw new ControllerArgumentException($"unexpected value of {_settings.CsvSettings.HeaderUserId}: '{companyUserId}'"); } - var (userEntityId, existingFirstName, existingLastName, existingEmail) = userEntityData; + var (existingFirstName, existingLastName, existingEmail) = userEntityData; + + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {companyUserId} does not exist in keycloak"); return ( - userEntityId, + iamUserId, new UserProfile(existingFirstName, existingLastName, existingEmail), - _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId) + _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId) ); } - private async ValueTask UpdateIdentityProviderLinksAsync(string userEntityId, Guid companyUserId, IdentityProviderLink identityProviderLink, IEnumerable existingLinks, string? sharedIdpAlias) + private async ValueTask UpdateIdentityProviderLinksAsync(string iamUserId, Guid companyUserId, IdentityProviderLink identityProviderLink, IEnumerable existingLinks, string? sharedIdpAlias) { var (alias, userId, userName) = identityProviderLink; @@ -761,17 +763,17 @@ private async ValueTask UpdateIdentityProviderLinksAsync(string userEntity if (existingLink != null) { - await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId, alias).ConfigureAwait(false); + await _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, alias).ConfigureAwait(false); } - await _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId, identityProviderLink).ConfigureAwait(false); + await _provisioningManager.AddProviderUserLinkToCentralUserAsync(iamUserId, identityProviderLink).ConfigureAwait(false); return true; } - private async ValueTask UpdateUserProfileAsync(IUserRepository userRepository, string userEntityId, Guid companyUserId, UserProfile profile, IEnumerable existingLinks, string? sharedIdpAlias) + private async ValueTask UpdateUserProfileAsync(IUserRepository userRepository, string iamUserId, Guid companyUserId, UserProfile profile, IEnumerable existingLinks, string? sharedIdpAlias) { var (firstName, lastName, email) = (profile.FirstName ?? "", profile.LastName ?? "", profile.Email ?? ""); - await _provisioningManager.UpdateCentralUserAsync(userEntityId, firstName, lastName, email).ConfigureAwait(false); + await _provisioningManager.UpdateCentralUserAsync(iamUserId, firstName, lastName, email).ConfigureAwait(false); if (sharedIdpAlias != null) { @@ -952,50 +954,51 @@ private async IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataLin private async IAsyncEnumerable<(Guid CompanyUserId, UserProfile UserProfile, IAsyncEnumerable LinkDatas)> GetOwnCompanyIdentityProviderLinkDataInternalAsync(Guid companyId) { - await foreach (var (companyUserId, firstName, lastName, email, userEntityId) in _portalRepositories.GetInstance() + await foreach (var (companyUserId, firstName, lastName, email) in _portalRepositories.GetInstance() .GetOwnCompanyUserQuery(companyId) .Select(companyUser => - new ValueTuple( + new ValueTuple( companyUser.Id, companyUser.Firstname, companyUser.Lastname, - companyUser.Email, - companyUser.Identity!.UserEntityId)) + companyUser.Email)) .ToAsyncEnumerable().ConfigureAwait(false)) { - if (userEntityId != null) + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false); + if (iamUserId != null) { yield return ( companyUserId, new UserProfile(firstName, lastName, email), - _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId) + _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId) ); } } } - private async ValueTask<(string UserEntityId, string Alias)> GetUserAliasDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) + private async ValueTask<(string IamUserId, string Alias)> GetUserAliasDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) { - var userAliasData = await _portalRepositories.GetInstance().GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); - if (userAliasData == default) + var (isValidUser, alias, isSameCompany) = await _portalRepositories.GetInstance().GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + if (!isValidUser) { throw new NotFoundException($"companyUserId {companyUserId} does not exist"); } - if (userAliasData.UserEntityId == null) - { - throw new UnexpectedConditionException($"companyUserId {companyUserId} is not linked to keycloak"); - } - if (userAliasData.Alias == null) + if (alias == null) { throw new NotFoundException($"identityProvider {identityProviderId} not found in company of user {companyUserId}"); } - if (!userAliasData.IsSameCompany) + if (!isSameCompany) { throw new ForbiddenException($"identityProvider {identityProviderId} is not associated with company {companyId}"); } + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false); + if (iamUserId == null) + { + throw new UnexpectedConditionException($"companyUserId {companyUserId} is not linked to keycloak"); + } return new ValueTuple( - userAliasData.UserEntityId, - userAliasData.Alias); + iamUserId, + alias); } private sealed record UserProfile(string? FirstName, string? LastName, string? Email); diff --git a/src/administration/Administration.Service/BusinessLogic/NetworkBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/NetworkBusinessLogic.cs index 690370d0e9..8c72599387 100644 --- a/src/administration/Administration.Service/BusinessLogic/NetworkBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/NetworkBusinessLogic.cs @@ -43,7 +43,7 @@ public class NetworkBusinessLogic : INetworkBusinessLogic private static readonly Regex ExternalID = new("^[A-Za-z0-9\\-+_/,.]{6,36}$", RegexOptions.Compiled, TimeSpan.FromSeconds(1)); private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IUserProvisioningService _userProvisioningService; private readonly INetworkRegistrationProcessHelper _processHelper; private readonly PartnerRegistrationSettings _settings; @@ -51,7 +51,7 @@ public class NetworkBusinessLogic : INetworkBusinessLogic public NetworkBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IUserProvisioningService userProvisioningService, INetworkRegistrationProcessHelper processHelper, IOptions options) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _userProvisioningService = userProvisioningService; _processHelper = processHelper; _settings = options.Value; @@ -59,7 +59,7 @@ public NetworkBusinessLogic(IPortalRepositories portalRepositories, IIdentitySer public async Task HandlePartnerRegistration(PartnerRegistrationData data) { - var ownerCompanyId = _identityService.IdentityData.CompanyId; + var ownerCompanyId = _identityData.CompanyId; var networkRepository = _portalRepositories.GetInstance(); var companyRepository = _portalRepositories.GetInstance(); var processStepRepository = _portalRepositories.GetInstance(); diff --git a/src/administration/Administration.Service/BusinessLogic/RegistrationStatusBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/RegistrationStatusBusinessLogic.cs index 9b7a08c925..b2ab0d625f 100644 --- a/src/administration/Administration.Service/BusinessLogic/RegistrationStatusBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/RegistrationStatusBusinessLogic.cs @@ -34,22 +34,22 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public class RegistrationStatusBusinessLogic : IRegistrationStatusBusinessLogic { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly OnboardingServiceProviderSettings _settings; public RegistrationStatusBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IOptions options) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = options.Value; } public Task GetCallbackAddress() => - _portalRepositories.GetInstance().GetCallbackData(_identityService.IdentityData.CompanyId); + _portalRepositories.GetInstance().GetCallbackData(_identityData.CompanyId); public async Task SetCallbackAddress(OnboardingServiceProviderCallbackRequestData requestData) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var companyRepository = _portalRepositories.GetInstance(); var (hasCompanyRole, ospDetails) = await companyRepository .GetCallbackEditData(companyId, CompanyRoleId.ONBOARDING_SERVICE_PROVIDER) diff --git a/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs index b3c0dd22d6..ee7217e2b6 100644 --- a/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -39,7 +38,7 @@ public class ServiceAccountBusinessLogic : IServiceAccountBusinessLogic private readonly IProvisioningManager _provisioningManager; private readonly IPortalRepositories _portalRepositories; private readonly IServiceAccountCreation _serviceAccountCreation; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly ServiceAccountSettings _settings; public ServiceAccountBusinessLogic( @@ -52,7 +51,7 @@ public ServiceAccountBusinessLogic( _provisioningManager = provisioningManager; _portalRepositories = portalRepositories; _serviceAccountCreation = serviceAccountCreation; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = options.Value; } @@ -67,7 +66,7 @@ public async Task CreateOwnCompanyServiceAccountAsync(Ser throw new ControllerArgumentException("name must not be empty", "name"); } - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetBpnAndTechnicalUserRoleIds(companyId, _settings.ClientId).ConfigureAwait(false); if (result == default) { @@ -102,7 +101,7 @@ public async Task CreateOwnCompanyServiceAccountAsync(Ser public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId) { var serviceAccountRepository = _portalRepositories.GetInstance(); - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(serviceAccountId, companyId).ConfigureAwait(false); if (result == default) { @@ -122,9 +121,9 @@ public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId }); // serviceAccount - if (!string.IsNullOrWhiteSpace(result.ClientId)) + if (!string.IsNullOrWhiteSpace(result.ClientClientId)) { - await _provisioningManager.DeleteCentralClientAsync(result.ClientId).ConfigureAwait(false); + await _provisioningManager.DeleteCentralClientAsync(result.ClientClientId).ConfigureAwait(false); } _portalRepositories.GetInstance().DeleteCompanyUserAssignedRoles(result.UserRoleIds.Select(userRoleId => (serviceAccountId, userRoleId))); @@ -147,17 +146,20 @@ public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId public async Task GetOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(serviceAccountId, companyId); if (result == null) { throw new ConflictException($"serviceAccount {serviceAccountId} not found for company {companyId}"); } - if (result.ClientId == null || result.ClientClientId == null) + if (result.ClientClientId == null) { throw new ConflictException($"undefined clientId for serviceAccount {serviceAccountId}"); } - var authData = await _provisioningManager.GetCentralClientAuthDataAsync(result.ClientId).ConfigureAwait(false); + + var internalClientId = await _provisioningManager.GetIdOfCentralClientAsync(result.ClientClientId).ConfigureAwait(false); + + var authData = await _provisioningManager.GetCentralClientAuthDataAsync(internalClientId).ConfigureAwait(false); return new ServiceAccountConnectorOfferData( result.ServiceAccountId, result.ClientClientId, @@ -176,17 +178,17 @@ public async Task GetOwnCompanyServiceAccountD public async Task ResetOwnCompanyServiceAccountSecretAsync(Guid serviceAccountId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(serviceAccountId, companyId); if (result == null) { throw new ConflictException($"serviceAccount {serviceAccountId} not found for company {companyId}"); } - if (result.ClientId == null || result.ClientClientId == null) + if (result.ClientClientId == null) { throw new ConflictException($"undefined clientId for serviceAccount {serviceAccountId}"); } - var authData = await _provisioningManager.ResetCentralClientAuthDataAsync(result.ClientId).ConfigureAwait(false); + var authData = await _provisioningManager.ResetCentralClientAuthDataAsync(result.ClientClientId).ConfigureAwait(false); return new ServiceAccountDetails( result.ServiceAccountId, result.ClientClientId, @@ -210,7 +212,7 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAs throw new ArgumentException($"serviceAccountId {serviceAccountId} from path does not match the one in body {serviceAccountDetails.ServiceAccountId}", nameof(serviceAccountId)); } - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var serviceAccountRepository = _portalRepositories.GetInstance(); var result = await serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(serviceAccountId, companyId).ConfigureAwait(false); if (result == null) @@ -221,23 +223,19 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAs { throw new ConflictException($"serviceAccount {serviceAccountId} is already INACTIVE"); } - if (result.ClientId == null) - { - throw new ConflictException($"clientId of serviceAccount {serviceAccountId} should not be null"); - } if (result.ClientClientId == null) { throw new ConflictException($"clientClientId of serviceAccount {serviceAccountId} should not be null"); } - await _provisioningManager.UpdateCentralClientAsync( - result.ClientId, + var internalClientId = await _provisioningManager.UpdateCentralClientAsync( + result.ClientClientId, new ClientConfigData( serviceAccountDetails.Name, serviceAccountDetails.Description, serviceAccountDetails.IamClientAuthMethod)).ConfigureAwait(false); - var authData = await _provisioningManager.GetCentralClientAuthDataAsync(result.ClientId).ConfigureAwait(false); + var authData = await _provisioningManager.GetCentralClientAuthDataAsync(internalClientId).ConfigureAwait(false); serviceAccountRepository.AttachAndModifyCompanyServiceAccount( serviceAccountId, @@ -271,8 +269,8 @@ await _provisioningManager.UpdateCentralClientAsync( page, size, 15, - _portalRepositories.GetInstance().GetOwnCompanyServiceAccountsUntracked(_identityService.IdentityData.CompanyId, clientId, isOwner, isUserStatusActive ? UserStatusId.ACTIVE : UserStatusId.INACTIVE)); + _portalRepositories.GetInstance().GetOwnCompanyServiceAccountsUntracked(_identityData.CompanyId, clientId, isOwner, isUserStatusActive ? UserStatusId.ACTIVE : UserStatusId.INACTIVE)); public IAsyncEnumerable GetServiceAccountRolesAsync(string? languageShortName) => - _portalRepositories.GetInstance().GetServiceAccountRolesAsync(_identityService.IdentityData.CompanyId, _settings.ClientId, languageShortName ?? Constants.DefaultLanguage); + _portalRepositories.GetInstance().GetServiceAccountRolesAsync(_identityData.CompanyId, _settings.ClientId, languageShortName ?? Constants.DefaultLanguage); } diff --git a/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs index e349e01f19..0f52aa19c0 100644 --- a/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs @@ -34,19 +34,19 @@ public class SubscriptionConfigurationBusinessLogic : ISubscriptionConfiguration { private readonly IOfferSubscriptionProcessService _offerSubscriptionProcessService; private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; public SubscriptionConfigurationBusinessLogic(IOfferSubscriptionProcessService offerSubscriptionProcessService, IPortalRepositories portalRepositories, IIdentityService identityService) { _offerSubscriptionProcessService = offerSubscriptionProcessService; _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; } /// public async Task GetProviderCompanyDetailsAsync() { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance() .GetProviderCompanyDetailAsync(CompanyRoleId.SERVICE_PROVIDER, companyId) .ConfigureAwait(false); @@ -74,7 +74,7 @@ public Task SetProviderCompanyDetailsAsync(ProviderDetailData data) "the maximum allowed length is 100 characters", nameof(data.Url)); } - return SetOfferProviderCompanyDetailsInternalAsync(data, _identityService.IdentityData.CompanyId); + return SetOfferProviderCompanyDetailsInternalAsync(data, _identityData.CompanyId); } private async Task SetOfferProviderCompanyDetailsInternalAsync(ProviderDetailData data, Guid companyId) diff --git a/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs index c75357046f..ca36ccdf4e 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -45,7 +44,7 @@ public class UserBusinessLogic : IUserBusinessLogic private readonly IUserProvisioningService _userProvisioningService; private readonly IProvisioningDBAccess _provisioningDbAccess; private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IMailingService _mailingService; private readonly ILogger _logger; private readonly UserSettings _settings; @@ -75,7 +74,7 @@ public UserBusinessLogic( _userProvisioningService = userProvisioningService; _provisioningDbAccess = provisioningDbAccess; _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _mailingService = mailingService; _logger = logger; _settings = settings.Value; @@ -98,7 +97,7 @@ public IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable CreateOwnCompanyUsersInternalAsync(IEnumerable userList) { - var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identityService.IdentityId).ConfigureAwait(false); + var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identityData.IdentityId).ConfigureAwait(false); var distinctRoles = userList.SelectMany(user => user.Roles).Distinct().ToList(); @@ -161,12 +160,12 @@ private Task> GetOwnCompanyUserRoleData(IEnumerable()); } - return _userProvisioningService.GetOwnCompanyPortalRoleDatas(_settings.Portal.KeycloakClientID, roles, _identityService.IdentityData.CompanyId); + return _userProvisioningService.GetOwnCompanyPortalRoleDatas(_settings.Portal.KeycloakClientID, roles, _identityData.CompanyId); } public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, UserCreationInfoIdp userCreationInfo) { - var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, _identityService.IdentityId).ConfigureAwait(false); + var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, _identityData.IdentityId).ConfigureAwait(false); var displayName = await _userProvisioningService.GetIdentityProviderDisplayName(companyNameIdpAliasData.IdpAlias).ConfigureAwait(false); if (!userCreationInfo.Roles.Any()) @@ -227,9 +226,8 @@ public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, Us public Task> GetOwnCompanyUserDatasAsync(int page, int size, GetOwnCompanyUsersFilter filter) { var companyUsers = _portalRepositories.GetInstance().GetOwnCompanyUserQuery( - _identityService.IdentityData.CompanyId, + _identityData.CompanyId, filter.CompanyUserId, - filter.UserEntityId, filter.FirstName, filter.LastName, filter.Email, @@ -245,7 +243,6 @@ public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, Us .Skip(skip) .Take(take) .Select(companyUser => new CompanyUserData( - companyUser.Identity!.UserEntityId!, companyUser.Id, companyUser.Identity!.UserStatusId, companyUser.Identity!.IdentityAssignedRoles.Select(x => x.UserRole!).Select(userRole => userRole.UserRoleText)) @@ -279,7 +276,7 @@ public async IAsyncEnumerable GetClientRolesAsync(Guid appId, strin public async Task GetOwnCompanyUserDetailsAsync(Guid userId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var details = await _portalRepositories.GetInstance().GetOwnCompanyUserDetailsUntrackedAsync(userId, companyId).ConfigureAwait(false); if (details == null) { @@ -294,16 +291,16 @@ public async Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId { throw new ControllerArgumentException("businessPartnerNumbers must not exceed 20 characters", nameof(businessPartnerNumbers)); } - var companyId = _identityService.IdentityData.CompanyId; - var user = await _portalRepositories.GetInstance().GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(userId, companyId).ConfigureAwait(false); - if (user == null || user.UserEntityId == null) + var companyId = _identityData.CompanyId; + var (assignedBusinessPartnerNumbers, isValidUser) = await _portalRepositories.GetInstance().GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(userId, companyId).ConfigureAwait(false); + if (!isValidUser) { throw new NotFoundException($"user {userId} not found in company {companyId}"); } - + var iamUserId = await _provisioningManager.GetUserByUserName(userId.ToString()).ConfigureAwait(false) ?? throw new ConflictException("user {userId} not found in keycloak"); var businessPartnerRepository = _portalRepositories.GetInstance(); - await _provisioningManager.AddBpnAttributetoUserAsync(user.UserEntityId, businessPartnerNumbers).ConfigureAwait(false); - foreach (var businessPartnerToAdd in businessPartnerNumbers.Except(user.AssignedBusinessPartnerNumbers)) + await _provisioningManager.AddBpnAttributetoUserAsync(iamUserId, businessPartnerNumbers).ConfigureAwait(false); + foreach (var businessPartnerToAdd in businessPartnerNumbers.Except(assignedBusinessPartnerNumbers)) { businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(userId, businessPartnerToAdd); } @@ -316,7 +313,7 @@ public Task AddOwnCompanyUsersBusinessPartnerNumberAsync(Guid userId, strin public async Task GetOwnUserDetails() { - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; var userRoleIds = await _portalRepositories.GetInstance() .GetUserRoleIdsUntrackedAsync(_settings.UserAdminRoles).ToListAsync().ConfigureAwait(false); var details = await _portalRepositories.GetInstance().GetUserDetailsUntrackedAsync(userId, userRoleIds).ConfigureAwait(false); @@ -329,7 +326,7 @@ public async Task GetOwnUserDetails() public async Task UpdateOwnUserDetails(Guid companyUserId, OwnCompanyUserEditableDetails ownCompanyUserEditableDetails) { - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; if (companyUserId != userId) { throw new ForbiddenException($"invalid userId {companyUserId} for user {userId}"); @@ -341,16 +338,13 @@ public async Task UpdateOwnUserDetails(Guid companyUserId, O throw new ArgumentOutOfRangeException($"user {companyUserId} is not a shared idp user"); } var companyUser = userData.CompanyUser; - if (string.IsNullOrWhiteSpace(companyUser.UserEntityId)) - { - throw new ForbiddenException("UserEntityId must be set."); - } + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {companyUserId} not found in keycloak"); var iamIdpAlias = userData.IamIdpAlias; - var userIdShared = await _provisioningManager.GetProviderUserIdForCentralUserIdAsync(iamIdpAlias, companyUser.UserEntityId).ConfigureAwait(false); + var userIdShared = await _provisioningManager.GetProviderUserIdForCentralUserIdAsync(iamIdpAlias, iamUserId).ConfigureAwait(false); if (userIdShared == null) { - throw new NotFoundException($"no shared realm userid found for {companyUser.UserEntityId} in realm {iamIdpAlias}"); + throw new NotFoundException($"no shared realm userid found for {iamUserId} in realm {iamIdpAlias}"); } await _provisioningManager.UpdateSharedRealmUserAsync( iamIdpAlias, @@ -388,7 +382,7 @@ await _provisioningManager.UpdateSharedRealmUserAsync( public async Task DeleteOwnUserAsync(Guid companyUserId) { - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; if (companyUserId != userId) { throw new ForbiddenException($"companyUser {companyUserId} is not the id of user {userId}"); @@ -405,7 +399,7 @@ public async Task DeleteOwnUserAsync(Guid companyUserId) public async IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable userIds) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var iamIdpAlias = await _portalRepositories.GetInstance().GetSharedIdentityProviderIamAliasDataUntrackedAsync(companyId); await foreach (var accountData in _portalRepositories.GetInstance().GetCompanyUserAccountDataUntrackedAsync(userIds, companyId).ConfigureAwait(false)) @@ -437,46 +431,45 @@ public async IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable private async Task DeleteUserInternalAsync(string? sharedIdpAlias, CompanyUserAccountData accountData) { - var (userId, userEntityId, businessPartnerNumbers, roleIds, offerIds, invitationIds) = accountData; - if (userEntityId != null) + var (companyUserId, businessPartnerNumbers, roleIds, offerIds, invitationIds) = accountData; + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false); + if (iamUserId != null) { - await DeleteIamUserAsync(sharedIdpAlias, userEntityId).ConfigureAwait(false); + await DeleteIamUserAsync(sharedIdpAlias, iamUserId).ConfigureAwait(false); } - _portalRepositories.GetInstance().AttachAndModifyIdentity(userId, i => - { - i.UserEntityId = userEntityId; - }, + _portalRepositories.GetInstance().AttachAndModifyIdentity( + companyUserId, + null, i => { i.UserStatusId = UserStatusId.DELETED; - i.UserEntityId = null; }); _portalRepositories.GetInstance() - .DeleteCompanyUserAssignedBusinessPartners(businessPartnerNumbers.Select(bpn => (userId, bpn))); + .DeleteCompanyUserAssignedBusinessPartners(businessPartnerNumbers.Select(bpn => (companyUserId, bpn))); _portalRepositories.GetInstance() - .DeleteAppFavourites(offerIds.Select(offerId => (offerId, userId))); + .DeleteAppFavourites(offerIds.Select(offerId => (offerId, companyUserId))); _portalRepositories.GetInstance() - .DeleteCompanyUserAssignedRoles(roleIds.Select(userRoleId => (userId, userRoleId))); + .DeleteCompanyUserAssignedRoles(roleIds.Select(userRoleId => (companyUserId, userRoleId))); _portalRepositories.GetInstance() .DeleteInvitations(invitationIds); } - private async Task DeleteIamUserAsync(string? sharedIdpAlias, string userEntityId) + private async Task DeleteIamUserAsync(string? sharedIdpAlias, string iamUserId) { if (sharedIdpAlias != null) { - var userIdShared = await _provisioningManager.GetProviderUserIdForCentralUserIdAsync(sharedIdpAlias, userEntityId).ConfigureAwait(false); + var userIdShared = await _provisioningManager.GetProviderUserIdForCentralUserIdAsync(sharedIdpAlias, iamUserId).ConfigureAwait(false); if (userIdShared != null) { await _provisioningManager.DeleteSharedRealmUserAsync(sharedIdpAlias, userIdShared).ConfigureAwait(false); } } - await _provisioningManager.DeleteCentralRealmUserAsync(userEntityId).ConfigureAwait(false); + await _provisioningManager.DeleteCentralRealmUserAsync(iamUserId).ConfigureAwait(false); } private async Task CanResetPassword(Guid userId) @@ -507,18 +500,18 @@ private async Task CanResetPassword(Guid userId) public async Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId) { - var identity = _identityService.IdentityData; - var idpUserName = await _portalRepositories.GetInstance().GetIdpCategoryIdByUserIdAsync(companyUserId, identity.CompanyId).ConfigureAwait(false); - if (idpUserName != null && !string.IsNullOrWhiteSpace(idpUserName.TargetIamUserId) && !string.IsNullOrWhiteSpace(idpUserName.IdpName)) + var (alias, isValidUser) = await _portalRepositories.GetInstance().GetIdpCategoryIdByUserIdAsync(companyUserId, _identityData.CompanyId).ConfigureAwait(false); + if (isValidUser && !string.IsNullOrWhiteSpace(alias)) { - if (await CanResetPassword(identity.UserId).ConfigureAwait(false)) + if (await CanResetPassword(_identityData.IdentityId).ConfigureAwait(false)) { - await _provisioningManager.ResetSharedUserPasswordAsync(idpUserName.IdpName, idpUserName.TargetIamUserId).ConfigureAwait(false); + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {companyUserId} not found in keycloak"); + await _provisioningManager.ResetSharedUserPasswordAsync(alias, iamUserId).ConfigureAwait(false); return true; } throw new ArgumentException($"cannot reset password more often than {_settings.PasswordReset.MaxNoOfReset} in {_settings.PasswordReset.NoOfHours} hours"); } - throw new NotFoundException($"Cannot identify companyId or shared idp : userId {companyUserId} is not associated with admin users company {identity.CompanyId}"); + throw new NotFoundException($"Cannot identify companyId or shared idp : userId {companyUserId} is not associated with admin users company {_identityData.CompanyId}"); } public Task> GetOwnCompanyAppUsersAsync(Guid appId, int page, int size, CompanyUserFilter filter) => @@ -528,41 +521,37 @@ public async Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId) 15, _portalRepositories.GetInstance().GetOwnCompanyAppUsersPaginationSourceAsync( appId, - _identityService.IdentityId, + _identityData.IdentityId, new[] { OfferSubscriptionStatusId.ACTIVE }, new[] { UserStatusId.ACTIVE, UserStatusId.INACTIVE }, filter)); public async Task DeleteOwnUserBusinessPartnerNumbersAsync(Guid userId, string businessPartnerNumber) { - var identity = _identityService.IdentityData; var userBusinessPartnerRepository = _portalRepositories.GetInstance(); - var userWithBpn = await userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(userId, identity.CompanyId, businessPartnerNumber).ConfigureAwait(false); + var (isValidUser, isAssignedBusinessPartner, isSameCompany) = await userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(userId, _identityData.CompanyId, businessPartnerNumber).ConfigureAwait(false); - if (userWithBpn == default) + if (!isValidUser) { throw new NotFoundException($"user {userId} does not exist"); } - if (!userWithBpn.IsAssignedBusinessPartner) + if (!isAssignedBusinessPartner) { throw new ForbiddenException($"businessPartnerNumber {businessPartnerNumber} is not assigned to user {userId}"); } - if (userWithBpn.UserEntityId == null) + if (!isSameCompany) { - throw new ConflictException($"user {userId} is not associated with a user in keycloak"); + throw new ForbiddenException($"userId {userId} and adminUserId {_identityData.IdentityId} do not belong to same company"); } - if (!userWithBpn.IsValidUser) - { - throw new ForbiddenException($"userId {userId} and adminUserId {identity.UserId} do not belong to same company"); - } + var iamUserId = await _provisioningManager.GetUserByUserName(userId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {userId} is not associated with a user in keycloak"); userBusinessPartnerRepository.DeleteCompanyUserAssignedBusinessPartner(userId, businessPartnerNumber); - await _provisioningManager.DeleteCentralUserBusinessPartnerNumberAsync(userWithBpn.UserEntityId, businessPartnerNumber).ConfigureAwait(false); + await _provisioningManager.DeleteCentralUserBusinessPartnerNumberAsync(iamUserId, businessPartnerNumber).ConfigureAwait(false); return await _portalRepositories.SaveAsync().ConfigureAwait(false); } diff --git a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs index adcf428727..dcb94da6bc 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -39,29 +38,29 @@ public class UserRolesBusinessLogic : IUserRolesBusinessLogic private static readonly JsonSerializerOptions _options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; private readonly IPortalRepositories _portalRepositories; private readonly IProvisioningManager _provisioningManager; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly UserSettings _settings; public UserRolesBusinessLogic(IPortalRepositories portalRepositories, IProvisioningManager provisioningManager, IIdentityService identityService, IOptions options) { _portalRepositories = portalRepositories; _provisioningManager = provisioningManager; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = options.Value; } public IAsyncEnumerable GetCoreOfferRoles(string? languageShortName) => - _portalRepositories.GetInstance().GetCoreOfferRolesAsync(_identityService.IdentityData.CompanyId, languageShortName ?? Constants.DefaultLanguage, _settings.Portal.KeycloakClientID) + _portalRepositories.GetInstance().GetCoreOfferRolesAsync(_identityData.CompanyId, languageShortName ?? Constants.DefaultLanguage, _settings.Portal.KeycloakClientID) .PreSortedGroupBy(x => x.OfferId) .Select(x => new OfferRoleInfos(x.Key, x.Select(s => new OfferRoleInfo(s.RoleId, s.RoleText, s.Description)))); public IAsyncEnumerable GetAppRolesAsync(Guid appId, string? languageShortName) => _portalRepositories.GetInstance() - .GetAppRolesAsync(appId, _identityService.IdentityData.CompanyId, languageShortName ?? Constants.DefaultLanguage); + .GetAppRolesAsync(appId, _identityData.CompanyId, languageShortName ?? Constants.DefaultLanguage); public Task> ModifyCoreOfferUserRolesAsync(Guid offerId, Guid companyUserId, IEnumerable roles) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; return ModifyUserRolesInternal( async () => { @@ -72,7 +71,6 @@ public Task> ModifyCoreOfferUserRolesAsync(Guid offe : new OfferIamUserData( result.IsValidOffer, result.IamClientIds, - result.IamUserId, result.IsSameCompany, "Portal", result.Firstname, @@ -99,10 +97,10 @@ public Task> ModifyCoreOfferUserRolesAsync(Guid offe public Task> ModifyAppUserRolesAsync(Guid appId, Guid companyUserId, IEnumerable roles) => ModifyUserRolesInternal( () => _portalRepositories.GetInstance() - .GetAppAssignedIamClientUserDataUntrackedAsync(appId, companyUserId, _identityService.IdentityData.CompanyId), + .GetAppAssignedIamClientUserDataUntrackedAsync(appId, companyUserId, _identityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), - appId, companyUserId, roles, _identityService.IdentityData.CompanyId, + appId, companyUserId, roles, _identityData.CompanyId, data => { var userName = $"{data.firstname} {data.lastname}"; @@ -120,10 +118,10 @@ public Task> ModifyAppUserRolesAsync(Guid appId, Gui public Task> ModifyUserRoleAsync(Guid appId, UserRoleInfo userRoleInfo) => ModifyUserRolesInternal( () => _portalRepositories.GetInstance() - .GetAppAssignedIamClientUserDataUntrackedAsync(appId, userRoleInfo.CompanyUserId, _identityService.IdentityData.CompanyId), + .GetAppAssignedIamClientUserDataUntrackedAsync(appId, userRoleInfo.CompanyUserId, _identityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), - appId, userRoleInfo.CompanyUserId, userRoleInfo.Roles, _identityService.IdentityData.CompanyId, null); + appId, userRoleInfo.CompanyUserId, userRoleInfo.Roles, _identityData.CompanyId, null); private async Task> ModifyUserRolesInternal( Func> getIamUserData, @@ -132,9 +130,9 @@ private async Task> ModifyUserRolesInternal( Func<(Guid offerId, string offerName, string? firstname, string? lastname, IEnumerable removedRoles, IEnumerable addedRoles), (string content, NotificationTypeId notificationTypeId)>? getNotificationData) { var result = await getIamUserData().ConfigureAwait(false); - if (result == default || string.IsNullOrWhiteSpace(result.IamUserId)) + if (result == default) { - throw new NotFoundException($"iamUserId for user {companyUserId} not found"); + throw new NotFoundException($"user {companyUserId} not found"); } if (!result.IsSameCompany) @@ -153,16 +151,13 @@ private async Task> ModifyUserRolesInternal( throw new ConflictException($"offerId {offerId} is not associated with any keycloak-client"); } - if (result.IamUserId == null) - { - throw new ConflictException($"user {companyUserId} is not associated with any iamUser"); - } - if (string.IsNullOrWhiteSpace(result.OfferName)) { throw new ConflictException("OfferName must be set here."); } + var iamUserId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {companyUserId} is not associated with any iamUser"); + var distinctRoles = roles.Where(role => !string.IsNullOrWhiteSpace(role)).Distinct().ToList(); var existingRoles = await getUserRoleModificationData(companyUserId, distinctRoles, offerId).ToListAsync().ConfigureAwait(false); var nonExistingRoles = distinctRoles.Except(existingRoles.Select(r => r.CompanyUserRoleText)); @@ -174,12 +169,12 @@ private async Task> ModifyUserRolesInternal( var rolesToDelete = existingRoles.Where(x => x.IsAssignedToUser).ExceptBy(distinctRoles, role => role.CompanyUserRoleText); var rolesNotAdded = rolesToAdd.Any() - ? rolesToAdd.Except(await AddRoles(companyUserId, result.IamClientIds, rolesToAdd, result.IamUserId).ConfigureAwait(false)) + ? rolesToAdd.Except(await AddRoles(companyUserId, result.IamClientIds, rolesToAdd, iamUserId).ConfigureAwait(false)) : Enumerable.Empty(); if (rolesToDelete.Any()) { - await DeleteRoles(companyUserId, result.IamClientIds, rolesToDelete, result.IamUserId).ConfigureAwait(false); + await DeleteRoles(companyUserId, result.IamClientIds, rolesToDelete, iamUserId).ConfigureAwait(false); } if (getNotificationData != null) diff --git a/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs index f848a3541e..b4eef9e86a 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs @@ -38,7 +38,7 @@ public class UserUploadBusinessLogic : IUserUploadBusinessLogic private readonly IUserProvisioningService _userProvisioningService; private readonly IMailingService _mailingService; private readonly UserSettings _settings; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IErrorMessageService _errorMessageService; /// @@ -58,7 +58,7 @@ public UserUploadBusinessLogic( { _userProvisioningService = userProvisioningService; _mailingService = mailingService; - _identityService = identityService; + _identityData = identityService.IdentityData; _errorMessageService = errorMessageService; _settings = settings.Value; } @@ -73,8 +73,7 @@ private async ValueTask UploadOwnCompanyIdpUsersInternalAsync { using var stream = document.OpenReadStream(); - var identity = _identityService.IdentityData; - var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, identity.UserId).ConfigureAwait(false); + var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, _identityData.IdentityId).ConfigureAwait(false); var validRoleData = new List(); @@ -93,7 +92,7 @@ private async ValueTask UploadOwnCompanyIdpUsersInternalAsync parsed.FirstName, parsed.LastName, parsed.Email, - await GetUserRoleDatas(parsed.Roles, validRoleData, identity.CompanyId).ConfigureAwait(false), + await GetUserRoleDatas(parsed.Roles, validRoleData, _identityData.CompanyId).ConfigureAwait(false), parsed.ProviderUserName, parsed.ProviderUserId, UserStatusId.ACTIVE, @@ -207,8 +206,7 @@ private async ValueTask UploadOwnCompanySharedIdpUsersInterna { using var stream = document.OpenReadStream(); - var identity = _identityService.IdentityData; - var (companyNameIdpAliasData, _) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(identity.UserId).ConfigureAwait(false); + var (companyNameIdpAliasData, _) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identityData.IdentityId).ConfigureAwait(false); var validRoleData = new List(); @@ -227,7 +225,7 @@ private async ValueTask UploadOwnCompanySharedIdpUsersInterna parsed.FirstName, parsed.LastName, parsed.Email, - await GetUserRoleDatas(parsed.Roles, validRoleData, identity.CompanyId).ConfigureAwait(false), + await GetUserRoleDatas(parsed.Roles, validRoleData, _identityData.CompanyId).ConfigureAwait(false), parsed.Email, "", UserStatusId.ACTIVE, diff --git a/src/administration/Administration.Service/Controllers/UserController.cs b/src/administration/Administration.Service/Controllers/UserController.cs index a300ead217..3bfdbec02f 100644 --- a/src/administration/Administration.Service/Controllers/UserController.cs +++ b/src/administration/Administration.Service/Controllers/UserController.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -160,14 +159,13 @@ public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsy /// /// page index start from 0 /// size to get number of records - /// User Entity Id /// Company User Id /// First Name of User /// Last Name of User /// Email Id of User /// Paginated Result of Company User Data /// Example: GET: api/administration/user/owncompany/users?page=0&size=5 - /// Example: GET: api/administration/user/owncompany/users?page=0&size=5&userEntityId="31404026-64ee-4023-a122-3c7fc40e57b1" + /// Example: GET: api/administration/user/owncompany/users?page=0&size=5&companyUserId="31404026-64ee-4023-a122-3c7fc40e57b1" /// Result as a Company User Data [HttpGet] [Authorize(Roles = "view_user_management")] @@ -177,7 +175,6 @@ public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsy public Task> GetOwnCompanyUserDatasAsync( [FromQuery] int page, [FromQuery] int size, - [FromQuery] string? userEntityId = null, [FromQuery] Guid? companyUserId = null, [FromQuery] string? firstName = null, [FromQuery] string? lastName = null, @@ -185,7 +182,7 @@ public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsy _logic.GetOwnCompanyUserDatasAsync( page, size, - new(companyUserId, userEntityId, firstName, lastName, email)); + new(companyUserId, firstName, lastName, email)); /// /// Gets the user details for the given user Id diff --git a/src/administration/Administration.Service/Models/GetOwnCompanyUsersFilter.cs b/src/administration/Administration.Service/Models/GetOwnCompanyUsersFilter.cs index 57e5f66611..5760e1ee11 100644 --- a/src/administration/Administration.Service/Models/GetOwnCompanyUsersFilter.cs +++ b/src/administration/Administration.Service/Models/GetOwnCompanyUsersFilter.cs @@ -22,7 +22,6 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Models; public record GetOwnCompanyUsersFilter( Guid? CompanyUserId, - string? UserEntityId, string? FirstName, string? LastName, string? Email diff --git a/src/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogic.cs b/src/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogic.cs index 87d9f3ed28..b4eeab078d 100644 --- a/src/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogic.cs +++ b/src/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogic.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -125,12 +124,12 @@ await _offerProviderService if (data.ServiceAccounts.Count() == 1) { var serviceAccount = data.ServiceAccounts.FirstOrDefault(); - if (serviceAccount != default && serviceAccount.TechnicalClientId == null) + if (serviceAccount.TechnicalClientId == null) { throw new ConflictException($"ClientId of serviceAccount {serviceAccount.TechnicalUserId} should be set"); } - - var authData = await _provisioningManager.GetCentralClientAuthDataAsync(serviceAccount.TechnicalClientId).ConfigureAwait(false); + var internalClientId = await _provisioningManager.GetIdOfCentralClientAsync(serviceAccount.TechnicalClientId).ConfigureAwait(false); + var authData = await _provisioningManager.GetCentralClientAuthDataAsync(internalClientId).ConfigureAwait(false); technicalUserInfoData = new CallbackTechnicalUserInfoData( serviceAccount.TechnicalUserId, authData.Secret, diff --git a/src/framework/Framework.Models/PortalClaimTypes.cs b/src/framework/Framework.Models/PortalClaimTypes.cs index 359b262c3d..a27cc9bcd0 100644 --- a/src/framework/Framework.Models/PortalClaimTypes.cs +++ b/src/framework/Framework.Models/PortalClaimTypes.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -22,11 +21,8 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Models; public static class PortalClaimTypes { - private const string Base = "https://catena-x.net//schema/2023/05/identity/claims"; public const string Sub = "sub"; + public const string ClientId = "clientId"; public const string PreferredUserName = "preferred_username"; public const string ResourceAccess = "resource_access"; - public const string CompanyId = $"{Base}/company_id"; - public const string IdentityId = $"{Base}/identity_id"; - public const string IdentityType = $"{Base}/identity_type"; } diff --git a/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentityServiceCollectionExtensions.cs b/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentityServiceCollectionExtensions.cs index a57992518a..d128f70538 100644 --- a/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentityServiceCollectionExtensions.cs +++ b/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentityServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -20,31 +19,32 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Identities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.DependencyInjection; public static class ProcessIdentityServiceCollectionExtensions { - public static IServiceCollection AddConfigurationIdentityIdDetermination(this IServiceCollection services, IConfigurationSection section) + public static IServiceCollection AddConfigurationProcessIdentityIdDetermination(this IServiceCollection services, IConfigurationSection section) { services.AddOptions() .Bind(section) .ValidateOnStart(); return services - .AddTransient(); + .AddTransient() + .AddTransient(); } - public static IServiceCollection AddConfigurationIdentityService(this IServiceCollection services, IConfigurationSection section) + public static IServiceCollection AddConfigurationProcessIdentityService(this IServiceCollection services, IConfigurationSection section) { services.AddOptions() .Bind(section) .ValidateOnStart(); return services - .AddScoped() - .AddScoped(); + .AddScoped() + .AddTransient() + .AddTransient(); } } diff --git a/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentitySettings.cs b/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentitySettings.cs index 2f986a16d5..7516d83a90 100644 --- a/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentitySettings.cs +++ b/src/framework/Framework.ProcessIdentity/DependencyInjection/ProcessIdentitySettings.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/InvitedUserDetail.cs b/src/framework/Framework.ProcessIdentity/IProcessIdentityDataBuilder.cs similarity index 77% rename from src/portalbackend/PortalBackend.DBAccess/Models/InvitedUserDetail.cs rename to src/framework/Framework.ProcessIdentity/IProcessIdentityDataBuilder.cs index d5d4330ac4..938e27c4b7 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/InvitedUserDetail.cs +++ b/src/framework/Framework.ProcessIdentity/IProcessIdentityDataBuilder.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -19,7 +18,11 @@ ********************************************************************************/ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; -public record InvitedUserDetail(string? UserId, InvitationStatusId InvitationStatus, string? EmailId); +public interface IProcessIdentityDataBuilder : IIdentityData +{ + void AddIdentityData(IdentityTypeId identityType, Guid companyId); +} diff --git a/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityIdDetermination.cs b/src/framework/Framework.ProcessIdentity/IProcessIdentityDataDetermination.cs similarity index 83% rename from src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityIdDetermination.cs rename to src/framework/Framework.ProcessIdentity/IProcessIdentityDataDetermination.cs index 48841b974a..48fa2dc296 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityIdDetermination.cs +++ b/src/framework/Framework.ProcessIdentity/IProcessIdentityDataDetermination.cs @@ -17,12 +17,12 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; -public interface IIdentityIdDetermination +public interface IProcessIdentityDataDetermination { /// - /// Access to the identity Id + /// Initialize IdentityData /// - Guid IdentityId { get; } + public Task GetIdentityData(); } diff --git a/src/framework/Framework.ProcessIdentity/ProcessIdentityDataBuilder.cs b/src/framework/Framework.ProcessIdentity/ProcessIdentityDataBuilder.cs new file mode 100644 index 0000000000..1a68ef5bb1 --- /dev/null +++ b/src/framework/Framework.ProcessIdentity/ProcessIdentityDataBuilder.cs @@ -0,0 +1,50 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.DependencyInjection; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; + +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; + +public class ProcessIdentityDataBuilder : IProcessIdentityDataBuilder +{ + private readonly ProcessIdentitySettings _settings; + private IdentityTypeId? _identityTypeId; + private Guid? _companyId; + + public ProcessIdentityDataBuilder(IOptions options) + { + _settings = options.Value; + } + + public void AddIdentityData(IdentityTypeId identityType, Guid companyId) + { + _identityTypeId = identityType; + _companyId = companyId; + } + + public Guid IdentityId => _settings.ProcessUserId; + + public IdentityTypeId IdentityTypeId => _identityTypeId ?? throw new UnexpectedConditionException("identityType should never be null here (GetIdentityData must be called before)"); + + public Guid CompanyId => _companyId ?? throw new UnexpectedConditionException("companyId should never be null here (GetIdentityData must be called before)"); + +} diff --git a/src/portalbackend/PortalBackend.DBAccess/Identities/IdentityService.cs b/src/framework/Framework.ProcessIdentity/ProcessIdentityDataDetermination.cs similarity index 54% rename from src/portalbackend/PortalBackend.DBAccess/Identities/IdentityService.cs rename to src/framework/Framework.ProcessIdentity/ProcessIdentityDataDetermination.cs index 3ac25a1dab..38191ae5af 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Identities/IdentityService.cs +++ b/src/framework/Framework.ProcessIdentity/ProcessIdentityDataDetermination.cs @@ -18,30 +18,31 @@ ********************************************************************************/ using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Identities; +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; -public class IdentityService : IIdentityService +public class ProcessIdentityDataDetermination : IProcessIdentityDataDetermination { private readonly IIdentityRepository _identityRepository; - private readonly IIdentityIdDetermination _identityIdDetermination; - private IdentityData? _identityData; + private readonly IProcessIdentityDataBuilder _processIdentityDataBuilder; - public IdentityService(IPortalRepositories portalRepositories, IIdentityIdDetermination identityIdDetermination) + public ProcessIdentityDataDetermination(IPortalRepositories portalRepositories, IProcessIdentityDataBuilder processIdentityDataBuilder) { _identityRepository = portalRepositories.GetInstance(); - _identityIdDetermination = identityIdDetermination; + _processIdentityDataBuilder = processIdentityDataBuilder; } /// - public async ValueTask GetIdentityData() => - _identityData ?? (_identityData = - await _identityRepository.GetActiveIdentityDataByIdentityId(IdentityId).ConfigureAwait(false) ?? - throw new ConflictException($"Identity {_identityIdDetermination.IdentityId} could not be found")); + public async Task GetIdentityData() + { + (IdentityTypeId IdentityTypeId, Guid CompanyId) identityData; - public IdentityData IdentityData => _identityData ?? throw new UnexpectedConditionException("identityData should never be null here (endpoint must be annotated with an identity policy / as an alternative GetIdentityData should be used)"); + if ((identityData = await _identityRepository.GetActiveIdentityDataByIdentityId(_processIdentityDataBuilder.IdentityId).ConfigureAwait(false)) == default) + throw new ConflictException($"Identity {_processIdentityDataBuilder.IdentityId} could not be found"); - public Guid IdentityId => _identityIdDetermination.IdentityId; + _processIdentityDataBuilder.AddIdentityData(identityData.IdentityTypeId, identityData.CompanyId); + } } diff --git a/src/framework/Framework.ProcessIdentity/ConfigurationIdentityIdDetermination.cs b/src/framework/Framework.ProcessIdentity/ProcessIdentityService.cs similarity index 71% rename from src/framework/Framework.ProcessIdentity/ConfigurationIdentityIdDetermination.cs rename to src/framework/Framework.ProcessIdentity/ProcessIdentityService.cs index 1c2271240e..f2a4c0a210 100644 --- a/src/framework/Framework.ProcessIdentity/ConfigurationIdentityIdDetermination.cs +++ b/src/framework/Framework.ProcessIdentity/ProcessIdentityService.cs @@ -17,20 +17,17 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Microsoft.Extensions.Options; -using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.DependencyInjection; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; -public class ConfigurationIdentityIdDetermination : IIdentityIdDetermination +public class ProcessIdentityService : IIdentityService { - private readonly ProcessIdentitySettings _settings; - - public ConfigurationIdentityIdDetermination(IOptions options) + private readonly IIdentityData _identityData; + public ProcessIdentityService(IProcessIdentityDataBuilder processIdentityDataBuilder) { - _settings = options.Value; + _identityData = processIdentityDataBuilder; } - public Guid IdentityId => _settings.ProcessUserId; + public IIdentityData IdentityData => _identityData; } diff --git a/src/framework/Framework.PublicInfos/Framework.PublicInfos.csproj b/src/framework/Framework.PublicInfos/Framework.PublicInfos.csproj index e9509ca3c5..2c7a3e8040 100644 --- a/src/framework/Framework.PublicInfos/Framework.PublicInfos.csproj +++ b/src/framework/Framework.PublicInfos/Framework.PublicInfos.csproj @@ -35,6 +35,7 @@ + diff --git a/src/framework/Framework.PublicInfos/PublicInformationBusinessLogic.cs b/src/framework/Framework.PublicInfos/PublicInformationBusinessLogic.cs index 378d317431..36865cc9e2 100644 --- a/src/framework/Framework.PublicInfos/PublicInformationBusinessLogic.cs +++ b/src/framework/Framework.PublicInfos/PublicInformationBusinessLogic.cs @@ -33,7 +33,7 @@ public class PublicInformationBusinessLogic : IPublicInformationBusinessLogic { private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider; private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; /// /// Creates a new instance of @@ -45,12 +45,12 @@ public PublicInformationBusinessLogic(IActionDescriptorCollectionProvider action { _actionDescriptorCollectionProvider = actionDescriptorCollectionProvider; _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; } public async Task> GetPublicUrls() { - var companyRoleIds = await _portalRepositories.GetInstance().GetOwnCompanyRolesAsync(_identityService.IdentityData.CompanyId).ToArrayAsync().ConfigureAwait(false); + var companyRoleIds = await _portalRepositories.GetInstance().GetOwnCompanyRolesAsync(_identityData.CompanyId).ToArrayAsync().ConfigureAwait(false); return _actionDescriptorCollectionProvider.ActionDescriptors.Items .Where(item => item.ActionConstraints != null && item.ActionConstraints.OfType().Any()) .OfType() diff --git a/src/framework/Framework.Web/ClaimsIdentityDataBuilder.cs b/src/framework/Framework.Web/ClaimsIdentityDataBuilder.cs new file mode 100644 index 0000000000..c43b45a544 --- /dev/null +++ b/src/framework/Framework.Web/ClaimsIdentityDataBuilder.cs @@ -0,0 +1,51 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; + +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web; + +public class ClaimsIdentityDataBuilder : IClaimsIdentityDataBuilder +{ + private Guid? _identityId; + private IdentityTypeId? _identityTypeId; + private Guid? _companyId; + + public Guid IdentityId { get => _identityId ?? throw new UnexpectedConditionException("userId should never be null here (endpoint must be annotated with an identity policy)"); } + public IdentityTypeId IdentityTypeId { get => _identityTypeId ?? throw new UnexpectedConditionException("userId should never be null here (endpoint must be annotated with an identity policy)"); } + public Guid CompanyId { get => _companyId ?? throw new UnexpectedConditionException("companyId should never be null here (endpoint must be annotated with the a company policy)"); } + + public void AddIdentityId(Guid identityId) + { + _identityId = identityId; + } + + public void AddIdentityTypeId(IdentityTypeId identityTypeId) + { + _identityTypeId = identityTypeId; + } + + public void AddCompanyId(Guid companyId) + { + _companyId = companyId; + } + + public IClaimsIdentityDataBuilderStatus Status { get; set; } = IClaimsIdentityDataBuilderStatus.Initial; +} diff --git a/src/framework/Framework.Web/ClaimsIdentityService.cs b/src/framework/Framework.Web/ClaimsIdentityService.cs new file mode 100644 index 0000000000..9c00457546 --- /dev/null +++ b/src/framework/Framework.Web/ClaimsIdentityService.cs @@ -0,0 +1,33 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; + +namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web; + +public class ClaimsIdentityService : IIdentityService +{ + private readonly IIdentityData _identityData; + public ClaimsIdentityService(IClaimsIdentityDataBuilder claimsIdentityDataBuilder) + { + _identityData = claimsIdentityDataBuilder; + } + + public IIdentityData IdentityData => _identityData; +} diff --git a/src/framework/Framework.Web/ClaimsIdentityServiceCollectionExtensions.cs b/src/framework/Framework.Web/ClaimsIdentityServiceCollectionExtensions.cs index 0f9d87ee9b..1a2e8e8956 100644 --- a/src/framework/Framework.Web/ClaimsIdentityServiceCollectionExtensions.cs +++ b/src/framework/Framework.Web/ClaimsIdentityServiceCollectionExtensions.cs @@ -18,17 +18,16 @@ ********************************************************************************/ using Microsoft.Extensions.DependencyInjection; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Identities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web; public static class ClaimsIdentityServiceCollectionExtensions { - public static IServiceCollection AddClaimsIdentityIdDetermination(this IServiceCollection services) + public static IServiceCollection AddClaimsIdentityService(this IServiceCollection services) { return services - .AddScoped() - .AddScoped(); + .AddScoped() + .AddTransient(); } } diff --git a/src/framework/Framework.Web/Framework.Web.csproj b/src/framework/Framework.Web/Framework.Web.csproj index e92506c34b..42d499da6a 100644 --- a/src/framework/Framework.Web/Framework.Web.csproj +++ b/src/framework/Framework.Web/Framework.Web.csproj @@ -26,7 +26,6 @@ enable - diff --git a/src/framework/Framework.Web/ClaimsIdentityIdDetermination.cs b/src/framework/Framework.Web/IClaimsIdentityDataBuilder.cs similarity index 66% rename from src/framework/Framework.Web/ClaimsIdentityIdDetermination.cs rename to src/framework/Framework.Web/IClaimsIdentityDataBuilder.cs index d0525a0510..3f68c55f2c 100644 --- a/src/framework/Framework.Web/ClaimsIdentityIdDetermination.cs +++ b/src/framework/Framework.Web/IClaimsIdentityDataBuilder.cs @@ -17,22 +17,24 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Microsoft.AspNetCore.Http; -using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web; -public class ClaimsIdentityIdDetermination : IIdentityIdDetermination +public interface IClaimsIdentityDataBuilder : IIdentityData { - private readonly IHttpContextAccessor _httpContextAccessor; - private Guid? _identityId; + void AddIdentityId(Guid identityId); + void AddIdentityTypeId(IdentityTypeId identityTypeId); + void AddCompanyId(Guid companyId); - public ClaimsIdentityIdDetermination(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } + IClaimsIdentityDataBuilderStatus Status { get; set; } +} - /// - public Guid IdentityId => (_identityId ??= _httpContextAccessor.HttpContext?.User.GetIdentityId())!.Value; +public enum IClaimsIdentityDataBuilderStatus +{ + Initial, + Initialized, + Complete, + Empty } diff --git a/src/framework/Framework.Web/MandatoryIdentityClaimHandler.cs b/src/framework/Framework.Web/MandatoryIdentityClaimHandler.cs index a4183313eb..eb15bd92a7 100644 --- a/src/framework/Framework.Web/MandatoryIdentityClaimHandler.cs +++ b/src/framework/Framework.Web/MandatoryIdentityClaimHandler.cs @@ -21,8 +21,10 @@ using Microsoft.Extensions.Logging; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using System.Security.Claims; namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web { @@ -38,40 +40,94 @@ public MandatoryIdentityClaimRequirement(PolicyTypeId policyTypeId) public class MandatoryIdentityClaimHandler : AuthorizationHandler { - private readonly IIdentityService _identityService; + private readonly IIdentityRepository _identityRepository; + private readonly IServiceAccountRepository _serviceAccountRepository; + private readonly IClaimsIdentityDataBuilder _identityDataBuilder; private readonly ILogger _logger; - public MandatoryIdentityClaimHandler(IIdentityService identityService, ILogger logger) + public MandatoryIdentityClaimHandler(IClaimsIdentityDataBuilder claimsIdentityDataBuilder, IPortalRepositories portalRepositories, ILogger logger) { - _identityService = identityService; + _identityDataBuilder = claimsIdentityDataBuilder; + _identityRepository = portalRepositories.GetInstance(); + _serviceAccountRepository = portalRepositories.GetInstance(); _logger = logger; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, MandatoryIdentityClaimRequirement requirement) { - try + if (_identityDataBuilder.Status == IClaimsIdentityDataBuilderStatus.Initial) { - if (requirement.PolicyTypeId switch - { - PolicyTypeId.ValidIdentity => _identityService.IdentityId != Guid.Empty, - PolicyTypeId.ValidCompany => (await _identityService.GetIdentityData().ConfigureAwait(false)).CompanyId != Guid.Empty, - PolicyTypeId.CompanyUser => _identityService.IdentityId != Guid.Empty && (await _identityService.GetIdentityData().ConfigureAwait(false)).IdentityType == IdentityTypeId.COMPANY_USER, - PolicyTypeId.ServiceAccount => _identityService.IdentityId != Guid.Empty && (await _identityService.GetIdentityData().ConfigureAwait(false)).IdentityType == IdentityTypeId.COMPANY_SERVICE_ACCOUNT, - _ => throw new UnexpectedConditionException($"unexpected PolicyTypeId {requirement.PolicyTypeId}") - }) - { - context.Succeed(requirement); - } - else - { - context.Fail(); - } + await InitializeClaims(context.User).ConfigureAwait(false); } - catch (Exception e) + if (_identityDataBuilder.Status == IClaimsIdentityDataBuilderStatus.Empty) { - _logger.LogInformation(e, "unable to retrieve IdentityData"); context.Fail(); + return; } + if (requirement.PolicyTypeId switch + { + PolicyTypeId.ValidIdentity => _identityDataBuilder.IdentityId != Guid.Empty, + PolicyTypeId.ValidCompany => (await GetCompanyId().ConfigureAwait(false)) != Guid.Empty, + PolicyTypeId.CompanyUser => _identityDataBuilder.IdentityTypeId == IdentityTypeId.COMPANY_USER, + PolicyTypeId.ServiceAccount => _identityDataBuilder.IdentityTypeId == IdentityTypeId.COMPANY_SERVICE_ACCOUNT, + _ => throw new UnexpectedConditionException($"unexpected PolicyTypeId {requirement.PolicyTypeId}") + }) + { + context.Succeed(requirement); + } + else + { + context.Fail(); + } + } + + private async ValueTask InitializeClaims(ClaimsPrincipal principal) + { + var preferredUserName = principal.Claims.SingleOrDefault(x => x.Type == PortalClaimTypes.PreferredUserName)?.Value; + if (Guid.TryParse(preferredUserName, out var identityId)) + { + _identityDataBuilder.AddIdentityId(identityId); + _identityDataBuilder.AddIdentityTypeId(IdentityTypeId.COMPANY_USER); + _identityDataBuilder.Status = IClaimsIdentityDataBuilderStatus.Initialized; + return; + } + + (Guid IdentityId, Guid CompanyId) serviceAccountData; + var clientId = principal.Claims.SingleOrDefault(x => x.Type == PortalClaimTypes.ClientId)?.Value; + if (!string.IsNullOrWhiteSpace(clientId) && (serviceAccountData = await _serviceAccountRepository.GetServiceAccountDataByClientId(clientId).ConfigureAwait(false)) != default) + { + _identityDataBuilder.AddIdentityId(serviceAccountData.IdentityId); + _identityDataBuilder.AddIdentityTypeId(IdentityTypeId.COMPANY_SERVICE_ACCOUNT); + _identityDataBuilder.AddCompanyId(serviceAccountData.CompanyId); + _identityDataBuilder.Status = IClaimsIdentityDataBuilderStatus.Complete; + return; + } + + var sub = principal.Claims.SingleOrDefault(x => x.Type == PortalClaimTypes.Sub)?.Value; + _logger.LogInformation("Preferred user name {PreferredUserName} couldn't be parsed to uuid for sub {Sub}", preferredUserName, sub); + + (Guid IdentityId, IdentityTypeId IdentityTypeId, Guid CompanyId) identityData; + if (!string.IsNullOrWhiteSpace(sub) && (identityData = await _identityRepository.GetActiveIdentityDataByUserEntityId(sub).ConfigureAwait(false)) != default) + { + _identityDataBuilder.AddIdentityId(identityData.IdentityId); + _identityDataBuilder.AddIdentityTypeId(identityData.IdentityTypeId); + _identityDataBuilder.AddCompanyId(identityData.CompanyId); + _identityDataBuilder.Status = IClaimsIdentityDataBuilderStatus.Complete; + return; + } + + _logger.LogWarning("No identity found for userEntityId {Sub}", sub); + _identityDataBuilder.Status = IClaimsIdentityDataBuilderStatus.Empty; + } + + private async ValueTask GetCompanyId() + { + if (_identityDataBuilder.Status == IClaimsIdentityDataBuilderStatus.Initialized) + { + _identityDataBuilder.AddCompanyId(await _identityRepository.GetActiveCompanyIdByIdentityId(_identityDataBuilder.IdentityId).ConfigureAwait(false)); + _identityDataBuilder.Status = IClaimsIdentityDataBuilderStatus.Complete; + } + return _identityDataBuilder.CompanyId; } } } diff --git a/src/framework/Framework.Web/StartupServiceExtensions.cs b/src/framework/Framework.Web/StartupServiceExtensions.cs index 29397ac519..7b159eb9ab 100644 --- a/src/framework/Framework.Web/StartupServiceExtensions.cs +++ b/src/framework/Framework.Web/StartupServiceExtensions.cs @@ -89,7 +89,7 @@ public static IServiceCollection AddDefaultServices(this IServiceColle .AddCheck("JwtBearerConfiguration", tags: new[] { "keycloak" }); services.AddHttpContextAccessor(); - services.AddClaimsIdentityIdDetermination(); + services.AddClaimsIdentityService(); services.AddDateTimeProvider(); services.AddPublicInfos(); diff --git a/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs b/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs index 09d3505e87..81bcaa79b8 100644 --- a/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs +++ b/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs @@ -32,11 +32,6 @@ public static class ControllerExtensions public static T WithBearerToken(this ControllerBase controller, Func tokenConsumingFunction) => tokenConsumingFunction(controller.GetBearerToken()); - public static Guid GetIdentityId(this ClaimsPrincipal user) - { - return user.Claims.GetGuidFromClaim(PortalClaimTypes.IdentityId); - } - private static string GetBearerToken(this ControllerBase controller) { var authorization = controller.Request.Headers.Authorization.FirstOrDefault(); @@ -54,20 +49,4 @@ private static string GetBearerToken(this ControllerBase controller) return bearer; } - - private static Guid GetGuidFromClaim(this IEnumerable claims, string claimType) - { - var claimValue = claims.SingleOrDefault(x => x.Type == claimType)?.Value; - if (string.IsNullOrWhiteSpace(claimValue)) - { - throw new ControllerArgumentException($"Claim {claimType} must not be null or empty", nameof(claims)); - } - - if (!Guid.TryParse(claimValue, out var result) || Guid.Empty == result) - { - throw new ControllerArgumentException($"Claim {claimType} must contain a Guid", nameof(claims)); - } - - return result; - } } diff --git a/src/keycloak/Keycloak.Authentication/Keycloak.Authentication.csproj b/src/keycloak/Keycloak.Authentication/Keycloak.Authentication.csproj index 9374ac9a02..2d91e75b94 100644 --- a/src/keycloak/Keycloak.Authentication/Keycloak.Authentication.csproj +++ b/src/keycloak/Keycloak.Authentication/Keycloak.Authentication.csproj @@ -37,6 +37,7 @@ + diff --git a/src/keycloak/Keycloak.Authentication/KeycloakClaimsTransformation.cs b/src/keycloak/Keycloak.Authentication/KeycloakClaimsTransformation.cs index 88097e40b7..2aec20158d 100644 --- a/src/keycloak/Keycloak.Authentication/KeycloakClaimsTransformation.cs +++ b/src/keycloak/Keycloak.Authentication/KeycloakClaimsTransformation.cs @@ -19,11 +19,9 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Framework.Linq; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; using System.Json; using System.Security.Claims; @@ -31,80 +29,45 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication { public class KeycloakClaimsTransformation : IClaimsTransformation { - private readonly ILogger _logger; private readonly JwtBearerOptions _options; - private readonly IIdentityRepository _identityRepository; - public KeycloakClaimsTransformation(IOptions options, IPortalRepositories portalRepositories, ILogger logger) + public KeycloakClaimsTransformation(IOptions options) { - _identityRepository = portalRepositories.GetInstance(); - _logger = logger; _options = options.Value; } - public async Task TransformAsync(ClaimsPrincipal principal) + public Task TransformAsync(ClaimsPrincipal principal) { var claimsIdentity = new ClaimsIdentity(); - var rolesAdded = AddRoles(principal, claimsIdentity); - var identityAdded = await AddIdentity(principal, claimsIdentity).ConfigureAwait(false); - - if (rolesAdded || identityAdded) + if (AddRoles(principal, claimsIdentity)) { principal.AddIdentity(claimsIdentity); } - return principal; + return Task.FromResult(principal); } - private bool AddRoles(ClaimsPrincipal principal, ClaimsIdentity claimsIdentity) - { - var resource_access = principal.Claims - .FirstOrDefault(claim => claim.Type == PortalClaimTypes.ResourceAccess && claim.ValueType == "JSON")?.Value; - if (resource_access == null || - !((JsonValue.Parse(resource_access) as JsonObject)?.TryGetValue( - _options.TokenValidationParameters.ValidAudience, - out var audience) ?? false) || - !((audience as JsonObject)?.TryGetValue("roles", out var roles) ?? false) || - roles is not JsonArray) - { - return false; - } - - var rolesAdded = false; - foreach (JsonValue role in roles) - { - if (role.JsonType != JsonType.String) + private bool AddRoles(ClaimsPrincipal principal, ClaimsIdentity claimsIdentity) => + principal.Claims + .Where(claim => + claim.Type == PortalClaimTypes.ResourceAccess && + claim.ValueType == "JSON") + .SelectMany(claim => + JsonValue.Parse(claim.Value) is JsonObject jsonObject && + jsonObject.TryGetValue( + _options.TokenValidationParameters.ValidAudience, + out var audience) && + audience is JsonObject client && + client.TryGetValue("roles", out var jsonRoles) && + jsonRoles is JsonArray roles + ? roles.Where(x => x.JsonType == JsonType.String) + .Select(role => new Claim(ClaimTypes.Role, role)) + : Enumerable.Empty()) + .IfAny(claims => { - continue; - } - - claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role)); - rolesAdded = true; - } - - return rolesAdded; - } - - private async ValueTask AddIdentity(ClaimsPrincipal principal, ClaimsIdentity claimsIdentity) - { - var preferredUserName = principal.Claims.SingleOrDefault(x => x.Type == PortalClaimTypes.PreferredUserName)?.Value; - - if (!string.IsNullOrWhiteSpace(preferredUserName) && Guid.TryParse(preferredUserName, out var identityId)) - { - claimsIdentity.AddClaim(new Claim(PortalClaimTypes.IdentityId, preferredUserName!)); - return true; - } - - var sub = principal.Claims.SingleOrDefault(x => x.Type == PortalClaimTypes.Sub)?.Value; - _logger.LogInformation("Preferred user name {PreferredUserName} couldn't be parsed to uuid for userEntityId {Sub}", preferredUserName, sub); - - if (string.IsNullOrWhiteSpace(sub) || (identityId = await _identityRepository.GetIdentityIdByUserEntityId(sub).ConfigureAwait(false)) == Guid.Empty) - { - _logger.LogWarning("No identity found for userEntityId {Sub}", sub); - return false; - } - - claimsIdentity.AddClaim(new Claim(PortalClaimTypes.IdentityId, identityId.ToString())); - return true; - } + foreach (var claim in claims) + { + claimsIdentity.AddClaim(claim); + } + }); } } diff --git a/src/maintenance/Maintenance.App/Program.cs b/src/maintenance/Maintenance.App/Program.cs index 330e19e9b7..80c85aca48 100644 --- a/src/maintenance/Maintenance.App/Program.cs +++ b/src/maintenance/Maintenance.App/Program.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -37,7 +36,7 @@ .ConfigureServices((hostContext, services) => { services - .AddConfigurationIdentityIdDetermination(hostContext.Configuration.GetSection("ProcessIdentity")) + .AddConfigurationProcessIdentityIdDetermination(hostContext.Configuration.GetSection("ProcessIdentity")) .AddDbAuditing() .AddDbContext(o => o.UseNpgsql(hostContext.Configuration.GetConnectionString("PortalDb")) diff --git a/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs index 8af83b7cf1..2d30b33b70 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs @@ -51,7 +51,7 @@ public class AppChangeBusinessLogic : IAppChangeBusinessLogic private readonly INotificationService _notificationService; private readonly IProvisioningManager _provisioningManager; private readonly IOfferService _offerService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IOfferDocumentService _offerDocumentService; private readonly IDateTimeProvider _dateTimeProvider; @@ -81,7 +81,7 @@ public AppChangeBusinessLogic( _provisioningManager = provisioningManager; _settings = settings.Value; _offerService = offerService; - _identityService = identityService; + _identityData = identityService.IdentityData; _offerDocumentService = offerDocumentService; _dateTimeProvider = dateTimeProvider; } @@ -95,7 +95,6 @@ public Task> AddActiveAppUserRoleAsync(Guid appId, IEnu private async Task> InsertActiveAppUserRoleAsync(Guid appId, IEnumerable userRoles) { - var identity = _identityService.IdentityData; var result = await _portalRepositories.GetInstance().GetInsertActiveAppUserRoleDataAsync(appId, OfferTypeId.APP).ConfigureAwait(false); if (result == default) { @@ -107,9 +106,9 @@ private async Task> InsertActiveAppUserRoleAsync(Guid a throw new ConflictException($"App {appId} providing company is not yet set."); } - if (result.ProviderCompanyId.Value != identity.CompanyId) + if (result.ProviderCompanyId.Value != _identityData.CompanyId) { - throw new ForbiddenException($"Company {identity.CompanyId} is not the provider company of app {appId}"); + throw new ForbiddenException($"Company {_identityData.CompanyId} is not the provider company of app {appId}"); } var roleData = AppExtensions.CreateUserRolesWithDescriptions(_portalRepositories.GetInstance(), appId, userRoles); @@ -128,7 +127,7 @@ private async Task> InsertActiveAppUserRoleAsync(Guid a }; var serializeNotificationContent = JsonSerializer.Serialize(notificationContent); var content = _settings.ActiveAppNotificationTypeIds.Select(typeId => new ValueTuple(serializeNotificationContent, typeId)); - await _notificationService.CreateNotifications(_settings.ActiveAppCompanyAdminRoles, identity.UserId, content, result.ProviderCompanyId.Value).AwaitAll().ConfigureAwait(false); + await _notificationService.CreateNotifications(_settings.ActiveAppCompanyAdminRoles, _identityData.IdentityId, content, result.ProviderCompanyId.Value).AwaitAll().ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); return roleData; } @@ -156,7 +155,7 @@ await ValidateAndGetAppDescription(appId, offerRepository), private async Task> ValidateAndGetAppDescription(Guid appId, IOfferRepository offerRepository) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await offerRepository.GetActiveOfferDescriptionDataByIdAsync(appId, OfferTypeId.APP, companyId).ConfigureAwait(false); if (result == default) { @@ -189,8 +188,7 @@ public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, I documentContentType.CheckDocumentContentType(appLeadImageContentTypes); var offerRepository = _portalRepositories.GetInstance(); - var identity = _identityService.IdentityData; - var result = await offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, identity.CompanyId, OfferTypeId.APP).ConfigureAwait(false); + var result = await offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, _identityData.CompanyId, OfferTypeId.APP).ConfigureAwait(false); if (result == default) { @@ -202,14 +200,14 @@ public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, I } if (!result.IsUserOfProvider) { - throw new ForbiddenException($"Company {identity.CompanyId} is not the provider company of App {appId}"); + throw new ForbiddenException($"Company {_identityData.CompanyId} is not the provider company of App {appId}"); } var documentRepository = _portalRepositories.GetInstance(); var (documentContent, hash) = await document.GetContentAndHash(cancellationToken).ConfigureAwait(false); var doc = documentRepository.CreateDocument(document.FileName, documentContent, hash, documentContentType, DocumentTypeId.APP_LEADIMAGE, x => { - x.CompanyUserId = identity.UserId; + x.CompanyUserId = _identityData.IdentityId; x.DocumentStatusId = DocumentStatusId.LOCKED; }); offerRepository.CreateOfferAssignedDocument(appId, doc.Id); @@ -235,7 +233,7 @@ public Task UpdateTenantUrlAsync(Guid offerId, Guid subscriptionId, UpdateTenant private async Task UpdateTenantUrlAsyncInternal(Guid offerId, Guid subscriptionId, string url) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var offerSubscriptionsRepository = _portalRepositories.GetInstance(); var result = await offerSubscriptionsRepository.GetUpdateUrlDataAsync(offerId, subscriptionId, companyId).ConfigureAwait(false); if (result == null) @@ -312,7 +310,7 @@ private async Task UpdateTenantUrlAsyncInternal(Guid offerId, Guid subscriptionI public async Task GetActiveAppDocumentTypeDataAsync(Guid appId) { var appDocTypeData = await _portalRepositories.GetInstance() - .GetActiveOfferDocumentTypeDataOrderedAsync(appId, _identityService.IdentityData.CompanyId, OfferTypeId.APP, _settings.ActiveAppDocumentTypeIds) + .GetActiveOfferDocumentTypeDataOrderedAsync(appId, _identityData.CompanyId, OfferTypeId.APP, _settings.ActiveAppDocumentTypeIds) .PreSortedGroupBy(result => result.DocumentTypeId) .ToDictionaryAsync( group => group.Key, @@ -334,7 +332,7 @@ public async Task DeleteActiveAppDocumentAsync(Guid appId, Guid documentId) { var offerRepository = _portalRepositories.GetInstance(); var documentRepository = _portalRepositories.GetInstance(); - var result = await offerRepository.GetOfferAssignedAppDocumentsByIdAsync(appId, _identityService.IdentityData.CompanyId, OfferTypeId.APP, documentId).ConfigureAwait(false); + var result = await offerRepository.GetOfferAssignedAppDocumentsByIdAsync(appId, _identityData.CompanyId, OfferTypeId.APP, documentId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"Document {documentId} for App {appId} does not exist."); @@ -345,7 +343,7 @@ public async Task DeleteActiveAppDocumentAsync(Guid appId, Guid documentId) } if (!result.IsUserOfProvider) { - throw new ForbiddenException($"Company {_identityService.IdentityData.CompanyId} is not the provider company of App {appId}"); + throw new ForbiddenException($"Company {_identityData.CompanyId} is not the provider company of App {appId}"); } if (!_settings.DeleteActiveAppDocumentTypeIds.Contains(result.DocumentTypeId)) { diff --git a/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs index 770784929f..d09eb66fe9 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs @@ -45,7 +45,7 @@ public class AppReleaseBusinessLogic : IAppReleaseBusinessLogic private readonly IOfferService _offerService; private readonly IOfferDocumentService _offerDocumentService; private readonly IOfferSetupService _offerSetupService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; /// /// Constructor. @@ -63,7 +63,7 @@ public AppReleaseBusinessLogic(IPortalRepositories portalRepositories, IOptions< _offerService = offerService; _offerDocumentService = offerDocumentService; _offerSetupService = offerSetupService; - _identityService = identityService; + _identityData = identityService.IdentityData; } /// @@ -82,7 +82,7 @@ public Task> AddAppUserRoleAsync(Guid appId, IEnumerabl private async Task> InsertAppUserRoleAsync(Guid appId, IEnumerable userRoles) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().IsProviderCompanyUserAsync(appId, companyId, OfferTypeId.APP).ConfigureAwait(false); if (result == default) { @@ -151,7 +151,7 @@ public async Task GetAppDetailsForStatusAsync(Guid appId) /// public async Task DeleteAppRoleAsync(Guid appId, Guid roleId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var appUserRole = await _portalRepositories.GetInstance().GetAppUserRoleUntrackedAsync(appId, companyId, OfferStatusId.CREATED, roleId).ConfigureAwait(false); if (!appUserRole.IsProviderCompanyUser) { @@ -171,7 +171,7 @@ public async Task DeleteAppRoleAsync(Guid appId, Guid roleId) /// public IAsyncEnumerable GetAppProviderSalesManagersAsync() => - _portalRepositories.GetInstance().GetUserDataByAssignedRoles(_identityService.IdentityData.CompanyId, _settings.SalesManagerRoles); + _portalRepositories.GetInstance().GetUserDataByAssignedRoles(_identityData.CompanyId, _settings.SalesManagerRoles); /// public Task AddAppAsync(AppRequestModel appRequestModel) @@ -193,7 +193,7 @@ public Task AddAppAsync(AppRequestModel appRequestModel) private async Task CreateAppAsync(AppRequestModel appRequestModel) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; if (appRequestModel.SalesManagerId.HasValue) { await _offerService.ValidateSalesManager(appRequestModel.SalesManagerId.Value, _settings.SalesManagerRoles).ConfigureAwait(false); @@ -241,7 +241,7 @@ private async Task CreateAppAsync(AppRequestModel appRequestModel) /// public async Task UpdateAppReleaseAsync(Guid appId, AppRequestModel appRequestModel) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var appData = await _portalRepositories.GetInstance() .GetAppUpdateData( appId, @@ -394,7 +394,7 @@ public Task DeleteAppDocumentsAsync(Guid documentId) => /// public async Task DeleteAppAsync(Guid appId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var (isValidApp, isOfferType, isOfferStatus, isProviderCompanyUser, appData) = await _portalRepositories.GetInstance().GetAppDeleteDataAsync(appId, OfferTypeId.APP, companyId, OfferStatusId.CREATED).ConfigureAwait(false); if (!isValidApp) { @@ -446,7 +446,7 @@ public Task SetInstanceType(Guid appId, AppInstanceSetupData data) private async Task SetInstanceTypeInternal(Guid appId, AppInstanceSetupData data) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance() .GetOfferWithSetupDataById(appId, companyId, OfferTypeId.APP) .ConfigureAwait(false); diff --git a/src/marketplace/Apps.Service/BusinessLogic/AppsBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/AppsBusinessLogic.cs index 591f30613c..cc65343a83 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/AppsBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/AppsBusinessLogic.cs @@ -44,7 +44,7 @@ public class AppsBusinessLogic : IAppsBusinessLogic private readonly AppsSettings _settings; private readonly IOfferService _offerService; private readonly IOfferSetupService _offerSetupService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly ILogger _logger; /// @@ -70,7 +70,7 @@ public AppsBusinessLogic( _offerSubscriptionService = offerSubscriptionService; _offerService = offerService; _offerSetupService = offerSetupService; - _identityService = identityService; + _identityData = identityService.IdentityData; _logger = logger; _settings = settings.Value; } @@ -91,7 +91,7 @@ public IAsyncEnumerable GetAllActiveAppsAsync(string? languageShortName /// public IAsyncEnumerable GetAllUserUserBusinessAppsAsync() => _portalRepositories.GetInstance() - .GetAllBusinessAppDataForUserIdAsync(_identityService.IdentityId) + .GetAllBusinessAppDataForUserIdAsync(_identityData.IdentityId) .Select(x => new BusinessAppData( x.OfferId, @@ -105,7 +105,7 @@ public IAsyncEnumerable GetAllUserUserBusinessAppsAsync() => public async Task GetAppDetailsByIdAsync(Guid appId, string? languageShortName = null) { var result = await _portalRepositories.GetInstance() - .GetOfferDetailsByIdAsync(appId, _identityService.IdentityData.CompanyId, languageShortName, Constants.DefaultLanguage, OfferTypeId.APP).ConfigureAwait(false); + .GetOfferDetailsByIdAsync(appId, _identityData.CompanyId, languageShortName, Constants.DefaultLanguage, OfferTypeId.APP).ConfigureAwait(false); if (result == null) { throw new NotFoundException($"appId {appId} does not exist"); @@ -138,19 +138,19 @@ public async Task GetAppDetailsByIdAsync(Guid appId, string? public IAsyncEnumerable GetAllFavouriteAppsForUserAsync() => _portalRepositories .GetInstance() - .GetAllFavouriteAppsForUserUntrackedAsync(_identityService.IdentityId); + .GetAllFavouriteAppsForUserUntrackedAsync(_identityData.IdentityId); /// public async Task RemoveFavouriteAppForUserAsync(Guid appId) { - _portalRepositories.Remove(new CompanyUserAssignedAppFavourite(appId, _identityService.IdentityId)); + _portalRepositories.Remove(new CompanyUserAssignedAppFavourite(appId, _identityData.IdentityId)); await _portalRepositories.SaveAsync().ConfigureAwait(false); } /// public async Task AddFavouriteAppForUserAsync(Guid appId) { - _portalRepositories.GetInstance().CreateAppFavourite(appId, _identityService.IdentityId); + _portalRepositories.GetInstance().CreateAppFavourite(appId, _identityData.IdentityId); await _portalRepositories.SaveAsync().ConfigureAwait(false); } @@ -164,7 +164,7 @@ public async Task AddFavouriteAppForUserAsync(Guid appId) async Task?> GetCompanyProvidedAppSubscriptionStatusData(int skip, int take) { var offerCompanySubscriptionResponse = await _portalRepositories.GetInstance() - .GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identityService.IdentityData.CompanyId, OfferTypeId.APP, sorting, OfferSubscriptionService.GetOfferSubscriptionFilterStatusIds(statusId), offerId)(skip, take).ConfigureAwait(false); + .GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identityData.CompanyId, OfferTypeId.APP, sorting, OfferSubscriptionService.GetOfferSubscriptionFilterStatusIds(statusId), offerId)(skip, take).ConfigureAwait(false); return offerCompanySubscriptionResponse == null ? null @@ -195,7 +195,7 @@ public Task UnsubscribeOwnCompanyAppSubscriptionAsync(Guid subscriptionId) => /// public Task> GetCompanyProvidedAppsDataForUserAsync(int page, int size, OfferSorting? sorting, string? offerName, AppStatusIdFilter? statusId) => Pagination.CreateResponseAsync(page, size, 15, - _portalRepositories.GetInstance().GetProvidedOffersData(GetOfferStatusIds(statusId), OfferTypeId.APP, _identityService.IdentityData.CompanyId, sorting ?? OfferSorting.DateDesc, offerName)); + _portalRepositories.GetInstance().GetProvidedOffersData(GetOfferStatusIds(statusId), OfferTypeId.APP, _identityData.CompanyId, sorting ?? OfferSorting.DateDesc, offerName)); private static IEnumerable GetOfferStatusIds(AppStatusIdFilter? appStatusIdFilter) => appStatusIdFilter switch @@ -236,9 +236,9 @@ public Task GetSubscriptionDetailForSubscriber /// public IAsyncEnumerable GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsync() => - _portalRepositories.GetInstance().GetOwnCompanyActiveSubscribedOfferSubscriptionStatusesUntrackedAsync(_identityService.IdentityData.CompanyId, OfferTypeId.APP, DocumentTypeId.APP_LEADIMAGE); + _portalRepositories.GetInstance().GetOwnCompanyActiveSubscribedOfferSubscriptionStatusesUntrackedAsync(_identityData.CompanyId, OfferTypeId.APP, DocumentTypeId.APP_LEADIMAGE); /// public IAsyncEnumerable GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync() => - _portalRepositories.GetInstance().GetOwnCompanySubscribedOfferSubscriptionUntrackedAsync(_identityService.IdentityData.CompanyId, OfferTypeId.APP); + _portalRepositories.GetInstance().GetOwnCompanySubscribedOfferSubscriptionUntrackedAsync(_identityData.CompanyId, OfferTypeId.APP); } diff --git a/src/marketplace/Offers.Library.Web/OfferDocumentService.cs b/src/marketplace/Offers.Library.Web/OfferDocumentService.cs index edc5d6d5b9..918c5596d2 100644 --- a/src/marketplace/Offers.Library.Web/OfferDocumentService.cs +++ b/src/marketplace/Offers.Library.Web/OfferDocumentService.cs @@ -33,7 +33,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Offers.Library.Web; public class OfferDocumentService : IOfferDocumentService { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; /// /// Constructor. @@ -43,7 +43,7 @@ public class OfferDocumentService : IOfferDocumentService public OfferDocumentService(IPortalRepositories portalRepositories, IIdentityService identityService) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; } public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IFormFile document, OfferTypeId offerTypeId, IEnumerable uploadDocumentTypeIdSettings, OfferStatusId offerStatusId, CancellationToken cancellationToken) @@ -58,7 +58,6 @@ public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IF throw new ControllerArgumentException("File name should not be null"); } - var identity = _identityService.IdentityData; var uploadContentTypeSettings = uploadDocumentTypeIdSettings.FirstOrDefault(x => x.DocumentTypeId == documentTypeId); if (uploadContentTypeSettings == null) { @@ -80,7 +79,7 @@ public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IF } var offerRepository = _portalRepositories.GetInstance(); - var result = await offerRepository.GetProviderCompanyUserIdForOfferUntrackedAsync(id, identity.CompanyId, offerStatusId, offerTypeId).ConfigureAwait(false); + var result = await offerRepository.GetProviderCompanyUserIdForOfferUntrackedAsync(id, _identityData.CompanyId, offerStatusId, offerTypeId).ConfigureAwait(false); if (result == default) { @@ -92,14 +91,14 @@ public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IF if (!result.IsUserOfProvider) { - throw new ForbiddenException($"Company {identity.CompanyId} is not the provider company of {offerTypeId} {id}"); + throw new ForbiddenException($"Company {_identityData.CompanyId} is not the provider company of {offerTypeId} {id}"); } var (content, hash) = await document.GetContentAndHash(cancellationToken).ConfigureAwait(false); var doc = _portalRepositories.GetInstance().CreateDocument(document.FileName, content, hash, mediaTypeId, documentTypeId, x => { - x.CompanyUserId = identity.UserId; + x.CompanyUserId = _identityData.IdentityId; }); _portalRepositories.GetInstance().CreateOfferAssignedDocument(id, doc.Id); diff --git a/src/marketplace/Offers.Library/Service/OfferService.cs b/src/marketplace/Offers.Library/Service/OfferService.cs index 9d5587e298..decb668752 100644 --- a/src/marketplace/Offers.Library/Service/OfferService.cs +++ b/src/marketplace/Offers.Library/Service/OfferService.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -43,7 +42,7 @@ public class OfferService : IOfferService private readonly IPortalRepositories _portalRepositories; private readonly INotificationService _notificationService; private readonly IRoleBaseMailService _roleBaseMailService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IOfferSetupService _offerSetupService; private readonly ILogger _logger; @@ -66,7 +65,7 @@ public OfferService(IPortalRepositories portalRepositories, _portalRepositories = portalRepositories; _notificationService = notificationService; _roleBaseMailService = roleBaseMailService; - _identityService = identityService; + _identityData = identityService.IdentityData; _offerSetupService = offerSetupService; _logger = logger; } @@ -124,20 +123,19 @@ public async Task CreateOrUpdateOfferSubscriptionAgreementConsentAsync(Guid subs private async Task<(Guid CompanyId, OfferSubscription OfferSubscription, Guid CompanyUserId)> GetOfferSubscriptionCompanyAndUserAsync(Guid subscriptionId, OfferTypeId offerTypeId) { - var identity = _identityService.IdentityData; var result = await _portalRepositories.GetInstance() - .GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync(subscriptionId, identity.UserId, offerTypeId) + .GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync(subscriptionId, _identityData.IdentityId, offerTypeId) .ConfigureAwait(false); if (result == default) { - throw new ControllerArgumentException("Company or CompanyUser not assigned correctly.", nameof(identity.UserEntityId)); + throw new ControllerArgumentException("Company or CompanyUser not assigned correctly.", nameof(_identityData.IdentityId)); } var (companyId, offerSubscription) = result; if (offerSubscription is null) { throw new NotFoundException($"Invalid OfferSubscription {subscriptionId} for OfferType {offerTypeId}"); } - return (companyId, offerSubscription, identity.UserId); + return (companyId, offerSubscription, _identityData.IdentityId); } /// @@ -162,7 +160,7 @@ public IAsyncEnumerable GetOfferTypeAgreements(OfferTypeI public async Task GetProviderOfferAgreementConsentById(Guid offerId, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOfferAgreementConsentById(offerId, companyId, offerTypeId).ConfigureAwait(false); if (result == default) { @@ -177,7 +175,6 @@ public async Task GetProviderOfferAgreementConsentById(Gu public async Task> CreateOrUpdateProviderOfferAgreementConsent(Guid offerId, OfferAgreementConsent offerAgreementConsent, OfferTypeId offerTypeId) { - var identity = _identityService.IdentityData; var (dbAgreements, requiredAgreementIds) = await GetProviderOfferAgreementConsent(offerId, OfferStatusId.CREATED, offerTypeId).ConfigureAwait(false); var invalidConsents = offerAgreementConsent.Agreements.ExceptBy(requiredAgreementIds, consent => consent.AgreementId); if (invalidConsents.Any()) @@ -190,8 +187,8 @@ public async Task> CreateOrUpdateProviderOfferAgr dbAgreements, offerAgreementConsent.Agreements, offerId, - identity.CompanyId, - identity.UserId, + _identityData.CompanyId, + _identityData.IdentityId, DateTimeOffset.UtcNow) .Select(consent => new ConsentStatusData(consent.AgreementId, consent.ConsentStatusId)); @@ -204,7 +201,7 @@ public async Task> CreateOrUpdateProviderOfferAgr private async Task GetProviderOfferAgreementConsent(Guid offerId, OfferStatusId statusId, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOfferAgreementConsent(offerId, companyId, statusId, offerTypeId).ConfigureAwait(false); if (result == default) { @@ -220,7 +217,6 @@ private async Task GetProviderOfferAgreementConsent /// public async Task CreateServiceOfferingAsync(ServiceOfferingData data, OfferTypeId offerTypeId) { - var identity = _identityService.IdentityData; if (!data.ServiceTypeIds.Any()) { throw new ControllerArgumentException("ServiceTypeIds must be specified", nameof(data.ServiceTypeIds)); @@ -230,13 +226,13 @@ public async Task CreateServiceOfferingAsync(ServiceOfferingData data, Off throw new ControllerArgumentException("Title should be at least three character long", nameof(data.Title)); } - var result = await _portalRepositories.GetInstance().GetCompanyNameUntrackedAsync(identity.CompanyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetCompanyNameUntrackedAsync(_identityData.CompanyId).ConfigureAwait(false); if (!result.IsValidCompany) { - throw new ControllerArgumentException($"No company {identity.CompanyId} found"); + throw new ControllerArgumentException($"No company {_identityData.CompanyId} found"); } - if (data.SalesManager.HasValue && identity.UserId != data.SalesManager.Value) + if (data.SalesManager.HasValue && _identityData.IdentityId != data.SalesManager.Value) throw new ControllerArgumentException("SalesManager does not exist", nameof(data.SalesManager)); await CheckLanguageCodesExist(data.Descriptions.Select(x => x.LanguageCode)).ConfigureAwait(false); @@ -249,7 +245,7 @@ public async Task CreateServiceOfferingAsync(ServiceOfferingData data, Off service.SalesManagerId = data.SalesManager; service.Provider = result.CompanyName; service.OfferStatusId = OfferStatusId.CREATED; - service.ProviderCompanyId = identity.CompanyId; + service.ProviderCompanyId = _identityData.CompanyId; service.MarketingUrl = data.ProviderUri; service.LicenseTypeId = LicenseTypeId.COTS; service.DateLastChanged = DateTimeOffset.UtcNow; @@ -268,7 +264,7 @@ public async Task CreateServiceOfferingAsync(ServiceOfferingData data, Off /// public async Task GetProviderOfferDetailsForStatusAsync(Guid offerId, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var offerDetail = await _portalRepositories.GetInstance().GetProviderOfferDataWithConsentStatusAsync(offerId, companyId, offerTypeId).ConfigureAwait(false); if (offerDetail == default) { @@ -309,7 +305,7 @@ public async Task GetProviderOfferDetailsForStatusAsync(G /// public async Task ValidateSalesManager(Guid salesManagerId, IEnumerable salesManagerRoles) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var userRoleIds = await _portalRepositories.GetInstance() .GetUserRoleIdsUntrackedAsync(salesManagerRoles).ToListAsync().ConfigureAwait(false); var responseData = await _portalRepositories.GetInstance() @@ -431,7 +427,7 @@ private async Task SubmitAppServiceAsync(Guid offerId, IEnumerable new ValueTuple(serializeNotificationContent, typeId)); - await _notificationService.CreateNotifications(catenaAdminRoles, _identityService.IdentityId, content, false).ConfigureAwait(false); + await _notificationService.CreateNotifications(catenaAdminRoles, _identityData.IdentityId, content, false).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); } @@ -521,7 +517,7 @@ public async Task ApproveOfferRequestAsync(Guid offerId, OfferTypeId offerTypeId var serializeNotificationContent = JsonSerializer.Serialize(notificationContent); var content = approveOfferNotificationTypeIds.Select(typeId => new ValueTuple(serializeNotificationContent, typeId)); - await _notificationService.CreateNotifications(approveOfferRoles, _identityService.IdentityId, content, offerDetails.ProviderCompanyId.Value).AwaitAll().ConfigureAwait(false); + await _notificationService.CreateNotifications(approveOfferRoles, _identityData.IdentityId, content, offerDetails.ProviderCompanyId.Value).AwaitAll().ConfigureAwait(false); await _notificationService.SetNotificationsForOfferToDone(catenaAdminRoles, submitOfferNotificationTypeIds, offerId).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); @@ -596,7 +592,7 @@ public async Task DeclineOfferAsync(Guid offerId, OfferDeclineRequest data, Offe (JsonSerializer.Serialize(notificationContent), notificationTypeId) }; - await _notificationService.CreateNotifications(notificationRecipients, _identityService.IdentityId, content, declineData.CompanyId.Value).AwaitAll().ConfigureAwait(false); + await _notificationService.CreateNotifications(notificationRecipients, _identityData.IdentityId, content, declineData.CompanyId.Value).AwaitAll().ConfigureAwait(false); await _notificationService.SetNotificationsForOfferToDone(catenaAdminRoles, submitOfferNotificationTypeIds, offerId).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); @@ -638,7 +634,7 @@ private async Task CheckLanguageCodesExist(IEnumerable languageCodes) public async Task DeactivateOfferIdAsync(Guid offerId, OfferTypeId offerTypeId) { var offerRepository = _portalRepositories.GetInstance(); - var offerData = await offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var offerData = await offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _identityData.CompanyId).ConfigureAwait(false); if (offerData == default) { throw new NotFoundException($"{offerTypeId} {offerId} does not exist."); @@ -694,7 +690,7 @@ public async Task DeactivateOfferIdAsync(Guid offerId, OfferTypeId offerTypeId) /// public async Task DeleteDocumentsAsync(Guid documentId, IEnumerable documentTypeIdSettings, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOfferDocumentsAsync(documentId, companyId, documentTypeIdSettings, offerTypeId).ConfigureAwait(false); if (result == default) { @@ -744,7 +740,7 @@ public async Task DeleteDocumentsAsync(Guid documentId, IEnumerable> GetTechnicalUserProfilesForOffer(Guid offerId, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var result = await _portalRepositories.GetInstance() .GetTechnicalUserProfileInformation(offerId, companyId, offerTypeId).ConfigureAwait(false); if (result == default) @@ -763,7 +759,7 @@ public async Task> GetTechnicalUser /// public async Task UpdateTechnicalUserProfiles(Guid offerId, OfferTypeId offerTypeId, IEnumerable data, string technicalUserProfileClient) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; if (data.Any(x => x.TechnicalUserProfileId == null && !x.UserRoleIds.Any())) { throw new ControllerArgumentException("Technical User Profiles and Role IDs both should not be empty."); @@ -838,7 +834,7 @@ public Task GetSubscriptionDetailsForSubscribe private async Task GetOfferSubscriptionDetailsInternal(Guid offerId, Guid subscriptionId, OfferTypeId offerTypeId, IEnumerable contactUserRoles, OfferCompanyRole offerCompanyRole, Func, Task<(bool, bool, R?)>> query) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var userRoleIds = await ValidateRoleData(contactUserRoles).ConfigureAwait(false); var (exists, isUserOfCompany, details) = await query(offerId, subscriptionId, companyId, offerTypeId, userRoleIds) @@ -882,7 +878,7 @@ private async Task> ValidateRoleData(IEnumerable?> GetCompanySubscribedOfferSubscriptionStatusesData(int skip, int take) { var offerCompanySubscriptionResponse = await _portalRepositories.GetInstance() - .GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_identityService.IdentityData.CompanyId, offerTypeId, documentTypeId)(skip, take).ConfigureAwait(false); + .GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_identityData.CompanyId, offerTypeId, documentTypeId)(skip, take).ConfigureAwait(false); return offerCompanySubscriptionResponse == null ? null @@ -902,7 +898,7 @@ private async Task> ValidateRoleData(IEnumerable public async Task UnsubscribeOwnCompanySubscriptionAsync(Guid subscriptionId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var offerSubscriptionsRepository = _portalRepositories.GetInstance(); var connectorsRepository = _portalRepositories.GetInstance(); var userRepository = _portalRepositories.GetInstance(); diff --git a/src/marketplace/Offers.Library/Service/OfferSetupService.cs b/src/marketplace/Offers.Library/Service/OfferSetupService.cs index 0b47004a05..8364717dfb 100644 --- a/src/marketplace/Offers.Library/Service/OfferSetupService.cs +++ b/src/marketplace/Offers.Library/Service/OfferSetupService.cs @@ -48,7 +48,7 @@ public class OfferSetupService : IOfferSetupService private readonly IOfferSubscriptionProcessService _offerSubscriptionProcessService; private readonly IMailingService _mailingService; private readonly ITechnicalUserProfileService _technicalUserProfileService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly ILogger _logger; /// @@ -81,21 +81,20 @@ public OfferSetupService( _offerSubscriptionProcessService = offerSubscriptionProcessService; _mailingService = mailingService; _technicalUserProfileService = technicalUserProfileService; - _identityService = identityService; + _identityData = identityService.IdentityData; _logger = logger; } public async Task AutoSetupOfferAsync(OfferAutoSetupData data, IEnumerable itAdminRoles, OfferTypeId offerTypeId, string basePortalAddress, IEnumerable serviceManagerRoles) { - var identity = _identityService.IdentityData; - _logger.LogDebug("AutoSetup started from Company {CompanyId} for {RequestId} with OfferUrl: {OfferUrl}", identity.CompanyId, data.RequestId, data.OfferUrl); + _logger.LogDebug("AutoSetup started from Company {CompanyId} for {RequestId} with OfferUrl: {OfferUrl}", _identityData.CompanyId, data.RequestId, data.OfferUrl); if (data.OfferUrl.Contains('#', StringComparison.OrdinalIgnoreCase)) { throw new ControllerArgumentException($"OfferUrl {data.OfferUrl} must not contain #"); } var offerSubscriptionsRepository = _portalRepositories.GetInstance(); - var offerDetails = await GetAndValidateOfferDetails(data.RequestId, identity.CompanyId, offerTypeId, offerSubscriptionsRepository).ConfigureAwait(false); + var offerDetails = await GetAndValidateOfferDetails(data.RequestId, _identityData.CompanyId, offerTypeId, offerSubscriptionsRepository).ConfigureAwait(false); offerSubscriptionsRepository.AttachAndModifyOfferSubscription(data.RequestId, subscription => { @@ -110,7 +109,7 @@ public async Task AutoSetupOfferAsync(OfferAutoSetup appSubscriptionDetail.AppInstanceId = offerDetails.AppInstanceIds.Single(); appSubscriptionDetail.AppSubscriptionUrl = offerDetails.InstanceData.InstanceUrl; }); - await CreateNotifications(itAdminRoles, offerTypeId, offerDetails, identity.UserId).ConfigureAwait(false); + await CreateNotifications(itAdminRoles, offerTypeId, offerDetails, _identityData.IdentityId).ConfigureAwait(false); await SetNotificationsToDone(serviceManagerRoles, offerTypeId, offerDetails.OfferId, offerDetails.SalesManagerId).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); return new OfferAutoSetupResponseData(null, null); @@ -129,7 +128,7 @@ public async Task AutoSetupOfferAsync(OfferAutoSetup var createTechnicalUserData = new CreateTechnicalUserData(offerDetails.CompanyId, offerDetails.OfferName, offerDetails.Bpn, technicalUserClientId, offerTypeId == OfferTypeId.APP, true); var technicalUserInfoData = await CreateTechnicalUserForSubscription(data.RequestId, createTechnicalUserData).ConfigureAwait(false); - await CreateNotifications(itAdminRoles, offerTypeId, offerDetails, identity.UserId).ConfigureAwait(false); + await CreateNotifications(itAdminRoles, offerTypeId, offerDetails, _identityData.IdentityId).ConfigureAwait(false); await SetNotificationsToDone(serviceManagerRoles, offerTypeId, offerDetails.OfferId, offerDetails.SalesManagerId).ConfigureAwait(false); await _portalRepositories.SaveAsync().ConfigureAwait(false); @@ -403,7 +402,7 @@ await _mailingService /// public async Task StartAutoSetupAsync(OfferAutoSetupData data, OfferTypeId offerTypeId) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; _logger.LogDebug("AutoSetup Process started from Company {CompanyId} for {RequestId} with OfferUrl: {OfferUrl}", companyId, data.RequestId, data.OfferUrl); if (data.OfferUrl.Contains('#', StringComparison.OrdinalIgnoreCase)) { @@ -450,7 +449,7 @@ public async Task CreateSingleInstanceSubscriptionDetail(Guid offerSubscriptionI case true when offerDetails.AppInstanceIds.Count() != 1: throw new ConflictException("There must only be one app instance for single instance apps"); default: - if (offerDetails.ProviderCompanyId != _identityService.IdentityData.CompanyId) + if (offerDetails.ProviderCompanyId != _identityData.CompanyId) { throw new ConflictException("Subscription can only be activated by the provider of the offer"); } @@ -559,10 +558,10 @@ public async Task TriggerActivateSubscription(Guid offerSubscriptionId) { var context = await _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscriptionId, ProcessStepTypeId.TRIGGER_ACTIVATE_SUBSCRIPTION, null, true).ConfigureAwait(false); if (!await _portalRepositories.GetInstance() - .CheckOfferSubscriptionForProvider(offerSubscriptionId, _identityService.IdentityData.CompanyId).ConfigureAwait(false)) + .CheckOfferSubscriptionForProvider(offerSubscriptionId, _identityData.CompanyId).ConfigureAwait(false)) { throw new ConflictException( - $"Company {_identityService.IdentityData.CompanyId} must be provider of the offer for offerSubscription {offerSubscriptionId}"); + $"Company {_identityData.CompanyId} must be provider of the offer for offerSubscription {offerSubscriptionId}"); } _offerSubscriptionProcessService.FinalizeProcessSteps(context, Enumerable.Repeat(ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, 1)); diff --git a/src/marketplace/Offers.Library/Service/OfferSubscriptionService.cs b/src/marketplace/Offers.Library/Service/OfferSubscriptionService.cs index 5c9365090f..3f41f16b6f 100644 --- a/src/marketplace/Offers.Library/Service/OfferSubscriptionService.cs +++ b/src/marketplace/Offers.Library/Service/OfferSubscriptionService.cs @@ -36,7 +36,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Offers.Library.Service; public class OfferSubscriptionService : IOfferSubscriptionService { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IRoleBaseMailService _roleBaseMailService; /// @@ -51,15 +51,14 @@ public OfferSubscriptionService( IRoleBaseMailService roleBaseMailService) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _roleBaseMailService = roleBaseMailService; } /// public async Task AddOfferSubscriptionAsync(Guid offerId, IEnumerable offerAgreementConsentData, OfferTypeId offerTypeId, string basePortalAddress, IEnumerable notificationRecipients, IEnumerable serviceManagerRoles) { - var identity = _identityService.IdentityData; - var companyInformation = await ValidateCompanyInformationAsync(identity.CompanyId, identity.UserId).ConfigureAwait(false); + var companyInformation = await ValidateCompanyInformationAsync(_identityData.CompanyId, _identityData.IdentityId).ConfigureAwait(false); var offerProviderDetails = await ValidateOfferProviderDetailDataAsync(offerId, offerTypeId).ConfigureAwait(false); if (offerProviderDetails.ProviderCompanyId == null) @@ -71,11 +70,11 @@ public async Task AddOfferSubscriptionAsync(Guid offerId, IEnumerable(); var offerSubscription = offerTypeId == OfferTypeId.APP - ? await HandleAppSubscriptionAsync(offerId, offerSubscriptionsRepository, companyInformation, identity.UserId).ConfigureAwait(false) - : offerSubscriptionsRepository.CreateOfferSubscription(offerId, companyInformation.CompanyId, OfferSubscriptionStatusId.PENDING, identity.UserId); + ? await HandleAppSubscriptionAsync(offerId, offerSubscriptionsRepository, companyInformation, _identityData.IdentityId).ConfigureAwait(false) + : offerSubscriptionsRepository.CreateOfferSubscription(offerId, companyInformation.CompanyId, OfferSubscriptionStatusId.PENDING, _identityData.IdentityId); CreateProcessSteps(offerSubscription); - CreateConsentsForSubscription(offerSubscription.Id, offerAgreementConsentData, companyInformation.CompanyId, identity.UserId); + CreateConsentsForSubscription(offerSubscription.Id, offerAgreementConsentData, companyInformation.CompanyId, _identityData.IdentityId); var content = JsonSerializer.Serialize(new { @@ -85,7 +84,7 @@ public async Task AddOfferSubscriptionAsync(Guid offerId, IEnumerable _logger; /// @@ -69,7 +69,7 @@ public ServiceBusinessLogic( _offerService = offerService; _offerSubscriptionService = offerSubscriptionService; _offerSetupService = offerSetupService; - _identityService = identityService; + _identityData = identityService.IdentityData; _logger = logger; _settings = settings.Value; } @@ -89,7 +89,7 @@ public Task AddServiceSubscription(Guid serviceId, IEnumerable public async Task GetServiceDetailsAsync(Guid serviceId, string lang) { - var result = await _portalRepositories.GetInstance().GetServiceDetailByIdUntrackedAsync(serviceId, lang, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetServiceDetailByIdUntrackedAsync(serviceId, lang, _identityData.CompanyId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"Service {serviceId} does not exist"); @@ -114,7 +114,7 @@ public async Task GetServiceDetailsAsync(Guid serviceId, public async Task GetSubscriptionDetailAsync(Guid subscriptionId) { var subscriptionDetailData = await _portalRepositories.GetInstance() - .GetSubscriptionDetailDataForOwnUserAsync(subscriptionId, _identityService.IdentityData.CompanyId, OfferTypeId.SERVICE).ConfigureAwait(false); + .GetSubscriptionDetailDataForOwnUserAsync(subscriptionId, _identityData.CompanyId, OfferTypeId.SERVICE).ConfigureAwait(false); if (subscriptionDetailData is null) { throw new NotFoundException($"Subscription {subscriptionId} does not exist"); @@ -141,7 +141,7 @@ public Task AutoSetupServiceAsync(OfferAutoSetupData async Task?> GetCompanyProvidedAppSubscriptionStatusData(int skip, int take) { var offerCompanySubscriptionResponse = await _portalRepositories.GetInstance() - .GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identityService.IdentityData.CompanyId, OfferTypeId.SERVICE, sorting, OfferSubscriptionService.GetOfferSubscriptionFilterStatusIds(statusId), offerId)(skip, take).ConfigureAwait(false); + .GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identityData.CompanyId, OfferTypeId.SERVICE, sorting, OfferSubscriptionService.GetOfferSubscriptionFilterStatusIds(statusId), offerId)(skip, take).ConfigureAwait(false); return offerCompanySubscriptionResponse == null ? null @@ -167,7 +167,7 @@ public Task AutoSetupServiceAsync(OfferAutoSetupData async Task?> GetCompanyProvidedServiceStatusData(int skip, int take) { var companyProvidedServiceStatusData = await _portalRepositories.GetInstance() - .GetCompanyProvidedServiceStatusDataAsync(GetOfferStatusIds(statusId), OfferTypeId.SERVICE, _identityService.IdentityData.CompanyId, sorting ?? OfferSorting.DateDesc, offerName)(skip, take).ConfigureAwait(false); + .GetCompanyProvidedServiceStatusDataAsync(GetOfferStatusIds(statusId), OfferTypeId.SERVICE, _identityData.CompanyId, sorting ?? OfferSorting.DateDesc, offerName)(skip, take).ConfigureAwait(false); return companyProvidedServiceStatusData == null ? null diff --git a/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs b/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs index 6923f05d2d..ebe31c50c7 100644 --- a/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs +++ b/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs @@ -41,7 +41,7 @@ public class ServiceReleaseBusinessLogic : IServiceReleaseBusinessLogic private readonly IPortalRepositories _portalRepositories; private readonly IOfferService _offerService; private readonly IOfferDocumentService _offerDocumentService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly ServiceSettings _settings; /// @@ -62,7 +62,7 @@ public ServiceReleaseBusinessLogic( _portalRepositories = portalRepositories; _offerService = offerService; _offerDocumentService = offerDocumentService; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = settings.Value; } @@ -167,7 +167,7 @@ public Task CreateServiceOfferingAsync(ServiceOfferingData data) => /// public async Task UpdateServiceAsync(Guid serviceId, ServiceUpdateRequestData data) { - var companyId = _identityService.IdentityData.CompanyId; + var companyId = _identityData.CompanyId; var serviceData = await _portalRepositories .GetInstance() .GetServiceUpdateData(serviceId, data.ServiceTypeIds, companyId) diff --git a/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs b/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs index f6bee12431..862cb31c31 100644 --- a/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs +++ b/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs @@ -34,7 +34,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Notifications.Service.BusinessLogi public class NotificationBusinessLogic : INotificationBusinessLogic { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly NotificationSettings _settings; /// @@ -46,19 +46,19 @@ public class NotificationBusinessLogic : INotificationBusinessLogic public NotificationBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IOptions settings) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _settings = settings.Value; } /// public Task> GetNotificationsAsync(int page, int size, NotificationFilters filters) => Pagination.CreateResponseAsync(page, size, _settings.MaxPageSize, _portalRepositories.GetInstance() - .GetAllNotificationDetailsByReceiver(_identityService.IdentityId, filters.IsRead, filters.TypeId, filters.TopicId, filters.OnlyDueDate, filters.Sorting ?? NotificationSorting.DateDesc, filters.DoneState, filters.SearchTypeIds, filters.SearchQuery)); + .GetAllNotificationDetailsByReceiver(_identityData.IdentityId, filters.IsRead, filters.TypeId, filters.TopicId, filters.OnlyDueDate, filters.Sorting ?? NotificationSorting.DateDesc, filters.DoneState, filters.SearchTypeIds, filters.SearchQuery)); /// public async Task GetNotificationDetailDataAsync(Guid notificationId) { - var result = await _portalRepositories.GetInstance().GetNotificationByIdAndValidateReceiverAsync(notificationId, _identityService.IdentityId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetNotificationByIdAndValidateReceiverAsync(notificationId, _identityData.IdentityId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"Notification {notificationId} does not exist."); @@ -72,12 +72,12 @@ public async Task GetNotificationDetailDataAsync(Guid no /// public Task GetNotificationCountAsync(bool? isRead) => - _portalRepositories.GetInstance().GetNotificationCountForUserAsync(_identityService.IdentityId, isRead); + _portalRepositories.GetInstance().GetNotificationCountForUserAsync(_identityData.IdentityId, isRead); /// public async Task GetNotificationCountDetailsAsync() { - var details = await _portalRepositories.GetInstance().GetCountDetailsForUserAsync(_identityService.IdentityId).ToListAsync().ConfigureAwait(false); + var details = await _portalRepositories.GetInstance().GetCountDetailsForUserAsync(_identityData.IdentityId).ToListAsync().ConfigureAwait(false); var unreadNotifications = details.Where(x => !x.IsRead); return new NotificationCountDetails( details.Where(x => x.IsRead).Sum(x => x.Count), @@ -116,7 +116,7 @@ public async Task DeleteNotificationAsync(Guid notificationId) private async Task CheckNotificationExistsAndValidateReceiver(Guid notificationId) { - var result = await _portalRepositories.GetInstance().CheckNotificationExistsByIdAndValidateReceiverAsync(notificationId, _identityService.IdentityId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().CheckNotificationExistsByIdAndValidateReceiverAsync(notificationId, _identityData.IdentityId).ConfigureAwait(false); if (result == default || !result.IsNotificationExisting) { throw new NotFoundException($"Notification {notificationId} does not exist."); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyInvitedUserData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyInvitedUserData.cs index 8fec5b10e3..bc35d38d75 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyInvitedUserData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyInvitedUserData.cs @@ -22,6 +22,5 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; public record CompanyInvitedUserData( Guid CompanyUserId, - string? UserEntityId, IEnumerable BusinessPartnerNumbers, IEnumerable RoleIds); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountDetailedData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountDetailedData.cs index b0b9ae6e61..c967e6fa03 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountDetailedData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountDetailedData.cs @@ -24,9 +24,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; public record CompanyServiceAccountDetailedData( Guid ServiceAccountId, - string? ClientId, string? ClientClientId, - string? UserEntityId, string Name, string Description, IEnumerable UserRoleDatas, diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountWithRoleDataClientId.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountWithRoleDataClientId.cs index c5f4b21217..521e0527bc 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountWithRoleDataClientId.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyServiceAccountWithRoleDataClientId.cs @@ -29,6 +29,5 @@ public record CompanyServiceAccountWithRoleDataClientId( string Description, CompanyServiceAccountTypeId CompanyServiceAccountTypeId, Guid? OfferSubscriptionId, - string? ClientId, string? ClientClientId, IEnumerable UserRoleDatas); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserAccountData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserAccountData.cs index bc853699ff..e29c3a932d 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserAccountData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserAccountData.cs @@ -20,4 +20,4 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; -public record CompanyUserAccountData(Guid CompanyUserId, string? UserEntityId, IEnumerable BusinessPartnerNumbers, IEnumerable RoleIds, IEnumerable OfferIds, IEnumerable InvitationIds); +public record CompanyUserAccountData(Guid CompanyUserId, IEnumerable BusinessPartnerNumbers, IEnumerable RoleIds, IEnumerable OfferIds, IEnumerable InvitationIds); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserBusinessPartners.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserBusinessPartners.cs deleted file mode 100644 index aae7ac12c1..0000000000 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserBusinessPartners.cs +++ /dev/null @@ -1,23 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG - * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; - -public record CompanyUserBusinessPartners(string? UserEntityId, IEnumerable AssignedBusinessPartnerNumbers); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserData.cs index 0931b2cdc1..d45b5e2241 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserData.cs @@ -25,15 +25,12 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; public class CompanyUserData { - public CompanyUserData(string userEntityId, Guid companyUserId, UserStatusId userStatusId, IEnumerable roles) + public CompanyUserData(Guid companyUserId, UserStatusId userStatusId, IEnumerable roles) { - UserEntityId = userEntityId; CompanyUserId = companyUserId; UserStatusId = userStatusId; Roles = roles; } - [JsonPropertyName("userEntityId")] - public string UserEntityId { get; set; } [JsonPropertyName("companyUserId")] public Guid CompanyUserId { get; set; } diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserIdentityProviderProcessData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserIdentityProviderProcessData.cs index 20e25ed2ff..0ac8b20fdf 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserIdentityProviderProcessData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserIdentityProviderProcessData.cs @@ -25,7 +25,6 @@ public record CompanyUserIdentityProviderProcessData( string? FirstName, string? LastName, string? Email, - string? UserId, string CompanyName, string? Bpn, IEnumerable ProviderLinkData diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserWithIdpBusinessPartnerData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserWithIdpBusinessPartnerData.cs index 40f6646244..5ce9de8fcb 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserWithIdpBusinessPartnerData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/CompanyUserWithIdpBusinessPartnerData.cs @@ -36,6 +36,5 @@ public record CompanyUserInformation( string? Lastname, string CompanyName, DateTimeOffset DateCreated, - UserStatusId UserStatusId, - string? UserEntityId + UserStatusId UserStatusId ); diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/OfferIamUserData.cs b/src/portalbackend/PortalBackend.DBAccess/Models/OfferIamUserData.cs index a6ae311b86..d745475306 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/OfferIamUserData.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Models/OfferIamUserData.cs @@ -23,7 +23,6 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; public record OfferIamUserData( bool IsValidOffer, IEnumerable IamClientIds, - string? IamUserId, bool IsSameCompany, string? OfferName, string? Firstname, @@ -32,7 +31,6 @@ public record OfferIamUserData( public record CoreOfferIamUserData( bool IsValidOffer, IEnumerable IamClientIds, - string? IamUserId, bool IsSameCompany, string? Firstname, string? Lastname); diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/ApplicationRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/ApplicationRepository.cs index 1bef33eb0f..02a7a5aaed 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/ApplicationRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/ApplicationRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -221,7 +220,6 @@ public IAsyncEnumerable GetInvitedUsersDataByApplication .Where(companyUser => companyUser!.Identity!.UserStatusId == UserStatusId.ACTIVE) .Select(companyUser => new CompanyInvitedUserData( companyUser!.Id, - companyUser.Identity!.UserEntityId, companyUser.CompanyUserAssignedBusinessPartners.Select(companyUserAssignedBusinessPartner => companyUserAssignedBusinessPartner.BusinessPartnerNumber), companyUser.Identity!.IdentityAssignedRoles.Select(companyUserAssignedRole => companyUserAssignedRole.UserRoleId))) .AsAsyncEnumerable(); diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/ConnectorsRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/ConnectorsRepository.cs index 1769a3d807..140dc2727b 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/ConnectorsRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/ConnectorsRepository.cs @@ -63,7 +63,7 @@ public ConnectorsRepository(PortalDbContext portalDbContext) con.CompanyServiceAccountId == null ? null : new TechnicalUserData( con.CompanyServiceAccount!.Id, con.CompanyServiceAccount.Name, - con.CompanyServiceAccount.ClientId!, + con.CompanyServiceAccount.ClientClientId, con.CompanyServiceAccount.Description)) ).SingleOrDefaultAsync(); @@ -89,7 +89,7 @@ public ConnectorsRepository(PortalDbContext portalDbContext) c.CompanyServiceAccountId == default ? null : new TechnicalUserData( c.CompanyServiceAccount!.Id, c.CompanyServiceAccount.Name, - c.CompanyServiceAccount.ClientId!, + c.CompanyServiceAccount.ClientClientId, c.CompanyServiceAccount.Description)) ).SingleOrDefaultAsync(); @@ -111,7 +111,7 @@ public ConnectorsRepository(PortalDbContext portalDbContext) connector.CompanyServiceAccountId == default ? null : new TechnicalUserData( connector.CompanyServiceAccount!.Id, connector.CompanyServiceAccount.Name, - connector.CompanyServiceAccount.ClientId!, + connector.CompanyServiceAccount.ClientClientId, connector.CompanyServiceAccount.Description)), connector.ProviderId == companyId )) diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityProviderRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityProviderRepository.cs index aa40fb0601..9fbf402395 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityProviderRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityProviderRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -21,6 +20,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; + namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; /// @@ -33,7 +33,7 @@ public interface IIdentityProviderRepository CompanyIdentityProvider CreateCompanyIdentityProvider(Guid companyId, Guid identityProviderId); void CreateCompanyIdentityProviders(IEnumerable<(Guid CompanyId, Guid IdentityProviderId)> companyIdIdentityProviderIds); Task GetSharedIdentityProviderIamAliasDataUntrackedAsync(Guid companyId); - Task GetIdpCategoryIdByUserIdAsync(Guid companyUserId, Guid userCompanyId); + Task<(string? Alias, bool IsValidUser)> GetIdpCategoryIdByUserIdAsync(Guid companyUserId, Guid userCompanyId); Task<(string? Alias, IdentityProviderCategoryId IamIdentityProviderCategory, bool IsOwnOrOwnerCompany, IdentityProviderTypeId TypeId)> GetOwnCompanyIdentityProviderAliasUntrackedAsync(Guid identityProviderId, Guid companyId); Task<(string? Alias, IdentityProviderCategoryId IamIdentityProviderCategory, bool IsOwnerCompany, IdentityProviderTypeId TypeId, IEnumerable ConnectedCompanies)> GetOwnIdentityProviderWithConnectedCompanies(Guid identityProviderId, Guid companyId); Task<(bool IsOwner, string? Alias, IdentityProviderCategoryId IdentityProviderCategory, IdentityProviderTypeId IdentityProviderTypeId, IEnumerable<(Guid CompanyId, IEnumerable Aliase)>? CompanyIdAliase)> GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(Guid identityProviderId, Guid companyId, bool queryAliase); @@ -41,7 +41,7 @@ public interface IIdentityProviderRepository IAsyncEnumerable<(Guid IdentityProviderId, string Alias)> GetOwnCompanyIdentityProviderAliasDataUntracked(Guid companyId, IEnumerable identityProviderIds); Task<(Guid IdentityProviderId, string? Alias)> GetSingleManagedIdentityProviderAliasDataUntracked(Guid companyId); IAsyncEnumerable<(Guid IdentityProviderId, string? Alias)> GetManagedIdentityProviderAliasDataUntracked(Guid companyId, IEnumerable identityProviderIds); - Task<(string? UserEntityId, string? Alias, bool IsSameCompany)> GetIamUserIsOwnCompanyIdentityProviderAliasAsync(Guid companyUserId, Guid identityProviderId, Guid companyId); + Task<(bool IsValidUser, string? Alias, bool IsSameCompany)> GetIamUserIsOwnCompanyIdentityProviderAliasAsync(Guid companyUserId, Guid identityProviderId, Guid companyId); Task<((Guid CompanyId, string? CompanyName, string? BusinessPartnerNumber) Company, (Guid CompanyUserId, string? FirstName, string? LastName, string? Email) CompanyUser, IEnumerable<(Guid IdentityProviderId, string Alias)> IdpAliase)> GetCompanyNameIdpAliaseUntrackedAsync(Guid companyUserId, Guid? applicationId, IdentityProviderCategoryId identityProviderCategoryId, IdentityProviderTypeId identityProviderTypeId); diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityRepository.cs index 2e0923f4c8..3834bad891 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IIdentityRepository.cs @@ -17,12 +17,13 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; public interface IIdentityRepository { - Task GetActiveIdentityDataByIdentityId(Guid identityId); - Task GetIdentityIdByUserEntityId(string userEntityId); + Task GetActiveCompanyIdByIdentityId(Guid identityId); + Task<(IdentityTypeId IdentityTypeId, Guid CompanyId)> GetActiveIdentityDataByIdentityId(Guid identityId); + Task<(Guid IdentityId, IdentityTypeId IdentityTypeId, Guid CompanyId)> GetActiveIdentityDataByUserEntityId(string userEntityId); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IInvitationRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IInvitationRepository.cs index 2fb2a59666..e453fb1e5f 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IInvitationRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IInvitationRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -18,13 +17,13 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; public interface IInvitationRepository { - IAsyncEnumerable GetInvitedUserDetailsUntrackedAsync(Guid applicationId); + public IAsyncEnumerable<(InvitationStatusId InvitationStatus, string? EmailId, IEnumerable Roles)> GetInvitedUserDetailsUntrackedAsync(Guid applicationId); Task GetInvitationStatusAsync(Guid companyUserId); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IServiceAccountRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IServiceAccountRepository.cs index 6338e8951c..afb97774c4 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IServiceAccountRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IServiceAccountRepository.cs @@ -30,15 +30,15 @@ public interface IServiceAccountRepository CompanyServiceAccount CreateCompanyServiceAccount(Guid identityId, string name, string description, - string clientId, string clientClientId, CompanyServiceAccountTypeId companyServiceAccountTypeId, Action? setOptionalParameters = null); void AttachAndModifyCompanyServiceAccount(Guid id, Action? initialize, Action modify); Task GetOwnCompanyServiceAccountWithIamClientIdAsync(Guid serviceAccountId, Guid userCompanyId); - Task<(IEnumerable UserRoleIds, Guid? ConnectorId, string? ClientId, ConnectorStatusId? statusId, OfferSubscriptionStatusId? OfferStatusId)> GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(Guid serviceAccountId, Guid companyId); + Task<(IEnumerable UserRoleIds, Guid? ConnectorId, string? ClientClientId, ConnectorStatusId? statusId, OfferSubscriptionStatusId? OfferStatusId)> GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(Guid serviceAccountId, Guid companyId); Task GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(Guid serviceAccountId, Guid companyId); Func?>> GetOwnCompanyServiceAccountsUntracked(Guid userCompanyId, string? clientId, bool? isOwner, UserStatusId userStatusId); Task CheckActiveServiceAccountExistsForCompanyAsync(Guid technicalUserId, Guid companyId); + public Task<(Guid IdentityId, Guid CompanyId)> GetServiceAccountDataByClientId(string clientId); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserBusinessPartnerRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserBusinessPartnerRepository.cs index 76528c9624..25c8a1e815 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserBusinessPartnerRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserBusinessPartnerRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -27,5 +26,5 @@ public interface IUserBusinessPartnerRepository CompanyUserAssignedBusinessPartner CreateCompanyUserAssignedBusinessPartner(Guid companyUserId, string businessPartnerNumber); CompanyUserAssignedBusinessPartner DeleteCompanyUserAssignedBusinessPartner(Guid companyUserId, string businessPartnerNumber); void DeleteCompanyUserAssignedBusinessPartners(IEnumerable<(Guid CompanyUserId, string BusinessPartnerNumber)> companyUserAssignedBusinessPartnerIds); - Task<(string? UserEntityId, bool IsAssignedBusinessPartner, bool IsValidUser)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(Guid companyUserId, Guid userCompanyId, string businessPartnerNumber); + Task<(bool IsValidUser, bool IsAssignedBusinessPartner, bool IsSameCompany)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(Guid companyUserId, Guid userCompanyId, string businessPartnerNumber); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRepository.cs index 13212aa7ce..a504084649 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -35,12 +34,12 @@ public interface IUserRepository CompanyUser CreateCompanyUser(Guid identityId, string? firstName, string? lastName, string email); Identity CreateIdentity(Guid companyId, UserStatusId userStatusId, IdentityTypeId identityTypeId, Action? setOptionalFields); void AttachAndModifyCompanyUser(Guid companyUserId, Action? initialize, Action setOptionalParameters); - IQueryable GetOwnCompanyUserQuery(Guid companyId, Guid? companyUserId = null, string? userEntityId = null, string? firstName = null, string? lastName = null, string? email = null, IEnumerable? statusIds = null); - Task<(string UserEntityId, string? FirstName, string? LastName, string? Email)> GetUserEntityDataAsync(Guid companyUserId, Guid companyId); - IAsyncEnumerable<(string? UserEntityId, Guid CompanyUserId)> GetMatchingCompanyIamUsersByNameEmail(string firstName, string lastName, string email, Guid companyId, IEnumerable companyUserStatusIds); + IQueryable GetOwnCompanyUserQuery(Guid companyId, Guid? companyUserId = null, string? firstName = null, string? lastName = null, string? email = null, IEnumerable? statusIds = null); + Task<(string? FirstName, string? LastName, string? Email)> GetUserEntityDataAsync(Guid companyUserId, Guid companyId); + IAsyncEnumerable<(Guid CompanyUserId, bool IsFullMatch)> GetMatchingCompanyIamUsersByNameEmail(string firstName, string lastName, string email, Guid companyId, IEnumerable companyUserStatusIds); Task IsOwnCompanyUserWithEmailExisting(string email, Guid companyId); Task GetOwnCompanyUserDetailsUntrackedAsync(Guid companyUserId, Guid companyId); - Task GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(Guid companyUserId, Guid companyId); + Task<(IEnumerable AssignedBusinessPartnerNumbers, bool IsValidUser)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(Guid companyUserId, Guid companyId); Task GetUserDetailsUntrackedAsync(Guid companyUserId, IEnumerable userRoleIds); Task GetUserWithCompanyIdpAsync(Guid companyUserId); @@ -86,7 +85,7 @@ public interface IUserRepository /// User account data for deletion of own userId /// /// - /// SharedIdpAlias, CompanyUserId, UserEntityId, BusinessPartnerNumbers, RoleIds, OfferIds, InvitationIds + /// SharedIdpAlias, CompanyUserId, BusinessPartnerNumbers, RoleIds, OfferIds, InvitationIds Task<(string? SharedIdpAlias, CompanyUserAccountData AccountData)> GetSharedIdentityProviderUserAccountDataUntrackedAsync(Guid companyUserId); /// @@ -94,7 +93,7 @@ public interface IUserRepository /// /// /// - /// CompanyUserId, UserEntityId, BusinessPartnerNumbers, RoleIds, OfferIds, InvitationIds + /// CompanyUserId, BusinessPartnerNumbers, RoleIds, OfferIds, InvitationIds IAsyncEnumerable GetCompanyUserAccountDataUntrackedAsync(IEnumerable companyUserIds, Guid companyId); /// diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs index d5d838d9ad..732ecbc8c5 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IUserRolesRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -69,6 +68,6 @@ public interface IUserRolesRepository IAsyncEnumerable<(string ClientClientId, IEnumerable<(Guid UserRoleId, string UserRoleText)> UserRoles)> GetUserRolesByClientId(IEnumerable iamClientIds); - IAsyncEnumerable<(Guid CompanyUserId, string UserEntityId, IEnumerable UserRoleIds)> GetUserWithUserRolesForApplicationId(Guid applicationId, IEnumerable userRoleIds); + IAsyncEnumerable<(Guid CompanyUserId, IEnumerable UserRoleIds)> GetUserWithUserRolesForApplicationId(Guid applicationId, IEnumerable userRoleIds); IAsyncEnumerable GetRolesForClient(string technicalUserProfileClient); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityProviderRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityProviderRepository.cs index f6ec7db2a8..e6d03f36e4 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityProviderRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityProviderRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -84,18 +83,17 @@ public IamIdentityProvider CreateIamIdentityProvider(Guid identityProviderId, st .Select(identityProvider => identityProvider.IamIdentityProvider!.IamIdpAlias) .SingleOrDefaultAsync(); - public Task GetIdpCategoryIdByUserIdAsync(Guid companyUserId, Guid userCompanyId) => + public Task<(string? Alias, bool IsValidUser)> GetIdpCategoryIdByUserIdAsync(Guid companyUserId, Guid userCompanyId) => _context.CompanyUsers.AsNoTracking() .Where(companyUser => companyUser.Id == companyUserId && companyUser.Identity!.CompanyId == userCompanyId) - .Select(companyUser => new IdpUser - { - TargetIamUserId = companyUser.Identity!.UserEntityId, - IdpName = companyUser.Identity!.Company!.IdentityProviders + .Select(companyUser => new ValueTuple( + companyUser.Identity!.Company!.IdentityProviders .Where(identityProvider => identityProvider.IdentityProviderTypeId == IdentityProviderTypeId.SHARED) .Select(identityProvider => identityProvider.IamIdentityProvider!.IamIdpAlias) - .SingleOrDefault() - }).SingleOrDefaultAsync(); + .SingleOrDefault(), + true)) + .SingleOrDefaultAsync(); public Task<(string? Alias, IdentityProviderCategoryId IamIdentityProviderCategory, bool IsOwnOrOwnerCompany, IdentityProviderTypeId TypeId)> GetOwnCompanyIdentityProviderAliasUntrackedAsync(Guid identityProviderId, Guid companyId) => _context.IdentityProviders @@ -185,12 +183,12 @@ public IamIdentityProvider CreateIamIdentityProvider(Guid identityProviderId, st )) .ToAsyncEnumerable(); - public Task<(string? UserEntityId, string? Alias, bool IsSameCompany)> GetIamUserIsOwnCompanyIdentityProviderAliasAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) => + public Task<(bool IsValidUser, string? Alias, bool IsSameCompany)> GetIamUserIsOwnCompanyIdentityProviderAliasAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) => _context.CompanyUsers .AsNoTracking() .Where(companyUser => companyUser.Id == companyUserId) - .Select(companyUser => new ValueTuple( - companyUser.Identity!.UserEntityId, + .Select(companyUser => new ValueTuple( + true, companyUser.Identity!.Company!.IdentityProviders .Where(identityProvider => identityProvider.Id == identityProviderId) .Select(identityProvider => identityProvider.IamIdentityProvider!.IamIdpAlias) diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityRepository.cs index fb4e161d58..ca4fe06768 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/IdentityRepository.cs @@ -20,7 +20,6 @@ using Microsoft.EntityFrameworkCore; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; @@ -32,14 +31,23 @@ public IdentityRepository(PortalDbContext context) { _context = context; } + public Task GetActiveCompanyIdByIdentityId(Guid identityId) => + _context.Identities.Where(x => x.Id == identityId && x.UserEntityId != null && x.UserStatusId == UserStatusId.ACTIVE) + .Select(x => x.CompanyId) + .SingleOrDefaultAsync(); - public Task GetActiveIdentityDataByIdentityId(Guid identityId) => + public Task<(IdentityTypeId IdentityTypeId, Guid CompanyId)> GetActiveIdentityDataByIdentityId(Guid identityId) => _context.Identities.Where(x => x.Id == identityId && x.UserEntityId != null && x.UserStatusId == UserStatusId.ACTIVE) - .Select(x => new IdentityData(x.UserEntityId!, x.Id, x.IdentityTypeId, x.CompanyId)) + .Select(x => new ValueTuple( + x.IdentityTypeId, + x.CompanyId)) .SingleOrDefaultAsync(); - public Task GetIdentityIdByUserEntityId(string userEntityId) => - _context.Identities.Where(x => x.UserEntityId == userEntityId) - .Select(x => x.Id) + public Task<(Guid IdentityId, IdentityTypeId IdentityTypeId, Guid CompanyId)> GetActiveIdentityDataByUserEntityId(string userEntityId) => + _context.Identities.Where(x => x.UserEntityId == userEntityId && x.UserStatusId == UserStatusId.ACTIVE) + .Select(x => new ValueTuple( + x.Id, + x.IdentityTypeId, + x.CompanyId)) .SingleOrDefaultAsync(); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/InvitationRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/InvitationRepository.cs index 1a435a024c..34e9622895 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/InvitationRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/InvitationRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -19,7 +18,6 @@ ********************************************************************************/ using Microsoft.EntityFrameworkCore; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; @@ -34,16 +32,16 @@ public InvitationRepository(PortalDbContext dbContext) { _dbContext = dbContext; } - public IAsyncEnumerable GetInvitedUserDetailsUntrackedAsync(Guid applicationId) => + public IAsyncEnumerable<(InvitationStatusId InvitationStatus, string? EmailId, IEnumerable Roles)> GetInvitedUserDetailsUntrackedAsync(Guid applicationId) => _dbContext.Invitations .AsNoTracking() .Where(invitation => invitation.CompanyApplicationId == applicationId && invitation.CompanyUser!.Identity!.UserStatusId != UserStatusId.DELETED) - .Select(invitation => new InvitedUserDetail( - invitation.CompanyUser!.Identity!.UserEntityId, + .Select(invitation => new ValueTuple>( invitation.InvitationStatusId, - invitation.CompanyUser.Email)) + invitation.CompanyUser!.Email, + invitation.CompanyUser.Identity!.IdentityAssignedRoles.Select(role => role.UserRole!.UserRoleText))) .AsAsyncEnumerable(); public Task GetInvitationStatusAsync(Guid companyUserId) => diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/OfferSubscriptionsRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/OfferSubscriptionsRepository.cs index e5aa42c4a6..45115b49c2 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/OfferSubscriptionsRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/OfferSubscriptionsRepository.cs @@ -453,7 +453,7 @@ public Task GetOfferSubscriptionDataForProcessIdAsync(Guid processId) => _context.OfferSubscriptions .Where(x => x.Id == offerSubscriptionId) .Select(x => new ValueTuple, string?, string?, OfferSubscriptionStatusId>( - x.CompanyServiceAccounts.Select(sa => new ValueTuple(sa.Id, sa.ClientId)), + x.CompanyServiceAccounts.Select(sa => new ValueTuple(sa.Id, sa.ClientClientId)), x.AppSubscriptionDetail!.AppInstance!.IamClient!.ClientClientId, x.Offer!.ProviderCompany!.ProviderCompanyDetail!.AutoSetupCallbackUrl, x.OfferSubscriptionStatusId diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/ServiceAccountRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/ServiceAccountRepository.cs index e1779f35e2..0581bf3962 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/ServiceAccountRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/ServiceAccountRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -41,7 +40,6 @@ public CompanyServiceAccount CreateCompanyServiceAccount( Guid identityId, string name, string description, - string clientId, string clientClientId, CompanyServiceAccountTypeId companyServiceAccountTypeId, Action? setOptionalParameters = null) @@ -52,7 +50,6 @@ public CompanyServiceAccount CreateCompanyServiceAccount( description, companyServiceAccountTypeId) { - ClientId = clientId, ClientClientId = clientClientId }; setOptionalParameters?.Invoke(entity); @@ -87,7 +84,6 @@ public void AttachAndModifyCompanyServiceAccount( serviceAccount.Description, serviceAccount.CompanyServiceAccountTypeId, serviceAccount.OfferSubscriptionId, - serviceAccount.ClientId, serviceAccount.ClientClientId, serviceAccount.Identity!.IdentityAssignedRoles .Select(assignedRole => assignedRole.UserRole) @@ -97,7 +93,7 @@ public void AttachAndModifyCompanyServiceAccount( userRole.UserRoleText)))) .SingleOrDefaultAsync(); - public Task<(IEnumerable UserRoleIds, Guid? ConnectorId, string? ClientId, ConnectorStatusId? statusId, OfferSubscriptionStatusId? OfferStatusId)> GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(Guid serviceAccountId, Guid companyId) => + public Task<(IEnumerable UserRoleIds, Guid? ConnectorId, string? ClientClientId, ConnectorStatusId? statusId, OfferSubscriptionStatusId? OfferStatusId)> GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(Guid serviceAccountId, Guid companyId) => _dbContext.CompanyServiceAccounts .Where(serviceAccount => serviceAccount.Id == serviceAccountId && @@ -106,7 +102,7 @@ public void AttachAndModifyCompanyServiceAccount( .Select(sa => new ValueTuple, Guid?, string?, ConnectorStatusId?, OfferSubscriptionStatusId?>( sa.Identity!.IdentityAssignedRoles.Select(r => r.UserRoleId), sa.Connector!.Id, - sa.ClientId, + sa.ClientClientId, sa.Connector!.StatusId, sa.OfferSubscription!.OfferSubscriptionStatusId)) .SingleOrDefaultAsync(); @@ -120,12 +116,10 @@ public void AttachAndModifyCompanyServiceAccount( (serviceAccount.CompaniesLinkedServiceAccount!.Owners == companyId || serviceAccount.CompaniesLinkedServiceAccount!.Provider == companyId)) .Select(serviceAccount => new CompanyServiceAccountDetailedData( serviceAccount.Id, - serviceAccount.ClientId, serviceAccount.ClientClientId, - serviceAccount.Identity!.UserEntityId, serviceAccount.Name, serviceAccount.Description, - serviceAccount.Identity.IdentityAssignedRoles + serviceAccount.Identity!.IdentityAssignedRoles .Select(assignedRole => assignedRole.UserRole) .Select(userRole => new UserRoleData( userRole!.Id, @@ -195,4 +189,12 @@ public Task CheckActiveServiceAccountExistsForCompanyAsync(Guid technicalU sa.Identity!.UserStatusId == UserStatusId.ACTIVE && sa.Identity.CompanyId == companyId) .AnyAsync(); + + public Task<(Guid IdentityId, Guid CompanyId)> GetServiceAccountDataByClientId(string clientId) => + _dbContext.CompanyServiceAccounts + .Where(sa => sa.ClientClientId == clientId) + .Select(sa => new ValueTuple( + sa.Id, + sa.Identity!.CompanyId)) + .SingleOrDefaultAsync(); } diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserBusinessPartnerRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserBusinessPartnerRepository.cs index 8536954c87..d8e8bd9c98 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserBusinessPartnerRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserBusinessPartnerRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -56,12 +55,12 @@ public CompanyUserAssignedBusinessPartner DeleteCompanyUserAssignedBusinessPartn public void DeleteCompanyUserAssignedBusinessPartners(IEnumerable<(Guid CompanyUserId, string BusinessPartnerNumber)> companyUserAssignedBusinessPartnerIds) => _dbContext.RemoveRange(companyUserAssignedBusinessPartnerIds.Select(ids => new CompanyUserAssignedBusinessPartner(ids.CompanyUserId, ids.BusinessPartnerNumber))); - public Task<(string? UserEntityId, bool IsAssignedBusinessPartner, bool IsValidUser)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(Guid companyUserId, Guid userCompanyId, string businessPartnerNumber) => + public Task<(bool IsValidUser, bool IsAssignedBusinessPartner, bool IsSameCompany)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(Guid companyUserId, Guid userCompanyId, string businessPartnerNumber) => _dbContext.CompanyUsers .AsNoTracking() .Where(companyUser => companyUser.Id == companyUserId) - .Select(companyUser => new ValueTuple( - companyUser.Identity!.UserEntityId, + .Select(companyUser => new ValueTuple( + true, companyUser.CompanyUserAssignedBusinessPartners!.Any(assignedPartner => assignedPartner.BusinessPartnerNumber == businessPartnerNumber), companyUser.Identity!.CompanyId == userCompanyId )) diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRepository.cs index f912026c04..784ea3d85c 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -86,7 +85,6 @@ public void AttachAndModifyCompanyUser(Guid companyUserId, Action? public IQueryable GetOwnCompanyUserQuery( Guid companyId, Guid? companyUserId = null, - string? userEntityId = null, string? firstName = null, string? lastName = null, string? email = null, @@ -95,7 +93,6 @@ public IQueryable GetOwnCompanyUserQuery( return _dbContext.CompanyUsers .AsNoTracking() .Where(companyUser => companyUser.Identity!.CompanyId == companyId && - (userEntityId == null || companyUser.Identity!.UserEntityId == userEntityId) && (!companyUserId.HasValue || companyUser.Id == companyUserId.Value) && (firstName == null || companyUser.Firstname == firstName) && (lastName == null || companyUser.Lastname == lastName) && @@ -103,20 +100,18 @@ public IQueryable GetOwnCompanyUserQuery( (statusIds == null || statusIds.Contains(companyUser.Identity!.UserStatusId))); } - public Task<(string UserEntityId, string? FirstName, string? LastName, string? Email)> GetUserEntityDataAsync(Guid companyUserId, Guid companyId) => + public Task<(string? FirstName, string? LastName, string? Email)> GetUserEntityDataAsync(Guid companyUserId, Guid companyId) => _dbContext.CompanyUsers .AsNoTracking() .Where(companyUser => companyUser.Id == companyUserId && - companyUser.Identity!.CompanyId == companyId && - companyUser.Identity!.UserEntityId != null) - .Select(companyUser => new ValueTuple( - companyUser.Identity!.UserEntityId!, + companyUser.Identity!.CompanyId == companyId) + .Select(companyUser => new ValueTuple( companyUser.Firstname, companyUser.Lastname, companyUser.Email)) .SingleOrDefaultAsync(); - public IAsyncEnumerable<(string? UserEntityId, Guid CompanyUserId)> GetMatchingCompanyIamUsersByNameEmail(string firstName, string lastName, string email, Guid companyId, IEnumerable companyUserStatusIds) => + public IAsyncEnumerable<(Guid CompanyUserId, bool IsFullMatch)> GetMatchingCompanyIamUsersByNameEmail(string firstName, string lastName, string email, Guid companyId, IEnumerable companyUserStatusIds) => _dbContext.CompanyUsers .AsNoTracking() .Where(companyUser => @@ -126,11 +121,9 @@ public IQueryable GetOwnCompanyUserQuery( (companyUser.Email == email || companyUser.Firstname == firstName || companyUser.Lastname == lastName)) - .Select(companyUser => new ValueTuple( - companyUser.Identity!.UserEntityId, - companyUser.Firstname == firstName && companyUser.Lastname == lastName && companyUser.Email == email - ? companyUser.Id - : Guid.Empty)) + .Select(companyUser => new ValueTuple( + companyUser.Id, + companyUser.Firstname == firstName && companyUser.Lastname == lastName && companyUser.Email == email)) .AsAsyncEnumerable(); public Task IsOwnCompanyUserWithEmailExisting(string email, Guid companyId) => @@ -164,17 +157,17 @@ public Task IsOwnCompanyUserWithEmailExisting(string email, Guid companyId }) .SingleOrDefaultAsync(); - public Task GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(Guid companyUserId, Guid companyId) => + public Task<(IEnumerable AssignedBusinessPartnerNumbers, bool IsValidUser)> GetOwnCompanyUserWithAssignedBusinessPartnerNumbersUntrackedAsync(Guid companyUserId, Guid companyId) => _dbContext.CompanyUsers .AsNoTracking() .Where(companyUser => companyUser.Id == companyUserId && companyUser.Identity!.CompanyId == companyId) - .Select(companyUser => new CompanyUserBusinessPartners( - companyUser.Identity!.UserEntityId, + .Select(companyUser => new ValueTuple, bool>( companyUser.CompanyUserAssignedBusinessPartners.Select(assignedPartner => - assignedPartner.BusinessPartnerNumber) - )) + assignedPartner.BusinessPartnerNumber), + true) + ) .SingleOrDefaultAsync(); public Task GetUserDetailsUntrackedAsync(Guid companyUserId, IEnumerable userRoleIds) => @@ -222,8 +215,7 @@ public Task IsOwnCompanyUserWithEmailExisting(string email, Guid companyId companyUser.Lastname, companyUser.Identity!.Company!.Name, companyUser.Identity.DateCreated, - companyUser.Identity.UserStatusId, - companyUser.Identity.UserEntityId), + companyUser.Identity.UserStatusId), companyUser.Identity!.Company!.IdentityProviders.Where(identityProvider => identityProvider.IdentityProviderTypeId == IdentityProviderTypeId.SHARED) .Select(identityProvider => identityProvider.IamIdentityProvider!.IamIdpAlias) @@ -289,7 +281,6 @@ public IAsyncEnumerable GetCompanyUserWithRoleId(IEnumerable userRol .Select(x => new OfferIamUserData( x.Subscriptions.Any(), x.Subscriptions.Select(subscription => subscription.AppSubscriptionDetail!.AppInstance!.IamClient!.ClientClientId).Distinct(), - x.User.Identity!.UserEntityId, x.User.Identity!.CompanyId == companyId, x.Subscriptions.Select(s => s.Offer!.Name).FirstOrDefault(), x.User.Firstname, @@ -311,7 +302,6 @@ public IAsyncEnumerable GetCompanyUserWithRoleId(IEnumerable userRol .Select(x => new CoreOfferIamUserData( x.Offer != null, x.Offer!.AppInstances.Select(instance => instance.IamClient!.ClientClientId), - x.User.Identity!.UserEntityId, x.User.Identity!.CompanyId == companyId, x.User.Firstname, x.User.Lastname)) @@ -374,7 +364,6 @@ public IAsyncEnumerable GetServiceProviderCompanyUserWithRoleIdAsync(Guid companyUser.Identity!.Company!.IdentityProviders.SingleOrDefault(identityProvider => identityProvider.IdentityProviderTypeId == IdentityProviderTypeId.SHARED)!.IamIdentityProvider!.IamIdpAlias, new CompanyUserAccountData( companyUser.Id, - companyUser.Identity!.UserEntityId, companyUser.CompanyUserAssignedBusinessPartners.Select(assignedPartner => assignedPartner.BusinessPartnerNumber), companyUser.Identity!.IdentityAssignedRoles.Select(assignedRole => @@ -390,7 +379,6 @@ public IAsyncEnumerable GetCompanyUserAccountDataUntrack companyUser.Identity!.Company!.Id == companyId) .Select(companyUser => new CompanyUserAccountData( companyUser.Id, - companyUser.Identity!.UserEntityId, companyUser.CompanyUserAssignedBusinessPartners.Select(assignedPartner => assignedPartner.BusinessPartnerNumber), companyUser.Identity!.IdentityAssignedRoles.Select(assignedRole => @@ -453,8 +441,7 @@ public IAsyncEnumerable GetUserAssignedI cu.Firstname, cu.Lastname, cu.Email, - cu.Identity!.UserEntityId, - cu.Identity.Company!.Name, + cu.Identity!.Company!.Name, cu.Identity.Company.BusinessPartnerNumber, cu.CompanyUserAssignedIdentityProviders.Select(assigned => new ProviderLinkData(assigned.UserName, assigned.IdentityProvider!.IamIdentityProvider!.IamIdpAlias, assigned.ProviderId)) )) diff --git a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs index 5746bf9713..29f8f3f6b1 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs +++ b/src/portalbackend/PortalBackend.DBAccess/Repositories/UserRolesRepository.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -245,16 +244,14 @@ public async IAsyncEnumerable GetUserDataByAssignedRoles(Gu instance.App!.UserRoles.Select(role => new ValueTuple(role.Id, role.UserRoleText)))) .ToAsyncEnumerable(); - public IAsyncEnumerable<(Guid CompanyUserId, string UserEntityId, IEnumerable UserRoleIds)> GetUserWithUserRolesForApplicationId(Guid applicationId, IEnumerable userRoleIds) => + public IAsyncEnumerable<(Guid CompanyUserId, IEnumerable UserRoleIds)> GetUserWithUserRolesForApplicationId(Guid applicationId, IEnumerable userRoleIds) => _dbContext.CompanyApplications .AsNoTracking() .Where(application => application.Id == applicationId) .SelectMany(application => application.Company!.Identities) - .Where(user => user.IdentityAssignedRoles.Any(assigned => userRoleIds.Contains(assigned.UserRoleId)) && - user.UserEntityId != null) - .Select(user => new ValueTuple>( + .Where(user => user.IdentityAssignedRoles.Any(assigned => userRoleIds.Contains(assigned.UserRoleId))) + .Select(user => new ValueTuple>( user.Id, - user.UserEntityId!, user.IdentityAssignedRoles.Where(assigned => userRoleIds.Contains(assigned.UserRoleId)).Select(assigned => assigned.UserRoleId))) .ToAsyncEnumerable(); diff --git a/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.Designer.cs b/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.Designer.cs new file mode 100644 index 0000000000..d741786eb1 --- /dev/null +++ b/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.Designer.cs @@ -0,0 +1,8766 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +// +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities; + +#nullable disable + +namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.Migrations.Migrations +{ + [DbContext(typeof(PortalDbContext))] + [Migration("20231213195802_CPLP-3091-remove-keycloak-identity-links")] + partial class CPLP3091removekeycloakidentitylinks + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasDefaultSchema("portal") + .UseCollation("en_US.utf8") + .HasAnnotation("ProductVersion", "7.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditAppSubscriptionDetail20221118", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AppInstanceId") + .HasColumnType("uuid") + .HasColumnName("app_instance_id"); + + b.Property("AppSubscriptionUrl") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("app_subscription_url"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_app_subscription_detail20221118"); + + b.ToTable("audit_app_subscription_detail20221118", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditAppSubscriptionDetail20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AppInstanceId") + .HasColumnType("uuid") + .HasColumnName("app_instance_id"); + + b.Property("AppSubscriptionUrl") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("app_subscription_url"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_app_subscription_detail20231115"); + + b.ToTable("audit_app_subscription_detail20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyApplication20221005", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("ApplicationStatusId") + .HasColumnType("integer") + .HasColumnName("application_status_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_application20221005"); + + b.ToTable("audit_company_application20221005", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyApplication20230214", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("ApplicationStatusId") + .HasColumnType("integer") + .HasColumnName("application_status_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ChecklistProcessId") + .HasColumnType("uuid") + .HasColumnName("checklist_process_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_application20230214"); + + b.ToTable("audit_company_application20230214", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyApplication20230824", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("ApplicationStatusId") + .HasColumnType("integer") + .HasColumnName("application_status_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ChecklistProcessId") + .HasColumnType("uuid") + .HasColumnName("checklist_process_id"); + + b.Property("CompanyApplicationTypeId") + .HasColumnType("integer") + .HasColumnName("company_application_type_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OnboardingServiceProviderId") + .HasColumnType("uuid") + .HasColumnName("onboarding_service_provider_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_application20230824"); + + b.ToTable("audit_company_application20230824", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyApplication20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("ApplicationStatusId") + .HasColumnType("integer") + .HasColumnName("application_status_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ChecklistProcessId") + .HasColumnType("uuid") + .HasColumnName("checklist_process_id"); + + b.Property("CompanyApplicationTypeId") + .HasColumnType("integer") + .HasColumnName("company_application_type_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OnboardingServiceProviderId") + .HasColumnType("uuid") + .HasColumnName("onboarding_service_provider_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_application20231115"); + + b.ToTable("audit_company_application20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyAssignedRole2023316", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_assigned_role2023316"); + + b.ToTable("audit_company_assigned_role2023316", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanySsiDetail20230621", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanySsiDetailStatusId") + .HasColumnType("integer") + .HasColumnName("company_ssi_detail_status_id"); + + b.Property("CreatorUserId") + .HasColumnType("uuid") + .HasColumnName("creator_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("ExpiryDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiry_date"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("VerifiedCredentialExternalTypeUseCaseDetailId") + .HasColumnType("uuid") + .HasColumnName("verified_credential_external_type_use_case_detail_id"); + + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_ssi_detail20230621"); + + b.ToTable("audit_company_ssi_detail20230621", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanySsiDetail20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanySsiDetailStatusId") + .HasColumnType("integer") + .HasColumnName("company_ssi_detail_status_id"); + + b.Property("CreatorUserId") + .HasColumnType("uuid") + .HasColumnName("creator_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("ExpiryDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiry_date"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("VerifiedCredentialExternalTypeUseCaseDetailId") + .HasColumnType("uuid") + .HasColumnName("verified_credential_external_type_use_case_detail_id"); + + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_ssi_detail20231115"); + + b.ToTable("audit_company_ssi_detail20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyUser20221005", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyUserStatusId") + .HasColumnType("integer") + .HasColumnName("company_user_status_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Email") + .HasColumnType("text") + .HasColumnName("email"); + + b.Property("Firstname") + .HasColumnType("text") + .HasColumnName("firstname"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Lastlogin") + .HasColumnType("bytea") + .HasColumnName("lastlogin"); + + b.Property("Lastname") + .HasColumnType("text") + .HasColumnName("lastname"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_user20221005"); + + b.ToTable("audit_company_user20221005", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyUser20230522", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Email") + .HasColumnType("text") + .HasColumnName("email"); + + b.Property("Firstname") + .HasColumnType("text") + .HasColumnName("firstname"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Lastlogin") + .HasColumnType("bytea") + .HasColumnName("lastlogin"); + + b.Property("Lastname") + .HasColumnType("text") + .HasColumnName("lastname"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_user20230523"); + + b.ToTable("audit_company_user20230523", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditCompanyUserAssignedRole20221018", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_company_user_assigned_role20221018"); + + b.ToTable("audit_company_user_assigned_role20221018", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConnector20230405", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ConnectorUrl") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("connector_url"); + + b.Property("DapsRegistrationSuccessful") + .HasColumnType("boolean") + .HasColumnName("daps_registration_successful"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("HostId") + .HasColumnType("uuid") + .HasColumnName("host_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LocationId") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)") + .HasColumnName("location_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("ProviderId") + .HasColumnType("uuid") + .HasColumnName("provider_id"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("SelfDescriptionMessage") + .HasColumnType("text") + .HasColumnName("self_description_message"); + + b.Property("StatusId") + .HasColumnType("integer") + .HasColumnName("status_id"); + + b.Property("TypeId") + .HasColumnType("integer") + .HasColumnName("type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_connector20230405"); + + b.ToTable("audit_connector20230405", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConnector20230503", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("company_service_account_id"); + + b.Property("ConnectorUrl") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("connector_url"); + + b.Property("DapsRegistrationSuccessful") + .HasColumnType("boolean") + .HasColumnName("daps_registration_successful"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("HostId") + .HasColumnType("uuid") + .HasColumnName("host_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LocationId") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)") + .HasColumnName("location_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("ProviderId") + .HasColumnType("uuid") + .HasColumnName("provider_id"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("SelfDescriptionMessage") + .HasColumnType("text") + .HasColumnName("self_description_message"); + + b.Property("StatusId") + .HasColumnType("integer") + .HasColumnName("status_id"); + + b.Property("TypeId") + .HasColumnType("integer") + .HasColumnName("type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_connector20230503"); + + b.ToTable("audit_connector20230503", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConnector20230803", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("company_service_account_id"); + + b.Property("ConnectorUrl") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("connector_url"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("HostId") + .HasColumnType("uuid") + .HasColumnName("host_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LocationId") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character varying(2)") + .HasColumnName("location_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("ProviderId") + .HasColumnType("uuid") + .HasColumnName("provider_id"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("SelfDescriptionMessage") + .HasColumnType("text") + .HasColumnName("self_description_message"); + + b.Property("StatusId") + .HasColumnType("integer") + .HasColumnName("status_id"); + + b.Property("TypeId") + .HasColumnType("integer") + .HasColumnName("type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_connector20230803"); + + b.ToTable("audit_connector20230803", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConnector20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("company_service_account_id"); + + b.Property("ConnectorUrl") + .HasColumnType("text") + .HasColumnName("connector_url"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("HostId") + .HasColumnType("uuid") + .HasColumnName("host_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LocationId") + .HasColumnType("text") + .HasColumnName("location_id"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("ProviderId") + .HasColumnType("uuid") + .HasColumnName("provider_id"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("SelfDescriptionMessage") + .HasColumnType("text") + .HasColumnName("self_description_message"); + + b.Property("StatusId") + .HasColumnType("integer") + .HasColumnName("status_id"); + + b.Property("TypeId") + .HasColumnType("integer") + .HasColumnName("type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_connector20231115"); + + b.ToTable("audit_connector20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConsent20230412", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Comment") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("comment"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("ConsentStatusId") + .HasColumnType("integer") + .HasColumnName("consent_status_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Target") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("target"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_consent20230412"); + + b.ToTable("audit_consent20230412", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditConsent20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Comment") + .HasColumnType("text") + .HasColumnName("comment"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("ConsentStatusId") + .HasColumnType("integer") + .HasColumnName("consent_status_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Target") + .HasColumnType("text") + .HasColumnName("target"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_consent20231115"); + + b.ToTable("audit_consent20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditDocument20231108", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentContent") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("document_content"); + + b.Property("DocumentHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("document_hash"); + + b.Property("DocumentName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("document_name"); + + b.Property("DocumentStatusId") + .HasColumnType("integer") + .HasColumnName("document_status_id"); + + b.Property("DocumentTypeId") + .HasColumnType("integer") + .HasColumnName("document_type_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("MediaTypeId") + .HasColumnType("integer") + .HasColumnName("media_type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_document20231108"); + + b.ToTable("audit_document20231108", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditDocument20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentContent") + .HasColumnType("bytea") + .HasColumnName("document_content"); + + b.Property("DocumentHash") + .HasColumnType("bytea") + .HasColumnName("document_hash"); + + b.Property("DocumentName") + .HasColumnType("text") + .HasColumnName("document_name"); + + b.Property("DocumentStatusId") + .HasColumnType("integer") + .HasColumnName("document_status_id"); + + b.Property("DocumentTypeId") + .HasColumnType("integer") + .HasColumnName("document_type_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("MediaTypeId") + .HasColumnType("integer") + .HasColumnName("media_type_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_document20231115"); + + b.ToTable("audit_document20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditIdentity20230526", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("IdentityTypeId") + .HasColumnType("integer") + .HasColumnName("identity_type_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("UserEntityId") + .HasMaxLength(36) + .HasColumnType("character varying(36)") + .HasColumnName("user_entity_id"); + + b.Property("UserStatusId") + .HasColumnType("integer") + .HasColumnName("user_status_id") + .HasAnnotation("Relational:JsonPropertyName", "user_status_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_identity20230526"); + + b.ToTable("audit_identity20230526", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditIdentity20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("IdentityTypeId") + .HasColumnType("integer") + .HasColumnName("identity_type_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("UserEntityId") + .HasColumnType("text") + .HasColumnName("user_entity_id"); + + b.Property("UserStatusId") + .HasColumnType("integer") + .HasColumnName("user_status_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_identity20231115"); + + b.ToTable("audit_identity20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditIdentityAssignedRole20230522", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("IdentityId") + .HasColumnType("uuid") + .HasColumnName("identity_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_identity_assigned_role20230522"); + + b.ToTable("audit_identity_assigned_role20230522", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOffer20230119", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ContactEmail") + .HasColumnType("text") + .HasColumnName("contact_email"); + + b.Property("ContactNumber") + .HasColumnType("text") + .HasColumnName("contact_number"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DateReleased") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_released"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("MarketingUrl") + .HasColumnType("text") + .HasColumnName("marketing_url"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("OfferStatusId") + .HasColumnType("integer") + .HasColumnName("offer_status_id"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("text") + .HasColumnName("provider"); + + b.Property("ProviderCompanyId") + .HasColumnType("uuid") + .HasColumnName("provider_company_id"); + + b.Property("SalesManagerId") + .HasColumnType("uuid") + .HasColumnName("sales_manager_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer20230119"); + + b.ToTable("audit_offer20230119", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOffer20230406", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ContactEmail") + .HasColumnType("text") + .HasColumnName("contact_email"); + + b.Property("ContactNumber") + .HasColumnType("text") + .HasColumnName("contact_number"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DateReleased") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_released"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LicenseTypeId") + .HasColumnType("integer") + .HasColumnName("license_type_id"); + + b.Property("MarketingUrl") + .HasColumnType("text") + .HasColumnName("marketing_url"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("OfferStatusId") + .HasColumnType("integer") + .HasColumnName("offer_status_id"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.Property("Provider") + .IsRequired() + .HasColumnType("text") + .HasColumnName("provider"); + + b.Property("ProviderCompanyId") + .HasColumnType("uuid") + .HasColumnName("provider_company_id"); + + b.Property("SalesManagerId") + .HasColumnType("uuid") + .HasColumnName("sales_manager_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer20230406"); + + b.ToTable("audit_offer20230406", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOffer20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("ContactEmail") + .HasColumnType("text") + .HasColumnName("contact_email"); + + b.Property("ContactNumber") + .HasColumnType("text") + .HasColumnName("contact_number"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DateReleased") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_released"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LicenseTypeId") + .HasColumnType("integer") + .HasColumnName("license_type_id"); + + b.Property("MarketingUrl") + .HasColumnType("text") + .HasColumnName("marketing_url"); + + b.Property("Name") + .HasColumnType("text") + .HasColumnName("name"); + + b.Property("OfferStatusId") + .HasColumnType("integer") + .HasColumnName("offer_status_id"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.Property("Provider") + .HasColumnType("text") + .HasColumnName("provider"); + + b.Property("ProviderCompanyId") + .HasColumnType("uuid") + .HasColumnName("provider_company_id"); + + b.Property("SalesManagerId") + .HasColumnType("uuid") + .HasColumnName("sales_manager_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer20231115"); + + b.ToTable("audit_offer20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOfferSubscription20221005", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("Description") + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("DisplayName") + .HasColumnType("text") + .HasColumnName("display_name"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferSubscriptionStatusId") + .HasColumnType("integer") + .HasColumnName("offer_subscription_status_id"); + + b.Property("RequesterId") + .HasColumnType("uuid") + .HasColumnName("requester_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer_subscription20221005"); + + b.ToTable("audit_offer_subscription20221005", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOfferSubscription20230317", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("Description") + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("DisplayName") + .HasColumnType("text") + .HasColumnName("display_name"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferSubscriptionStatusId") + .HasColumnType("integer") + .HasColumnName("offer_subscription_status_id"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.Property("RequesterId") + .HasColumnType("uuid") + .HasColumnName("requester_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer_subscription20230317"); + + b.ToTable("audit_offer_subscription20230317", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOfferSubscription20231013", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("Description") + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("DisplayName") + .HasColumnType("text") + .HasColumnName("display_name"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferSubscriptionStatusId") + .HasColumnType("integer") + .HasColumnName("offer_subscription_status_id"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.Property("RequesterId") + .HasColumnType("uuid") + .HasColumnName("requester_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer_subscription20231013"); + + b.ToTable("audit_offer_subscription20231013", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditOfferSubscription20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("Description") + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("DisplayName") + .HasColumnType("text") + .HasColumnName("display_name"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferSubscriptionStatusId") + .HasColumnType("integer") + .HasColumnName("offer_subscription_status_id"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.Property("RequesterId") + .HasColumnType("uuid") + .HasColumnName("requester_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_offer_subscription20231115"); + + b.ToTable("audit_offer_subscription20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditProviderCompanyDetail20230614", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("AutoSetupCallbackUrl") + .HasColumnType("text") + .HasColumnName("auto_setup_callback_url"); + + b.Property("AutoSetupUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("auto_setup_url"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_provider_company_detail20230614"); + + b.ToTable("audit_provider_company_detail20230614", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditProviderCompanyDetail20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("AutoSetupCallbackUrl") + .HasColumnType("text") + .HasColumnName("auto_setup_callback_url"); + + b.Property("AutoSetupUrl") + .HasColumnType("text") + .HasColumnName("auto_setup_url"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_provider_company_detail20231115"); + + b.ToTable("audit_provider_company_detail20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditUserRole20221017", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("UserRoleText") + .IsRequired() + .HasColumnType("text") + .HasColumnName("user_role"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_user_role20221017"); + + b.ToTable("audit_user_role20221017", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.AuditEntities.AuditUserRole20231115", b => + { + b.Property("AuditV1Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("audit_v1id"); + + b.Property("AuditV1DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("audit_v1date_last_changed"); + + b.Property("AuditV1LastEditorId") + .HasColumnType("uuid") + .HasColumnName("audit_v1last_editor_id"); + + b.Property("AuditV1OperationId") + .HasColumnType("integer") + .HasColumnName("audit_v1operation_id"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("UserRoleText") + .HasColumnType("text") + .HasColumnName("user_role"); + + b.HasKey("AuditV1Id") + .HasName("pk_audit_user_role20231115"); + + b.ToTable("audit_user_role20231115", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Address", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("City") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("city"); + + b.Property("CountryAlpha2Code") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("country_alpha2code") + .HasAnnotation("Relational:JsonPropertyName", "country_alpha2code"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Region") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("region"); + + b.Property("Streetadditional") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("streetadditional"); + + b.Property("Streetname") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("streetname"); + + b.Property("Streetnumber") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("streetnumber"); + + b.Property("Zipcode") + .HasMaxLength(12) + .HasColumnType("character varying(12)") + .HasColumnName("zipcode"); + + b.HasKey("Id") + .HasName("pk_addresses"); + + b.HasIndex("CountryAlpha2Code") + .HasDatabaseName("ix_addresses_country_alpha2code"); + + b.ToTable("addresses", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AgreementCategoryId") + .HasColumnType("integer") + .HasColumnName("agreement_category_id"); + + b.Property("AgreementLink") + .HasColumnType("text") + .HasColumnName("agreement_link"); + + b.Property("AgreementType") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("agreement_type"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("IssuerCompanyId") + .HasColumnType("uuid") + .HasColumnName("issuer_company_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("UseCaseId") + .HasColumnType("uuid") + .HasColumnName("use_case_id"); + + b.HasKey("Id") + .HasName("pk_agreements"); + + b.HasIndex("AgreementCategoryId") + .HasDatabaseName("ix_agreements_agreement_category_id"); + + b.HasIndex("DocumentId") + .HasDatabaseName("ix_agreements_document_id"); + + b.HasIndex("IssuerCompanyId") + .HasDatabaseName("ix_agreements_issuer_company_id"); + + b.HasIndex("UseCaseId") + .HasDatabaseName("ix_agreements_use_case_id"); + + b.ToTable("agreements", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedCompanyRole", b => + { + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.HasKey("AgreementId", "CompanyRoleId") + .HasName("pk_agreement_assigned_company_roles"); + + b.HasIndex("CompanyRoleId") + .HasDatabaseName("ix_agreement_assigned_company_roles_company_role_id"); + + b.ToTable("agreement_assigned_company_roles", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedOffer", b => + { + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.HasKey("AgreementId", "OfferId") + .HasName("pk_agreement_assigned_offers"); + + b.HasIndex("OfferId") + .HasDatabaseName("ix_agreement_assigned_offers_offer_id"); + + b.ToTable("agreement_assigned_offers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedOfferType", b => + { + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.HasKey("AgreementId", "OfferTypeId") + .HasName("pk_agreement_assigned_offer_types"); + + b.HasIndex("OfferTypeId") + .HasDatabaseName("ix_agreement_assigned_offer_types_offer_type_id"); + + b.ToTable("agreement_assigned_offer_types", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementCategory", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_agreement_categories"); + + b.ToTable("agreement_categories", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "CX_FRAME_CONTRACT" + }, + new + { + Id = 2, + Label = "APP_CONTRACT" + }, + new + { + Id = 3, + Label = "DATA_CONTRACT" + }, + new + { + Id = 4, + Label = "SERVICE_CONTRACT" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppAssignedUseCase", b => + { + b.Property("AppId") + .HasColumnType("uuid") + .HasColumnName("app_id"); + + b.Property("UseCaseId") + .HasColumnType("uuid") + .HasColumnName("use_case_id"); + + b.HasKey("AppId", "UseCaseId") + .HasName("pk_app_assigned_use_cases"); + + b.HasIndex("UseCaseId") + .HasDatabaseName("ix_app_assigned_use_cases_use_case_id"); + + b.ToTable("app_assigned_use_cases", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstance", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AppId") + .HasColumnType("uuid") + .HasColumnName("app_id"); + + b.Property("IamClientId") + .HasColumnType("uuid") + .HasColumnName("iam_client_id"); + + b.HasKey("Id") + .HasName("pk_app_instances"); + + b.HasIndex("AppId") + .HasDatabaseName("ix_app_instances_app_id"); + + b.HasIndex("IamClientId") + .HasDatabaseName("ix_app_instances_iam_client_id"); + + b.ToTable("app_instances", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstanceAssignedCompanyServiceAccount", b => + { + b.Property("AppInstanceId") + .HasColumnType("uuid") + .HasColumnName("app_instance_id"); + + b.Property("CompanyServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("company_service_account_id"); + + b.HasKey("AppInstanceId", "CompanyServiceAccountId") + .HasName("pk_app_instance_assigned_service_accounts"); + + b.HasIndex("CompanyServiceAccountId") + .HasDatabaseName("ix_app_instance_assigned_service_accounts_company_service_acco"); + + b.ToTable("app_instance_assigned_service_accounts", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstanceSetup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AppId") + .HasColumnType("uuid") + .HasColumnName("app_id"); + + b.Property("InstanceUrl") + .HasColumnType("text") + .HasColumnName("instance_url"); + + b.Property("IsSingleInstance") + .HasColumnType("boolean") + .HasColumnName("is_single_instance"); + + b.HasKey("Id") + .HasName("pk_app_instance_setups"); + + b.HasIndex("AppId") + .IsUnique() + .HasDatabaseName("ix_app_instance_setups_app_id"); + + b.ToTable("app_instance_setups", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppLanguage", b => + { + b.Property("AppId") + .HasColumnType("uuid") + .HasColumnName("app_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.HasKey("AppId", "LanguageShortName") + .HasName("pk_app_languages"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_app_languages_language_short_name"); + + b.ToTable("app_languages", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppSubscriptionDetail", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AppInstanceId") + .HasColumnType("uuid") + .HasColumnName("app_instance_id"); + + b.Property("AppSubscriptionUrl") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("app_subscription_url"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("Id") + .HasName("pk_app_subscription_details"); + + b.HasIndex("AppInstanceId") + .HasDatabaseName("ix_app_subscription_details_app_instance_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_app_subscription_details_last_editor_id"); + + b.HasIndex("OfferSubscriptionId") + .IsUnique() + .HasDatabaseName("ix_app_subscription_details_offer_subscription_id"); + + b.ToTable("app_subscription_details", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_app_subscription_detail20231115\" (\"id\", \"offer_subscription_id\", \"app_instance_id\", \"app_subscription_url\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"offer_subscription_id\", \r\n NEW.\"app_instance_id\", \r\n NEW.\"app_subscription_url\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL AFTER INSERT\r\nON \"portal\".\"app_subscription_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_APPSUBSCRIPTIONDETAIL\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_app_subscription_detail20231115\" (\"id\", \"offer_subscription_id\", \"app_instance_id\", \"app_subscription_url\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"offer_subscription_id\", \r\n NEW.\"app_instance_id\", \r\n NEW.\"app_subscription_url\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL AFTER UPDATE\r\nON \"portal\".\"app_subscription_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_APPSUBSCRIPTIONDETAIL\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntry", b => + { + b.Property("ApplicationId") + .HasColumnType("uuid") + .HasColumnName("application_id"); + + b.Property("ApplicationChecklistEntryTypeId") + .HasColumnType("integer") + .HasColumnName("application_checklist_entry_type_id"); + + b.Property("ApplicationChecklistEntryStatusId") + .HasColumnType("integer") + .HasColumnName("application_checklist_entry_status_id"); + + b.Property("Comment") + .HasColumnType("text") + .HasColumnName("comment"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.HasKey("ApplicationId", "ApplicationChecklistEntryTypeId") + .HasName("pk_application_checklist"); + + b.HasIndex("ApplicationChecklistEntryStatusId") + .HasDatabaseName("ix_application_checklist_application_checklist_entry_status_id"); + + b.HasIndex("ApplicationChecklistEntryTypeId") + .HasDatabaseName("ix_application_checklist_application_checklist_entry_type_id"); + + b.ToTable("application_checklist", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_application_checklist_statuses"); + + b.ToTable("application_checklist_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "TO_DO" + }, + new + { + Id = 2, + Label = "IN_PROGRESS" + }, + new + { + Id = 3, + Label = "DONE" + }, + new + { + Id = 4, + Label = "FAILED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_application_checklist_types"); + + b.ToTable("application_checklist_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "REGISTRATION_VERIFICATION" + }, + new + { + Id = 2, + Label = "BUSINESS_PARTNER_NUMBER" + }, + new + { + Id = 3, + Label = "IDENTITY_WALLET" + }, + new + { + Id = 4, + Label = "CLEARING_HOUSE" + }, + new + { + Id = 5, + Label = "SELF_DESCRIPTION_LP" + }, + new + { + Id = 6, + Label = "APPLICATION_ACTIVATION" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AuditOperation", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_audit_operation"); + + b.ToTable("audit_operation", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "INSERT" + }, + new + { + Id = 2, + Label = "UPDATE" + }, + new + { + Id = 3, + Label = "DELETE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.BpdmIdentifier", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_bpdm_identifiers"); + + b.ToTable("bpdm_identifiers", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "EU_VAT_ID_DE" + }, + new + { + Id = 2, + Label = "CH_UID" + }, + new + { + Id = 3, + Label = "EU_VAT_ID_FR" + }, + new + { + Id = 4, + Label = "FR_SIREN" + }, + new + { + Id = 5, + Label = "EU_VAT_ID_AT" + }, + new + { + Id = 6, + Label = "DE_BNUM" + }, + new + { + Id = 7, + Label = "CZ_ICO" + }, + new + { + Id = 8, + Label = "EU_VAT_ID_CZ" + }, + new + { + Id = 9, + Label = "EU_VAT_ID_PL" + }, + new + { + Id = 10, + Label = "EU_VAT_ID_BE" + }, + new + { + Id = 11, + Label = "EU_VAT_ID_CH" + }, + new + { + Id = 12, + Label = "EU_VAT_ID_DK" + }, + new + { + Id = 13, + Label = "EU_VAT_ID_ES" + }, + new + { + Id = 14, + Label = "EU_VAT_ID_GB" + }, + new + { + Id = 15, + Label = "EU_VAT_ID_NO" + }, + new + { + Id = 16, + Label = "BE_ENT_NO" + }, + new + { + Id = 17, + Label = "CVR_DK" + }, + new + { + Id = 18, + Label = "ID_CRN" + }, + new + { + Id = 19, + Label = "NO_ORGID" + }, + new + { + Id = 20, + Label = "LEI_ID" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AddressId") + .HasColumnType("uuid") + .HasColumnName("address_id"); + + b.Property("BusinessPartnerNumber") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("business_partner_number"); + + b.Property("CompanyStatusId") + .HasColumnType("integer") + .HasColumnName("company_status_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("Shortname") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("shortname"); + + b.HasKey("Id") + .HasName("pk_companies"); + + b.HasIndex("AddressId") + .HasDatabaseName("ix_companies_address_id"); + + b.HasIndex("CompanyStatusId") + .HasDatabaseName("ix_companies_company_status_id"); + + b.HasIndex("SelfDescriptionDocumentId") + .HasDatabaseName("ix_companies_self_description_document_id"); + + b.ToTable("companies", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ApplicationStatusId") + .HasColumnType("integer") + .HasColumnName("application_status_id"); + + b.Property("ChecklistProcessId") + .HasColumnType("uuid") + .HasColumnName("checklist_process_id"); + + b.Property("CompanyApplicationTypeId") + .HasColumnType("integer") + .HasColumnName("company_application_type_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OnboardingServiceProviderId") + .HasColumnType("uuid") + .HasColumnName("onboarding_service_provider_id"); + + b.HasKey("Id") + .HasName("pk_company_applications"); + + b.HasIndex("ApplicationStatusId") + .HasDatabaseName("ix_company_applications_application_status_id"); + + b.HasIndex("ChecklistProcessId") + .IsUnique() + .HasDatabaseName("ix_company_applications_checklist_process_id"); + + b.HasIndex("CompanyApplicationTypeId") + .HasDatabaseName("ix_company_applications_company_application_type_id"); + + b.HasIndex("CompanyId") + .HasDatabaseName("ix_company_applications_company_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_company_applications_last_editor_id"); + + b.HasIndex("OnboardingServiceProviderId") + .HasDatabaseName("ix_company_applications_onboarding_service_provider_id"); + + b.ToTable("company_applications", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_application20231115\" (\"id\", \"date_created\", \"date_last_changed\", \"application_status_id\", \"company_id\", \"checklist_process_id\", \"company_application_type_id\", \"onboarding_service_provider_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"application_status_id\", \r\n NEW.\"company_id\", \r\n NEW.\"checklist_process_id\", \r\n NEW.\"company_application_type_id\", \r\n NEW.\"onboarding_service_provider_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION AFTER INSERT\r\nON \"portal\".\"company_applications\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYAPPLICATION\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_application20231115\" (\"id\", \"date_created\", \"date_last_changed\", \"application_status_id\", \"company_id\", \"checklist_process_id\", \"company_application_type_id\", \"onboarding_service_provider_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"application_status_id\", \r\n NEW.\"company_id\", \r\n NEW.\"checklist_process_id\", \r\n NEW.\"company_application_type_id\", \r\n NEW.\"onboarding_service_provider_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION AFTER UPDATE\r\nON \"portal\".\"company_applications\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYAPPLICATION\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_application_statuses"); + + b.ToTable("company_application_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "CREATED" + }, + new + { + Id = 2, + Label = "ADD_COMPANY_DATA" + }, + new + { + Id = 3, + Label = "INVITE_USER" + }, + new + { + Id = 4, + Label = "SELECT_COMPANY_ROLE" + }, + new + { + Id = 5, + Label = "UPLOAD_DOCUMENTS" + }, + new + { + Id = 6, + Label = "VERIFY" + }, + new + { + Id = 7, + Label = "SUBMITTED" + }, + new + { + Id = 8, + Label = "CONFIRMED" + }, + new + { + Id = 9, + Label = "DECLINED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_application_types"); + + b.ToTable("company_application_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "INTERNAL" + }, + new + { + Id = 2, + Label = "EXTERNAL" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyAssignedRole", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("CompanyId", "CompanyRoleId") + .HasName("pk_company_assigned_roles"); + + b.HasIndex("CompanyRoleId") + .HasDatabaseName("ix_company_assigned_roles_company_role_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_company_assigned_roles_last_editor_id"); + + b.ToTable("company_assigned_roles", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_assigned_role2023316\" (\"company_id\", \"company_role_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"company_id\", \r\n NEW.\"company_role_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE AFTER INSERT\r\nON \"portal\".\"company_assigned_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYASSIGNEDROLE\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_assigned_role2023316\" (\"company_id\", \"company_role_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"company_id\", \r\n NEW.\"company_role_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE AFTER UPDATE\r\nON \"portal\".\"company_assigned_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYASSIGNEDROLE\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyAssignedUseCase", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("UseCaseId") + .HasColumnType("uuid") + .HasColumnName("use_case_id"); + + b.HasKey("CompanyId", "UseCaseId") + .HasName("pk_company_assigned_use_cases"); + + b.HasIndex("UseCaseId") + .HasDatabaseName("ix_company_assigned_use_cases_use_case_id"); + + b.ToTable("company_assigned_use_cases", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyIdentifier", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("UniqueIdentifierId") + .HasColumnType("integer") + .HasColumnName("unique_identifier_id"); + + b.Property("Value") + .IsRequired() + .HasColumnType("text") + .HasColumnName("value"); + + b.HasKey("CompanyId", "UniqueIdentifierId") + .HasName("pk_company_identifiers"); + + b.HasIndex("UniqueIdentifierId") + .HasDatabaseName("ix_company_identifiers_unique_identifier_id"); + + b.ToTable("company_identifiers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyIdentityProvider", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("IdentityProviderId") + .HasColumnType("uuid") + .HasColumnName("identity_provider_id"); + + b.HasKey("CompanyId", "IdentityProviderId") + .HasName("pk_company_identity_providers"); + + b.HasIndex("IdentityProviderId") + .HasDatabaseName("ix_company_identity_providers_identity_provider_id"); + + b.ToTable("company_identity_providers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_roles"); + + b.ToTable("company_roles", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "ACTIVE_PARTICIPANT" + }, + new + { + Id = 2, + Label = "APP_PROVIDER" + }, + new + { + Id = 3, + Label = "SERVICE_PROVIDER" + }, + new + { + Id = 4, + Label = "OPERATOR" + }, + new + { + Id = 5, + Label = "ONBOARDING_SERVICE_PROVIDER" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleAssignedRoleCollection", b => + { + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.Property("UserRoleCollectionId") + .HasColumnType("uuid") + .HasColumnName("user_role_collection_id"); + + b.HasKey("CompanyRoleId") + .HasName("pk_company_role_assigned_role_collections"); + + b.HasIndex("UserRoleCollectionId") + .IsUnique() + .HasDatabaseName("ix_company_role_assigned_role_collections_user_role_collection"); + + b.ToTable("company_role_assigned_role_collections", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleDescription", b => + { + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.HasKey("CompanyRoleId", "LanguageShortName") + .HasName("pk_company_role_descriptions"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_company_role_descriptions_language_short_name"); + + b.ToTable("company_role_descriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleRegistrationData", b => + { + b.Property("CompanyRoleId") + .HasColumnType("integer") + .HasColumnName("company_role_id"); + + b.Property("IsRegistrationRole") + .HasColumnType("boolean") + .HasColumnName("is_registration_role"); + + b.HasKey("CompanyRoleId") + .HasName("pk_company_role_registration_data"); + + b.ToTable("company_role_registration_data", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ClientClientId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("client_client_id"); + + b.Property("CompanyServiceAccountTypeId") + .HasColumnType("integer") + .HasColumnName("company_service_account_type_id"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("Id") + .HasName("pk_company_service_accounts"); + + b.HasIndex("ClientClientId") + .IsUnique() + .HasDatabaseName("ix_company_service_accounts_client_client_id"); + + b.HasIndex("CompanyServiceAccountTypeId") + .HasDatabaseName("ix_company_service_accounts_company_service_account_type_id"); + + b.HasIndex("OfferSubscriptionId") + .HasDatabaseName("ix_company_service_accounts_offer_subscription_id"); + + b.ToTable("company_service_accounts", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccountType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_service_account_types"); + + b.ToTable("company_service_account_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "MANAGED" + }, + new + { + Id = 2, + Label = "OWN" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetail", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanySsiDetailStatusId") + .HasColumnType("integer") + .HasColumnName("company_ssi_detail_status_id"); + + b.Property("CreatorUserId") + .HasColumnType("uuid") + .HasColumnName("creator_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("ExpiryDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiry_date"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("VerifiedCredentialExternalTypeUseCaseDetailId") + .HasColumnType("uuid") + .HasColumnName("verified_credential_external_type_use_case_detail_id"); + + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.HasKey("Id") + .HasName("pk_company_ssi_details"); + + b.HasIndex("CompanyId") + .HasDatabaseName("ix_company_ssi_details_company_id"); + + b.HasIndex("CompanySsiDetailStatusId") + .HasDatabaseName("ix_company_ssi_details_company_ssi_detail_status_id"); + + b.HasIndex("CreatorUserId") + .HasDatabaseName("ix_company_ssi_details_creator_user_id"); + + b.HasIndex("DocumentId") + .IsUnique() + .HasDatabaseName("ix_company_ssi_details_document_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_company_ssi_details_last_editor_id"); + + b.HasIndex("VerifiedCredentialExternalTypeUseCaseDetailId") + .HasDatabaseName("ix_company_ssi_details_verified_credential_external_type_use_c"); + + b.HasIndex("VerifiedCredentialTypeId") + .HasDatabaseName("ix_company_ssi_details_verified_credential_type_id"); + + b.ToTable("company_ssi_details", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_ssi_detail20231115\" (\"id\", \"company_id\", \"verified_credential_type_id\", \"company_ssi_detail_status_id\", \"document_id\", \"date_created\", \"creator_user_id\", \"expiry_date\", \"verified_credential_external_type_use_case_detail_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"company_id\", \r\n NEW.\"verified_credential_type_id\", \r\n NEW.\"company_ssi_detail_status_id\", \r\n NEW.\"document_id\", \r\n NEW.\"date_created\", \r\n NEW.\"creator_user_id\", \r\n NEW.\"expiry_date\", \r\n NEW.\"verified_credential_external_type_use_case_detail_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL AFTER INSERT\r\nON \"portal\".\"company_ssi_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYSSIDETAIL\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_ssi_detail20231115\" (\"id\", \"company_id\", \"verified_credential_type_id\", \"company_ssi_detail_status_id\", \"document_id\", \"date_created\", \"creator_user_id\", \"expiry_date\", \"verified_credential_external_type_use_case_detail_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"company_id\", \r\n NEW.\"verified_credential_type_id\", \r\n NEW.\"company_ssi_detail_status_id\", \r\n NEW.\"document_id\", \r\n NEW.\"date_created\", \r\n NEW.\"creator_user_id\", \r\n NEW.\"expiry_date\", \r\n NEW.\"verified_credential_external_type_use_case_detail_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL AFTER UPDATE\r\nON \"portal\".\"company_ssi_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYSSIDETAIL\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetailStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_ssi_detail_statuses"); + + b.ToTable("company_ssi_detail_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "PENDING" + }, + new + { + Id = 2, + Label = "ACTIVE" + }, + new + { + Id = 3, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_company_statuses"); + + b.ToTable("company_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "PENDING" + }, + new + { + Id = 2, + Label = "ACTIVE" + }, + new + { + Id = 3, + Label = "REJECTED" + }, + new + { + Id = 4, + Label = "INACTIVE" + }, + new + { + Id = 5, + Label = "DELETED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("email"); + + b.Property("Firstname") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("firstname"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Lastlogin") + .HasColumnType("bytea") + .HasColumnName("lastlogin"); + + b.Property("Lastname") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("lastname"); + + b.HasKey("Id") + .HasName("pk_company_users"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_company_users_last_editor_id"); + + b.ToTable("company_users", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_COMPANYUSER"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_COMPANYUSER"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_COMPANYUSER", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYUSER\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_COMPANYUSER$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_user20230523\" (\"id\", \"email\", \"firstname\", \"lastlogin\", \"lastname\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"email\", \r\n NEW.\"firstname\", \r\n NEW.\"lastlogin\", \r\n NEW.\"lastname\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_COMPANYUSER$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_COMPANYUSER AFTER INSERT\r\nON \"portal\".\"company_users\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_COMPANYUSER\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_COMPANYUSER", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYUSER\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_COMPANYUSER$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_company_user20230523\" (\"id\", \"email\", \"firstname\", \"lastlogin\", \"lastname\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"email\", \r\n NEW.\"firstname\", \r\n NEW.\"lastlogin\", \r\n NEW.\"lastname\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_COMPANYUSER$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_COMPANYUSER AFTER UPDATE\r\nON \"portal\".\"company_users\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_COMPANYUSER\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedAppFavourite", b => + { + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("AppId") + .HasColumnType("uuid") + .HasColumnName("app_id"); + + b.HasKey("CompanyUserId", "AppId") + .HasName("pk_company_user_assigned_app_favourites"); + + b.HasIndex("AppId") + .HasDatabaseName("ix_company_user_assigned_app_favourites_app_id"); + + b.ToTable("company_user_assigned_app_favourites", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedBusinessPartner", b => + { + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("BusinessPartnerNumber") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("business_partner_number"); + + b.HasKey("CompanyUserId", "BusinessPartnerNumber") + .HasName("pk_company_user_assigned_business_partners"); + + b.ToTable("company_user_assigned_business_partners", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedIdentityProvider", b => + { + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("IdentityProviderId") + .HasColumnType("uuid") + .HasColumnName("identity_provider_id"); + + b.Property("ProviderId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("provider_id"); + + b.Property("UserName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("user_name"); + + b.HasKey("CompanyUserId", "IdentityProviderId") + .HasName("pk_company_user_assigned_identity_providers"); + + b.HasIndex("IdentityProviderId") + .HasDatabaseName("ix_company_user_assigned_identity_providers_identity_provider_"); + + b.ToTable("company_user_assigned_identity_providers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("company_service_account_id"); + + b.Property("ConnectorUrl") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("connector_url"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("HostId") + .HasColumnType("uuid") + .HasColumnName("host_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LocationId") + .IsRequired() + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("location_id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("ProviderId") + .HasColumnType("uuid") + .HasColumnName("provider_id"); + + b.Property("SelfDescriptionDocumentId") + .HasColumnType("uuid") + .HasColumnName("self_description_document_id"); + + b.Property("SelfDescriptionMessage") + .HasColumnType("text") + .HasColumnName("self_description_message"); + + b.Property("StatusId") + .HasColumnType("integer") + .HasColumnName("status_id"); + + b.Property("TypeId") + .HasColumnType("integer") + .HasColumnName("type_id"); + + b.HasKey("Id") + .HasName("pk_connectors"); + + b.HasIndex("CompanyServiceAccountId") + .IsUnique() + .HasDatabaseName("ix_connectors_company_service_account_id"); + + b.HasIndex("HostId") + .HasDatabaseName("ix_connectors_host_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_connectors_last_editor_id"); + + b.HasIndex("LocationId") + .HasDatabaseName("ix_connectors_location_id"); + + b.HasIndex("ProviderId") + .HasDatabaseName("ix_connectors_provider_id"); + + b.HasIndex("SelfDescriptionDocumentId") + .IsUnique() + .HasDatabaseName("ix_connectors_self_description_document_id"); + + b.HasIndex("StatusId") + .HasDatabaseName("ix_connectors_status_id"); + + b.HasIndex("TypeId") + .HasDatabaseName("ix_connectors_type_id"); + + b.ToTable("connectors", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_CONNECTOR"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_CONNECTOR"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_CONNECTOR", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_CONNECTOR\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_CONNECTOR$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_connector20231115\" (\"id\", \"name\", \"connector_url\", \"type_id\", \"status_id\", \"provider_id\", \"host_id\", \"self_description_document_id\", \"location_id\", \"self_description_message\", \"date_last_changed\", \"company_service_account_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"name\", \r\n NEW.\"connector_url\", \r\n NEW.\"type_id\", \r\n NEW.\"status_id\", \r\n NEW.\"provider_id\", \r\n NEW.\"host_id\", \r\n NEW.\"self_description_document_id\", \r\n NEW.\"location_id\", \r\n NEW.\"self_description_message\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"company_service_account_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_CONNECTOR$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_CONNECTOR AFTER INSERT\r\nON \"portal\".\"connectors\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_CONNECTOR\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_CONNECTOR", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_CONNECTOR\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_CONNECTOR$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_connector20231115\" (\"id\", \"name\", \"connector_url\", \"type_id\", \"status_id\", \"provider_id\", \"host_id\", \"self_description_document_id\", \"location_id\", \"self_description_message\", \"date_last_changed\", \"company_service_account_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"name\", \r\n NEW.\"connector_url\", \r\n NEW.\"type_id\", \r\n NEW.\"status_id\", \r\n NEW.\"provider_id\", \r\n NEW.\"host_id\", \r\n NEW.\"self_description_document_id\", \r\n NEW.\"location_id\", \r\n NEW.\"self_description_message\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"company_service_account_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_CONNECTOR$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_CONNECTOR AFTER UPDATE\r\nON \"portal\".\"connectors\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_CONNECTOR\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorAssignedOfferSubscription", b => + { + b.Property("ConnectorId") + .HasColumnType("uuid") + .HasColumnName("connector_id"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("ConnectorId", "OfferSubscriptionId") + .HasName("pk_connector_assigned_offer_subscriptions"); + + b.HasIndex("OfferSubscriptionId") + .HasDatabaseName("ix_connector_assigned_offer_subscriptions_offer_subscription_id"); + + b.ToTable("connector_assigned_offer_subscriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_connector_statuses"); + + b.ToTable("connector_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "PENDING" + }, + new + { + Id = 2, + Label = "ACTIVE" + }, + new + { + Id = 3, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_connector_types"); + + b.ToTable("connector_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "COMPANY_CONNECTOR" + }, + new + { + Id = 2, + Label = "CONNECTOR_AS_A_SERVICE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Consent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AgreementId") + .HasColumnType("uuid") + .HasColumnName("agreement_id"); + + b.Property("Comment") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("comment"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("ConsentStatusId") + .HasColumnType("integer") + .HasColumnName("consent_status_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("Target") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("target"); + + b.HasKey("Id") + .HasName("pk_consents"); + + b.HasIndex("AgreementId") + .HasDatabaseName("ix_consents_agreement_id"); + + b.HasIndex("CompanyId") + .HasDatabaseName("ix_consents_company_id"); + + b.HasIndex("CompanyUserId") + .HasDatabaseName("ix_consents_company_user_id"); + + b.HasIndex("ConsentStatusId") + .HasDatabaseName("ix_consents_consent_status_id"); + + b.HasIndex("DocumentId") + .HasDatabaseName("ix_consents_document_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_consents_last_editor_id"); + + b.ToTable("consents", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_CONSENT"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_CONSENT"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_CONSENT", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_CONSENT\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_CONSENT$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_consent20231115\" (\"id\", \"date_created\", \"comment\", \"consent_status_id\", \"target\", \"agreement_id\", \"company_id\", \"document_id\", \"company_user_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"comment\", \r\n NEW.\"consent_status_id\", \r\n NEW.\"target\", \r\n NEW.\"agreement_id\", \r\n NEW.\"company_id\", \r\n NEW.\"document_id\", \r\n NEW.\"company_user_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_CONSENT$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_CONSENT AFTER INSERT\r\nON \"portal\".\"consents\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_CONSENT\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_CONSENT", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_CONSENT\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_CONSENT$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_consent20231115\" (\"id\", \"date_created\", \"comment\", \"consent_status_id\", \"target\", \"agreement_id\", \"company_id\", \"document_id\", \"company_user_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"comment\", \r\n NEW.\"consent_status_id\", \r\n NEW.\"target\", \r\n NEW.\"agreement_id\", \r\n NEW.\"company_id\", \r\n NEW.\"document_id\", \r\n NEW.\"company_user_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_CONSENT$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_CONSENT AFTER UPDATE\r\nON \"portal\".\"consents\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_CONSENT\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentAssignedOffer", b => + { + b.Property("ConsentId") + .HasColumnType("uuid") + .HasColumnName("consent_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.HasKey("ConsentId", "OfferId") + .HasName("pk_consent_assigned_offers"); + + b.HasIndex("OfferId") + .HasDatabaseName("ix_consent_assigned_offers_offer_id"); + + b.ToTable("consent_assigned_offers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentAssignedOfferSubscription", b => + { + b.Property("ConsentId") + .HasColumnType("uuid") + .HasColumnName("consent_id"); + + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.HasKey("ConsentId", "OfferSubscriptionId") + .HasName("pk_consent_assigned_offer_subscriptions"); + + b.HasIndex("OfferSubscriptionId") + .HasDatabaseName("ix_consent_assigned_offer_subscriptions_offer_subscription_id"); + + b.ToTable("consent_assigned_offer_subscriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_consent_statuses"); + + b.ToTable("consent_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "ACTIVE" + }, + new + { + Id = 2, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", b => + { + b.Property("Alpha2Code") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("alpha2code") + .IsFixedLength() + .HasAnnotation("Relational:JsonPropertyName", "alpha2code"); + + b.Property("Alpha3Code") + .HasMaxLength(3) + .HasColumnType("character(3)") + .HasColumnName("alpha3code") + .IsFixedLength() + .HasAnnotation("Relational:JsonPropertyName", "alpha3code"); + + b.HasKey("Alpha2Code") + .HasName("pk_countries"); + + b.ToTable("countries", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CountryAssignedIdentifier", b => + { + b.Property("CountryAlpha2Code") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("country_alpha2code") + .HasAnnotation("Relational:JsonPropertyName", "country_alpha2code"); + + b.Property("UniqueIdentifierId") + .HasColumnType("integer") + .HasColumnName("unique_identifier_id"); + + b.Property("BpdmIdentifierId") + .HasColumnType("integer") + .HasColumnName("bpdm_identifier_id"); + + b.HasKey("CountryAlpha2Code", "UniqueIdentifierId") + .HasName("pk_country_assigned_identifiers"); + + b.HasIndex("BpdmIdentifierId") + .HasDatabaseName("ix_country_assigned_identifiers_bpdm_identifier_id"); + + b.HasIndex("UniqueIdentifierId") + .HasDatabaseName("ix_country_assigned_identifiers_unique_identifier_id"); + + b.ToTable("country_assigned_identifiers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CountryLongName", b => + { + b.Property("Alpha2Code") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("alpha2code") + .HasAnnotation("Relational:JsonPropertyName", "alpha2code"); + + b.Property("ShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("short_name"); + + b.Property("LongName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("long_name"); + + b.HasKey("Alpha2Code", "ShortName") + .HasName("pk_country_long_names"); + + b.HasIndex("ShortName") + .HasDatabaseName("ix_country_long_names_short_name"); + + b.ToTable("country_long_names", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DocumentContent") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("document_content"); + + b.Property("DocumentHash") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("document_hash"); + + b.Property("DocumentName") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("document_name"); + + b.Property("DocumentStatusId") + .HasColumnType("integer") + .HasColumnName("document_status_id"); + + b.Property("DocumentTypeId") + .HasColumnType("integer") + .HasColumnName("document_type_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("MediaTypeId") + .HasColumnType("integer") + .HasColumnName("media_type_id"); + + b.HasKey("Id") + .HasName("pk_documents"); + + b.HasIndex("CompanyUserId") + .HasDatabaseName("ix_documents_company_user_id"); + + b.HasIndex("DocumentStatusId") + .HasDatabaseName("ix_documents_document_status_id"); + + b.HasIndex("DocumentTypeId") + .HasDatabaseName("ix_documents_document_type_id"); + + b.HasIndex("MediaTypeId") + .HasDatabaseName("ix_documents_media_type_id"); + + b.ToTable("documents", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_DOCUMENT"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_DOCUMENT"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_DOCUMENT", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_DOCUMENT\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_DOCUMENT$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_document20231115\" (\"id\", \"date_created\", \"document_hash\", \"document_content\", \"document_name\", \"media_type_id\", \"document_type_id\", \"document_status_id\", \"company_user_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"document_hash\", \r\n NEW.\"document_content\", \r\n NEW.\"document_name\", \r\n NEW.\"media_type_id\", \r\n NEW.\"document_type_id\", \r\n NEW.\"document_status_id\", \r\n NEW.\"company_user_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_DOCUMENT$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_DOCUMENT AFTER INSERT\r\nON \"portal\".\"documents\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_DOCUMENT\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_DOCUMENT", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_DOCUMENT\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_DOCUMENT$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_document20231115\" (\"id\", \"date_created\", \"document_hash\", \"document_content\", \"document_name\", \"media_type_id\", \"document_type_id\", \"document_status_id\", \"company_user_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"document_hash\", \r\n NEW.\"document_content\", \r\n NEW.\"document_name\", \r\n NEW.\"media_type_id\", \r\n NEW.\"document_type_id\", \r\n NEW.\"document_status_id\", \r\n NEW.\"company_user_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_DOCUMENT$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_DOCUMENT AFTER UPDATE\r\nON \"portal\".\"documents\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_DOCUMENT\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_document_status"); + + b.ToTable("document_status", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "PENDING" + }, + new + { + Id = 2, + Label = "LOCKED" + }, + new + { + Id = 3, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_document_types"); + + b.ToTable("document_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "CX_FRAME_CONTRACT" + }, + new + { + Id = 2, + Label = "COMMERCIAL_REGISTER_EXTRACT" + }, + new + { + Id = 3, + Label = "APP_CONTRACT" + }, + new + { + Id = 4, + Label = "CONFORMITY_APPROVAL_REGISTRATION" + }, + new + { + Id = 5, + Label = "ADDITIONAL_DETAILS" + }, + new + { + Id = 6, + Label = "APP_LEADIMAGE" + }, + new + { + Id = 7, + Label = "APP_IMAGE" + }, + new + { + Id = 8, + Label = "SELF_DESCRIPTION" + }, + new + { + Id = 9, + Label = "APP_TECHNICAL_INFORMATION" + }, + new + { + Id = 10, + Label = "CONFORMITY_APPROVAL_CONNECTOR" + }, + new + { + Id = 11, + Label = "CONFORMITY_APPROVAL_BUSINESS_APPS" + }, + new + { + Id = 12, + Label = "CONFORMITY_APPROVAL_SERVICES" + }, + new + { + Id = 13, + Label = "SERVICE_LEADIMAGE" + }, + new + { + Id = 14, + Label = "PRESENTATION" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamClient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ClientClientId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("client_client_id"); + + b.HasKey("Id") + .HasName("pk_iam_clients"); + + b.HasIndex("ClientClientId") + .IsUnique() + .HasDatabaseName("ix_iam_clients_client_client_id"); + + b.ToTable("iam_clients", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamIdentityProvider", b => + { + b.Property("IamIdpAlias") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("iam_idp_alias"); + + b.Property("IdentityProviderId") + .HasColumnType("uuid") + .HasColumnName("identity_provider_id"); + + b.HasKey("IamIdpAlias") + .HasName("pk_iam_identity_providers"); + + b.HasIndex("IdentityProviderId") + .IsUnique() + .HasDatabaseName("ix_iam_identity_providers_identity_provider_id"); + + b.ToTable("iam_identity_providers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("IdentityTypeId") + .HasColumnType("integer") + .HasColumnName("identity_type_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("UserEntityId") + .HasMaxLength(36) + .HasColumnType("character varying(36)") + .HasColumnName("user_entity_id"); + + b.Property("UserStatusId") + .HasColumnType("integer") + .HasColumnName("user_status_id") + .HasAnnotation("Relational:JsonPropertyName", "user_status_id"); + + b.HasKey("Id") + .HasName("pk_identities"); + + b.HasIndex("CompanyId") + .HasDatabaseName("ix_identities_company_id"); + + b.HasIndex("IdentityTypeId") + .HasDatabaseName("ix_identities_identity_type_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_identities_last_editor_id"); + + b.HasIndex("UserEntityId") + .IsUnique() + .HasDatabaseName("ix_identities_user_entity_id"); + + b.HasIndex("UserStatusId") + .HasDatabaseName("ix_identities_user_status_id"); + + b.ToTable("identities", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_IDENTITY"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_IDENTITY"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_IDENTITY", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_IDENTITY\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_IDENTITY$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_identity20231115\" (\"id\", \"date_created\", \"company_id\", \"user_status_id\", \"user_entity_id\", \"identity_type_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"company_id\", \r\n NEW.\"user_status_id\", \r\n NEW.\"user_entity_id\", \r\n NEW.\"identity_type_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_IDENTITY$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_IDENTITY AFTER INSERT\r\nON \"portal\".\"identities\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_IDENTITY\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_IDENTITY", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_IDENTITY\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_IDENTITY$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_identity20231115\" (\"id\", \"date_created\", \"company_id\", \"user_status_id\", \"user_entity_id\", \"identity_type_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"company_id\", \r\n NEW.\"user_status_id\", \r\n NEW.\"user_entity_id\", \r\n NEW.\"identity_type_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_IDENTITY$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_IDENTITY AFTER UPDATE\r\nON \"portal\".\"identities\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_IDENTITY\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityAssignedRole", b => + { + b.Property("IdentityId") + .HasColumnType("uuid") + .HasColumnName("identity_id"); + + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("IdentityId", "UserRoleId") + .HasName("pk_identity_assigned_roles"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_identity_assigned_roles_last_editor_id"); + + b.HasIndex("UserRoleId") + .HasDatabaseName("ix_identity_assigned_roles_user_role_id"); + + b.ToTable("identity_assigned_roles", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_identity_assigned_role20230522\" (\"identity_id\", \"user_role_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"identity_id\", \r\n NEW.\"user_role_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE AFTER INSERT\r\nON \"portal\".\"identity_assigned_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_IDENTITYASSIGNEDROLE\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_identity_assigned_role20230522\" (\"identity_id\", \"user_role_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"identity_id\", \r\n NEW.\"user_role_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE AFTER UPDATE\r\nON \"portal\".\"identity_assigned_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_IDENTITYASSIGNEDROLE\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("IdentityProviderCategoryId") + .HasColumnType("integer") + .HasColumnName("identity_provider_category_id"); + + b.Property("IdentityProviderTypeId") + .HasColumnType("integer") + .HasColumnName("identity_provider_type_id"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.HasKey("Id") + .HasName("pk_identity_providers"); + + b.HasIndex("IdentityProviderCategoryId") + .HasDatabaseName("ix_identity_providers_identity_provider_category_id"); + + b.HasIndex("IdentityProviderTypeId") + .HasDatabaseName("ix_identity_providers_identity_provider_type_id"); + + b.HasIndex("OwnerId") + .HasDatabaseName("ix_identity_providers_owner_id"); + + b.ToTable("identity_providers", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderCategory", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_identity_provider_categories"); + + b.ToTable("identity_provider_categories", "portal"); + + b.HasData( + new + { + Id = 2, + Label = "KEYCLOAK_OIDC" + }, + new + { + Id = 3, + Label = "KEYCLOAK_SAML" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_identity_provider_types"); + + b.ToTable("identity_provider_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "OWN" + }, + new + { + Id = 2, + Label = "MANAGED" + }, + new + { + Id = 3, + Label = "SHARED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_identity_type"); + + b.ToTable("identity_type", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "COMPANY_USER" + }, + new + { + Id = 2, + Label = "COMPANY_SERVICE_ACCOUNT" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityUserStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_identity_user_statuses"); + + b.ToTable("identity_user_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "ACTIVE" + }, + new + { + Id = 2, + Label = "INACTIVE" + }, + new + { + Id = 3, + Label = "DELETED" + }, + new + { + Id = 4, + Label = "PENDING" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyApplicationId") + .HasColumnType("uuid") + .HasColumnName("company_application_id"); + + b.Property("CompanyUserId") + .HasColumnType("uuid") + .HasColumnName("company_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("InvitationStatusId") + .HasColumnType("integer") + .HasColumnName("invitation_status_id"); + + b.HasKey("Id") + .HasName("pk_invitations"); + + b.HasIndex("CompanyApplicationId") + .HasDatabaseName("ix_invitations_company_application_id"); + + b.HasIndex("CompanyUserId") + .HasDatabaseName("ix_invitations_company_user_id"); + + b.HasIndex("InvitationStatusId") + .HasDatabaseName("ix_invitations_invitation_status_id"); + + b.ToTable("invitations", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.InvitationStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_invitation_statuses"); + + b.ToTable("invitation_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "CREATED" + }, + new + { + Id = 2, + Label = "PENDING" + }, + new + { + Id = 3, + Label = "ACCEPTED" + }, + new + { + Id = 4, + Label = "DECLINED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", b => + { + b.Property("ShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("short_name") + .IsFixedLength(); + + b.HasKey("ShortName") + .HasName("pk_languages"); + + b.ToTable("languages", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.LanguageLongName", b => + { + b.Property("ShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("short_name") + .IsFixedLength(); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name") + .IsFixedLength(); + + b.Property("LongName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("long_name"); + + b.HasKey("ShortName", "LanguageShortName") + .HasName("pk_language_long_names"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_language_long_names_language_short_name"); + + b.ToTable("language_long_names", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.LicenseType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_license_types"); + + b.ToTable("license_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "COTS" + }, + new + { + Id = 2, + Label = "FOSS" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.MediaType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_media_types"); + + b.ToTable("media_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "JPEG" + }, + new + { + Id = 2, + Label = "GIF" + }, + new + { + Id = 3, + Label = "PNG" + }, + new + { + Id = 4, + Label = "SVG" + }, + new + { + Id = 5, + Label = "TIFF" + }, + new + { + Id = 6, + Label = "PDF" + }, + new + { + Id = 7, + Label = "JSON" + }, + new + { + Id = 8, + Label = "PEM" + }, + new + { + Id = 9, + Label = "CA_CERT" + }, + new + { + Id = 10, + Label = "PKX_CER" + }, + new + { + Id = 11, + Label = "OCTET" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NetworkRegistration", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ApplicationId") + .HasColumnType("uuid") + .HasColumnName("application_id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("ExternalId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("external_id"); + + b.Property("OnboardingServiceProviderId") + .HasColumnType("uuid") + .HasColumnName("onboarding_service_provider_id"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.HasKey("Id") + .HasName("pk_network_registrations"); + + b.HasIndex("ApplicationId") + .IsUnique() + .HasDatabaseName("ix_network_registrations_application_id"); + + b.HasIndex("CompanyId") + .IsUnique() + .HasDatabaseName("ix_network_registrations_company_id"); + + b.HasIndex("OnboardingServiceProviderId") + .HasDatabaseName("ix_network_registrations_onboarding_service_provider_id"); + + b.HasIndex("ProcessId") + .IsUnique() + .HasDatabaseName("ix_network_registrations_process_id"); + + b.HasIndex("ExternalId", "OnboardingServiceProviderId") + .IsUnique() + .HasDatabaseName("ix_network_registrations_external_id_onboarding_service_provid"); + + b.ToTable("network_registrations", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Notification", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Content") + .HasColumnType("text") + .HasColumnName("content"); + + b.Property("CreatorUserId") + .HasColumnType("uuid") + .HasColumnName("creator_user_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("Done") + .HasColumnType("boolean") + .HasColumnName("done"); + + b.Property("DueDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("due_date"); + + b.Property("IsRead") + .HasColumnType("boolean") + .HasColumnName("is_read"); + + b.Property("NotificationTypeId") + .HasColumnType("integer") + .HasColumnName("notification_type_id"); + + b.Property("ReceiverUserId") + .HasColumnType("uuid") + .HasColumnName("receiver_user_id"); + + b.HasKey("Id") + .HasName("pk_notifications"); + + b.HasIndex("CreatorUserId") + .HasDatabaseName("ix_notifications_creator_user_id"); + + b.HasIndex("NotificationTypeId") + .HasDatabaseName("ix_notifications_notification_type_id"); + + b.HasIndex("ReceiverUserId") + .HasDatabaseName("ix_notifications_receiver_user_id"); + + b.ToTable("notifications", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTopic", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_notification_topic"); + + b.ToTable("notification_topic", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "INFO" + }, + new + { + Id = 2, + Label = "ACTION" + }, + new + { + Id = 3, + Label = "OFFER" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_notification_type"); + + b.ToTable("notification_type", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "INFO" + }, + new + { + Id = 2, + Label = "ACTION" + }, + new + { + Id = 3, + Label = "WELCOME" + }, + new + { + Id = 4, + Label = "WELCOME_USE_CASES" + }, + new + { + Id = 5, + Label = "WELCOME_SERVICE_PROVIDER" + }, + new + { + Id = 6, + Label = "WELCOME_CONNECTOR_REGISTRATION" + }, + new + { + Id = 7, + Label = "WELCOME_APP_MARKETPLACE" + }, + new + { + Id = 8, + Label = "APP_SUBSCRIPTION_REQUEST" + }, + new + { + Id = 9, + Label = "APP_SUBSCRIPTION_ACTIVATION" + }, + new + { + Id = 10, + Label = "CONNECTOR_REGISTERED" + }, + new + { + Id = 11, + Label = "APP_RELEASE_REQUEST" + }, + new + { + Id = 12, + Label = "TECHNICAL_USER_CREATION" + }, + new + { + Id = 13, + Label = "SERVICE_REQUEST" + }, + new + { + Id = 14, + Label = "SERVICE_ACTIVATION" + }, + new + { + Id = 15, + Label = "APP_ROLE_ADDED" + }, + new + { + Id = 16, + Label = "APP_RELEASE_APPROVAL" + }, + new + { + Id = 17, + Label = "SERVICE_RELEASE_REQUEST" + }, + new + { + Id = 18, + Label = "SERVICE_RELEASE_APPROVAL" + }, + new + { + Id = 19, + Label = "APP_RELEASE_REJECTION" + }, + new + { + Id = 20, + Label = "SERVICE_RELEASE_REJECTION" + }, + new + { + Id = 21, + Label = "ROLE_UPDATE_CORE_OFFER" + }, + new + { + Id = 22, + Label = "ROLE_UPDATE_APP_OFFER" + }, + new + { + Id = 23, + Label = "SUBSCRIPTION_URL_UPDATE" + }, + new + { + Id = 24, + Label = "CREDENTIAL_APPROVAL" + }, + new + { + Id = 25, + Label = "CREDENTIAL_REJECTED" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTypeAssignedTopic", b => + { + b.Property("NotificationTypeId") + .HasColumnType("integer") + .HasColumnName("notification_type_id"); + + b.Property("NotificationTopicId") + .HasColumnType("integer") + .HasColumnName("notification_topic_id"); + + b.HasKey("NotificationTypeId", "NotificationTopicId") + .HasName("pk_notification_type_assigned_topics"); + + b.HasIndex("NotificationTopicId") + .HasDatabaseName("ix_notification_type_assigned_topics_notification_topic_id"); + + b.HasIndex("NotificationTypeId") + .IsUnique() + .HasDatabaseName("ix_notification_type_assigned_topics_notification_type_id"); + + b.ToTable("notification_type_assigned_topics", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ContactEmail") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("contact_email"); + + b.Property("ContactNumber") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("contact_number"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("DateReleased") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_released"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("LicenseTypeId") + .HasColumnType("integer") + .HasColumnName("license_type_id"); + + b.Property("MarketingUrl") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("marketing_url"); + + b.Property("Name") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("OfferStatusId") + .HasColumnType("integer") + .HasColumnName("offer_status_id"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("provider"); + + b.Property("ProviderCompanyId") + .HasColumnType("uuid") + .HasColumnName("provider_company_id"); + + b.Property("SalesManagerId") + .HasColumnType("uuid") + .HasColumnName("sales_manager_id"); + + b.HasKey("Id") + .HasName("pk_offers"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_offers_last_editor_id"); + + b.HasIndex("LicenseTypeId") + .HasDatabaseName("ix_offers_license_type_id"); + + b.HasIndex("OfferStatusId") + .HasDatabaseName("ix_offers_offer_status_id"); + + b.HasIndex("OfferTypeId") + .HasDatabaseName("ix_offers_offer_type_id"); + + b.HasIndex("ProviderCompanyId") + .HasDatabaseName("ix_offers_provider_company_id"); + + b.HasIndex("SalesManagerId") + .HasDatabaseName("ix_offers_sales_manager_id"); + + b.ToTable("offers", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_OFFER"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_OFFER"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_OFFER", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_OFFER\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_OFFER$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_offer20231115\" (\"id\", \"name\", \"date_created\", \"date_released\", \"marketing_url\", \"contact_email\", \"contact_number\", \"provider\", \"offer_type_id\", \"sales_manager_id\", \"provider_company_id\", \"offer_status_id\", \"license_type_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"name\", \r\n NEW.\"date_created\", \r\n NEW.\"date_released\", \r\n NEW.\"marketing_url\", \r\n NEW.\"contact_email\", \r\n NEW.\"contact_number\", \r\n NEW.\"provider\", \r\n NEW.\"offer_type_id\", \r\n NEW.\"sales_manager_id\", \r\n NEW.\"provider_company_id\", \r\n NEW.\"offer_status_id\", \r\n NEW.\"license_type_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_OFFER$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_OFFER AFTER INSERT\r\nON \"portal\".\"offers\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_OFFER\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_OFFER", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_OFFER\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_OFFER$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_offer20231115\" (\"id\", \"name\", \"date_created\", \"date_released\", \"marketing_url\", \"contact_email\", \"contact_number\", \"provider\", \"offer_type_id\", \"sales_manager_id\", \"provider_company_id\", \"offer_status_id\", \"license_type_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"name\", \r\n NEW.\"date_created\", \r\n NEW.\"date_released\", \r\n NEW.\"marketing_url\", \r\n NEW.\"contact_email\", \r\n NEW.\"contact_number\", \r\n NEW.\"provider\", \r\n NEW.\"offer_type_id\", \r\n NEW.\"sales_manager_id\", \r\n NEW.\"provider_company_id\", \r\n NEW.\"offer_status_id\", \r\n NEW.\"license_type_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_OFFER$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_OFFER AFTER UPDATE\r\nON \"portal\".\"offers\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_OFFER\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedDocument", b => + { + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("DocumentId") + .HasColumnType("uuid") + .HasColumnName("document_id"); + + b.HasKey("OfferId", "DocumentId") + .HasName("pk_offer_assigned_documents"); + + b.HasIndex("DocumentId") + .HasDatabaseName("ix_offer_assigned_documents_document_id"); + + b.ToTable("offer_assigned_documents", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedLicense", b => + { + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferLicenseId") + .HasColumnType("uuid") + .HasColumnName("offer_license_id"); + + b.HasKey("OfferId", "OfferLicenseId") + .HasName("pk_offer_assigned_licenses"); + + b.HasIndex("OfferLicenseId") + .HasDatabaseName("ix_offer_assigned_licenses_offer_license_id"); + + b.ToTable("offer_assigned_licenses", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedPrivacyPolicy", b => + { + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("PrivacyPolicyId") + .HasColumnType("integer") + .HasColumnName("privacy_policy_id"); + + b.HasKey("OfferId", "PrivacyPolicyId") + .HasName("pk_offer_assigned_privacy_policies"); + + b.HasIndex("PrivacyPolicyId") + .HasDatabaseName("ix_offer_assigned_privacy_policies_privacy_policy_id"); + + b.ToTable("offer_assigned_privacy_policies", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferDescription", b => + { + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.Property("DescriptionLong") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("description_long"); + + b.Property("DescriptionShort") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description_short"); + + b.HasKey("OfferId", "LanguageShortName") + .HasName("pk_offer_descriptions"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_offer_descriptions_language_short_name"); + + b.ToTable("offer_descriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferLicense", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Licensetext") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("licensetext"); + + b.HasKey("Id") + .HasName("pk_offer_licenses"); + + b.ToTable("offer_licenses", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_offer_statuses"); + + b.ToTable("offer_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "CREATED" + }, + new + { + Id = 2, + Label = "IN_REVIEW" + }, + new + { + Id = 3, + Label = "ACTIVE" + }, + new + { + Id = 4, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("Description") + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("description"); + + b.Property("DisplayName") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("display_name"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("OfferSubscriptionStatusId") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(1) + .HasColumnName("offer_subscription_status_id"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.Property("RequesterId") + .HasColumnType("uuid") + .HasColumnName("requester_id"); + + b.HasKey("Id") + .HasName("pk_offer_subscriptions"); + + b.HasIndex("CompanyId") + .HasDatabaseName("ix_offer_subscriptions_company_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_offer_subscriptions_last_editor_id"); + + b.HasIndex("OfferId") + .HasDatabaseName("ix_offer_subscriptions_offer_id"); + + b.HasIndex("OfferSubscriptionStatusId") + .HasDatabaseName("ix_offer_subscriptions_offer_subscription_status_id"); + + b.HasIndex("ProcessId") + .IsUnique() + .HasDatabaseName("ix_offer_subscriptions_process_id"); + + b.HasIndex("RequesterId") + .HasDatabaseName("ix_offer_subscriptions_requester_id"); + + b.ToTable("offer_subscriptions", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_offer_subscription20231115\" (\"id\", \"company_id\", \"offer_id\", \"offer_subscription_status_id\", \"display_name\", \"description\", \"requester_id\", \"last_editor_id\", \"process_id\", \"date_created\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"company_id\", \r\n NEW.\"offer_id\", \r\n NEW.\"offer_subscription_status_id\", \r\n NEW.\"display_name\", \r\n NEW.\"description\", \r\n NEW.\"requester_id\", \r\n NEW.\"last_editor_id\", \r\n NEW.\"process_id\", \r\n NEW.\"date_created\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION AFTER INSERT\r\nON \"portal\".\"offer_subscriptions\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_OFFERSUBSCRIPTION\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_offer_subscription20231115\" (\"id\", \"company_id\", \"offer_id\", \"offer_subscription_status_id\", \"display_name\", \"description\", \"requester_id\", \"last_editor_id\", \"process_id\", \"date_created\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"company_id\", \r\n NEW.\"offer_id\", \r\n NEW.\"offer_subscription_status_id\", \r\n NEW.\"display_name\", \r\n NEW.\"description\", \r\n NEW.\"requester_id\", \r\n NEW.\"last_editor_id\", \r\n NEW.\"process_id\", \r\n NEW.\"date_created\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION AFTER UPDATE\r\nON \"portal\".\"offer_subscriptions\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_OFFERSUBSCRIPTION\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionProcessData", b => + { + b.Property("OfferSubscriptionId") + .HasColumnType("uuid") + .HasColumnName("offer_subscription_id"); + + b.Property("OfferUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("offer_url"); + + b.HasKey("OfferSubscriptionId") + .HasName("pk_offer_subscriptions_process_datas"); + + b.ToTable("offer_subscriptions_process_datas", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_offer_subscription_statuses"); + + b.ToTable("offer_subscription_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "PENDING" + }, + new + { + Id = 2, + Label = "ACTIVE" + }, + new + { + Id = 3, + Label = "INACTIVE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferTag", b => + { + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("Name") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("tag_name") + .HasAnnotation("Relational:JsonPropertyName", "tag_name"); + + b.HasKey("OfferId", "Name") + .HasName("pk_offer_tags"); + + b.ToTable("offer_tags", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_offer_types"); + + b.ToTable("offer_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "APP" + }, + new + { + Id = 2, + Label = "CORE_COMPONENT" + }, + new + { + Id = 3, + Label = "SERVICE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OnboardingServiceProviderDetail", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("AuthUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("auth_url"); + + b.Property("CallbackUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("callback_url"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("text") + .HasColumnName("client_id"); + + b.Property("ClientSecret") + .IsRequired() + .HasColumnType("bytea") + .HasColumnName("client_secret"); + + b.HasKey("CompanyId") + .HasName("pk_onboarding_service_provider_details"); + + b.ToTable("onboarding_service_provider_details", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.PrivacyPolicy", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_privacy_policies"); + + b.ToTable("privacy_policies", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "COMPANY_DATA" + }, + new + { + Id = 2, + Label = "USER_DATA" + }, + new + { + Id = 3, + Label = "LOCATION" + }, + new + { + Id = 4, + Label = "BROWSER_HISTORY" + }, + new + { + Id = 5, + Label = "NONE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LockExpiryDate") + .HasColumnType("timestamp with time zone") + .HasColumnName("lock_expiry_date"); + + b.Property("ProcessTypeId") + .HasColumnType("integer") + .HasColumnName("process_type_id"); + + b.Property("Version") + .IsConcurrencyToken() + .HasColumnType("uuid") + .HasColumnName("version"); + + b.HasKey("Id") + .HasName("pk_processes"); + + b.HasIndex("ProcessTypeId") + .HasDatabaseName("ix_processes_process_type_id"); + + b.ToTable("processes", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStep", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("Message") + .HasColumnType("text") + .HasColumnName("message"); + + b.Property("ProcessId") + .HasColumnType("uuid") + .HasColumnName("process_id"); + + b.Property("ProcessStepStatusId") + .HasColumnType("integer") + .HasColumnName("process_step_status_id"); + + b.Property("ProcessStepTypeId") + .HasColumnType("integer") + .HasColumnName("process_step_type_id"); + + b.HasKey("Id") + .HasName("pk_process_steps"); + + b.HasIndex("ProcessId") + .HasDatabaseName("ix_process_steps_process_id"); + + b.HasIndex("ProcessStepStatusId") + .HasDatabaseName("ix_process_steps_process_step_status_id"); + + b.HasIndex("ProcessStepTypeId") + .HasDatabaseName("ix_process_steps_process_step_type_id"); + + b.ToTable("process_steps", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepStatus", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_process_step_statuses"); + + b.ToTable("process_step_statuses", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "TODO" + }, + new + { + Id = 2, + Label = "DONE" + }, + new + { + Id = 3, + Label = "SKIPPED" + }, + new + { + Id = 4, + Label = "FAILED" + }, + new + { + Id = 5, + Label = "DUPLICATE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_process_step_types"); + + b.ToTable("process_step_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "VERIFY_REGISTRATION" + }, + new + { + Id = 2, + Label = "CREATE_BUSINESS_PARTNER_NUMBER_PUSH" + }, + new + { + Id = 3, + Label = "CREATE_BUSINESS_PARTNER_NUMBER_PULL" + }, + new + { + Id = 4, + Label = "CREATE_BUSINESS_PARTNER_NUMBER_MANUAL" + }, + new + { + Id = 5, + Label = "CREATE_IDENTITY_WALLET" + }, + new + { + Id = 6, + Label = "RETRIGGER_IDENTITY_WALLET" + }, + new + { + Id = 7, + Label = "START_CLEARING_HOUSE" + }, + new + { + Id = 8, + Label = "RETRIGGER_CLEARING_HOUSE" + }, + new + { + Id = 9, + Label = "END_CLEARING_HOUSE" + }, + new + { + Id = 10, + Label = "START_SELF_DESCRIPTION_LP" + }, + new + { + Id = 11, + Label = "RETRIGGER_SELF_DESCRIPTION_LP" + }, + new + { + Id = 12, + Label = "ACTIVATE_APPLICATION" + }, + new + { + Id = 13, + Label = "RETRIGGER_BUSINESS_PARTNER_NUMBER_PUSH" + }, + new + { + Id = 14, + Label = "RETRIGGER_BUSINESS_PARTNER_NUMBER_PULL" + }, + new + { + Id = 15, + Label = "OVERRIDE_BUSINESS_PARTNER_NUMBER" + }, + new + { + Id = 16, + Label = "TRIGGER_OVERRIDE_CLEARING_HOUSE" + }, + new + { + Id = 17, + Label = "START_OVERRIDE_CLEARING_HOUSE" + }, + new + { + Id = 18, + Label = "FINISH_SELF_DESCRIPTION_LP" + }, + new + { + Id = 19, + Label = "DECLINE_APPLICATION" + }, + new + { + Id = 100, + Label = "TRIGGER_PROVIDER" + }, + new + { + Id = 101, + Label = "START_AUTOSETUP" + }, + new + { + Id = 102, + Label = "OFFERSUBSCRIPTION_CLIENT_CREATION" + }, + new + { + Id = 103, + Label = "SINGLE_INSTANCE_SUBSCRIPTION_DETAILS_CREATION" + }, + new + { + Id = 104, + Label = "OFFERSUBSCRIPTION_TECHNICALUSER_CREATION" + }, + new + { + Id = 105, + Label = "ACTIVATE_SUBSCRIPTION" + }, + new + { + Id = 106, + Label = "TRIGGER_PROVIDER_CALLBACK" + }, + new + { + Id = 107, + Label = "RETRIGGER_PROVIDER" + }, + new + { + Id = 108, + Label = "RETRIGGER_OFFERSUBSCRIPTION_CLIENT_CREATION" + }, + new + { + Id = 109, + Label = "RETRIGGER_OFFERSUBSCRIPTION_TECHNICALUSER_CREATION" + }, + new + { + Id = 110, + Label = "RETRIGGER_PROVIDER_CALLBACK" + }, + new + { + Id = 111, + Label = "TRIGGER_ACTIVATE_SUBSCRIPTION" + }, + new + { + Id = 200, + Label = "SYNCHRONIZE_USER" + }, + new + { + Id = 201, + Label = "RETRIGGER_SYNCHRONIZE_USER" + }, + new + { + Id = 202, + Label = "TRIGGER_CALLBACK_OSP_SUBMITTED" + }, + new + { + Id = 203, + Label = "TRIGGER_CALLBACK_OSP_APPROVED" + }, + new + { + Id = 204, + Label = "TRIGGER_CALLBACK_OSP_DECLINED" + }, + new + { + Id = 205, + Label = "RETRIGGER_CALLBACK_OSP_SUBMITTED" + }, + new + { + Id = 206, + Label = "RETRIGGER_CALLBACK_OSP_APPROVED" + }, + new + { + Id = 207, + Label = "RETRIGGER_CALLBACK_OSP_DECLINED" + }, + new + { + Id = 300, + Label = "SYNCHRONIZE_SERVICE_ACCOUNTS" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_process_types"); + + b.ToTable("process_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "APPLICATION_CHECKLIST" + }, + new + { + Id = 3, + Label = "OFFER_SUBSCRIPTION" + }, + new + { + Id = 4, + Label = "PARTNER_REGISTRATION" + }, + new + { + Id = 5, + Label = "SERVICE_ACCOUNT_SYNC" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProviderCompanyDetail", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AutoSetupCallbackUrl") + .HasColumnType("text") + .HasColumnName("auto_setup_callback_url"); + + b.Property("AutoSetupUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("auto_setup_url"); + + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_created"); + + b.Property("DateLastChanged") + .HasColumnType("timestamp with time zone") + .HasColumnName("date_last_changed"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.HasKey("Id") + .HasName("pk_provider_company_details"); + + b.HasIndex("CompanyId") + .IsUnique() + .HasDatabaseName("ix_provider_company_details_company_id"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_provider_company_details_last_editor_id"); + + b.ToTable("provider_company_details", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_provider_company_detail20231115\" (\"id\", \"date_created\", \"auto_setup_url\", \"auto_setup_callback_url\", \"company_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"auto_setup_url\", \r\n NEW.\"auto_setup_callback_url\", \r\n NEW.\"company_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL AFTER INSERT\r\nON \"portal\".\"provider_company_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_PROVIDERCOMPANYDETAIL\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_provider_company_detail20231115\" (\"id\", \"date_created\", \"auto_setup_url\", \"auto_setup_callback_url\", \"company_id\", \"date_last_changed\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"date_created\", \r\n NEW.\"auto_setup_url\", \r\n NEW.\"auto_setup_callback_url\", \r\n NEW.\"company_id\", \r\n NEW.\"date_last_changed\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL AFTER UPDATE\r\nON \"portal\".\"provider_company_details\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_PROVIDERCOMPANYDETAIL\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ServiceDetail", b => + { + b.Property("ServiceId") + .HasColumnType("uuid") + .HasColumnName("service_id"); + + b.Property("ServiceTypeId") + .HasColumnType("integer") + .HasColumnName("service_type_id"); + + b.HasKey("ServiceId", "ServiceTypeId") + .HasName("pk_service_details"); + + b.HasIndex("ServiceTypeId") + .HasDatabaseName("ix_service_details_service_type_id"); + + b.ToTable("service_details", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ServiceType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_service_types"); + + b.ToTable("service_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "DATASPACE_SERVICE" + }, + new + { + Id = 2, + Label = "CONSULTANCY_SERVICE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.HasKey("Id") + .HasName("pk_technical_user_profiles"); + + b.HasIndex("OfferId") + .HasDatabaseName("ix_technical_user_profiles_offer_id"); + + b.ToTable("technical_user_profiles", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfileAssignedUserRole", b => + { + b.Property("TechnicalUserProfileId") + .HasColumnType("uuid") + .HasColumnName("technical_user_profile_id"); + + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.HasKey("TechnicalUserProfileId", "UserRoleId") + .HasName("pk_technical_user_profile_assigned_user_roles"); + + b.HasIndex("UserRoleId") + .HasDatabaseName("ix_technical_user_profile_assigned_user_roles_user_role_id"); + + b.ToTable("technical_user_profile_assigned_user_roles", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UniqueIdentifier", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_unique_identifiers"); + + b.ToTable("unique_identifiers", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "COMMERCIAL_REG_NUMBER" + }, + new + { + Id = 2, + Label = "VAT_ID" + }, + new + { + Id = 3, + Label = "LEI_CODE" + }, + new + { + Id = 4, + Label = "VIES" + }, + new + { + Id = 5, + Label = "EORI" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("name"); + + b.Property("Shortname") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("shortname"); + + b.HasKey("Id") + .HasName("pk_use_cases"); + + b.ToTable("use_cases", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCaseDescription", b => + { + b.Property("UseCaseId") + .HasColumnType("uuid") + .HasColumnName("use_case_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text") + .HasColumnName("description"); + + b.HasKey("UseCaseId", "LanguageShortName") + .HasName("pk_use_case_descriptions"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_use_case_descriptions_language_short_name"); + + b.ToTable("use_case_descriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("LastEditorId") + .HasColumnType("uuid") + .HasColumnName("last_editor_id"); + + b.Property("OfferId") + .HasColumnType("uuid") + .HasColumnName("offer_id"); + + b.Property("UserRoleText") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("user_role") + .HasAnnotation("Relational:JsonPropertyName", "user_role"); + + b.HasKey("Id") + .HasName("pk_user_roles"); + + b.HasIndex("LastEditorId") + .HasDatabaseName("ix_user_roles_last_editor_id"); + + b.HasIndex("OfferId") + .HasDatabaseName("ix_user_roles_offer_id"); + + b.ToTable("user_roles", "portal", t => + { + t.HasTrigger("LC_TRIGGER_AFTER_INSERT_USERROLE"); + + t.HasTrigger("LC_TRIGGER_AFTER_UPDATE_USERROLE"); + }); + + b + .HasAnnotation("LC_TRIGGER_AFTER_INSERT_USERROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_INSERT_USERROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_INSERT_USERROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_user_role20231115\" (\"id\", \"user_role\", \"offer_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"user_role\", \r\n NEW.\"offer_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 1, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_INSERT_USERROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_INSERT_USERROLE AFTER INSERT\r\nON \"portal\".\"user_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_INSERT_USERROLE\"();") + .HasAnnotation("LC_TRIGGER_AFTER_UPDATE_USERROLE", "CREATE FUNCTION \"portal\".\"LC_TRIGGER_AFTER_UPDATE_USERROLE\"() RETURNS trigger as $LC_TRIGGER_AFTER_UPDATE_USERROLE$\r\nBEGIN\r\n INSERT INTO \"portal\".\"audit_user_role20231115\" (\"id\", \"user_role\", \"offer_id\", \"last_editor_id\", \"audit_v1id\", \"audit_v1operation_id\", \"audit_v1date_last_changed\", \"audit_v1last_editor_id\") SELECT NEW.\"id\", \r\n NEW.\"user_role\", \r\n NEW.\"offer_id\", \r\n NEW.\"last_editor_id\", \r\n gen_random_uuid(), \r\n 2, \r\n CURRENT_TIMESTAMP, \r\n NEW.\"last_editor_id\";\r\nRETURN NEW;\r\nEND;\r\n$LC_TRIGGER_AFTER_UPDATE_USERROLE$ LANGUAGE plpgsql;\r\nCREATE TRIGGER LC_TRIGGER_AFTER_UPDATE_USERROLE AFTER UPDATE\r\nON \"portal\".\"user_roles\"\r\nFOR EACH ROW EXECUTE PROCEDURE \"portal\".\"LC_TRIGGER_AFTER_UPDATE_USERROLE\"();"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleAssignedCollection", b => + { + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.Property("UserRoleCollectionId") + .HasColumnType("uuid") + .HasColumnName("user_role_collection_id"); + + b.HasKey("UserRoleId", "UserRoleCollectionId") + .HasName("pk_user_role_assigned_collections"); + + b.HasIndex("UserRoleCollectionId") + .HasDatabaseName("ix_user_role_assigned_collections_user_role_collection_id"); + + b.ToTable("user_role_assigned_collections", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollection", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text") + .HasColumnName("name"); + + b.HasKey("Id") + .HasName("pk_user_role_collections"); + + b.ToTable("user_role_collections", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollectionDescription", b => + { + b.Property("UserRoleCollectionId") + .HasColumnType("uuid") + .HasColumnName("user_role_collection_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.HasKey("UserRoleCollectionId", "LanguageShortName") + .HasName("pk_user_role_collection_descriptions"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_user_role_collection_descriptions_language_short_name"); + + b.ToTable("user_role_collection_descriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleDescription", b => + { + b.Property("UserRoleId") + .HasColumnType("uuid") + .HasColumnName("user_role_id"); + + b.Property("LanguageShortName") + .HasMaxLength(2) + .HasColumnType("character(2)") + .HasColumnName("language_short_name"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.HasKey("UserRoleId", "LanguageShortName") + .HasName("pk_user_role_descriptions"); + + b.HasIndex("LanguageShortName") + .HasDatabaseName("ix_user_role_descriptions_language_short_name"); + + b.ToTable("user_role_descriptions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasColumnType("text") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_verified_credential_external_types"); + + b.ToTable("verified_credential_external_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "TRACEABILITY_CREDENTIAL" + }, + new + { + Id = 2, + Label = "PCF_CREDENTIAL" + }, + new + { + Id = 3, + Label = "BEHAVIOR_TWIN_CREDENTIAL" + }, + new + { + Id = 4, + Label = "VEHICLE_DISMANTLE" + }, + new + { + Id = 5, + Label = "SUSTAINABILITY_CREDENTIAL" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalTypeUseCaseDetailVersion", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Expiry") + .HasColumnType("timestamp with time zone") + .HasColumnName("expiry"); + + b.Property("Template") + .IsRequired() + .HasColumnType("text") + .HasColumnName("template"); + + b.Property("ValidFrom") + .HasColumnType("timestamp with time zone") + .HasColumnName("valid_from"); + + b.Property("VerifiedCredentialExternalTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_external_type_id"); + + b.Property("Version") + .IsRequired() + .HasColumnType("text") + .HasColumnName("version"); + + b.HasKey("Id") + .HasName("pk_verified_credential_external_type_use_case_detail_versions"); + + b.HasIndex("VerifiedCredentialExternalTypeId", "Version") + .IsUnique() + .HasDatabaseName("ix_verified_credential_external_type_use_case_detail_versions_"); + + b.ToTable("verified_credential_external_type_use_case_detail_versions", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_verified_credential_types"); + + b.ToTable("verified_credential_types", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "TRACEABILITY_FRAMEWORK" + }, + new + { + Id = 2, + Label = "PCF_FRAMEWORK" + }, + new + { + Id = 3, + Label = "BEHAVIOR_TWIN_FRAMEWORK" + }, + new + { + Id = 4, + Label = "DISMANTLER_CERTIFICATE" + }, + new + { + Id = 5, + Label = "SUSTAINABILITY_FRAMEWORK" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedExternalType", b => + { + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.Property("VerifiedCredentialExternalTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_external_type_id"); + + b.HasKey("VerifiedCredentialTypeId", "VerifiedCredentialExternalTypeId") + .HasName("pk_verified_credential_type_assigned_external_types"); + + b.HasIndex("VerifiedCredentialExternalTypeId") + .HasDatabaseName("ix_verified_credential_type_assigned_external_types_verified_c"); + + b.HasIndex("VerifiedCredentialTypeId") + .IsUnique() + .HasDatabaseName("ix_verified_credential_type_assigned_external_types_verified_c1"); + + b.ToTable("verified_credential_type_assigned_external_types", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedKind", b => + { + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.Property("VerifiedCredentialTypeKindId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_kind_id"); + + b.HasKey("VerifiedCredentialTypeId", "VerifiedCredentialTypeKindId") + .HasName("pk_verified_credential_type_assigned_kinds"); + + b.HasIndex("VerifiedCredentialTypeId") + .HasDatabaseName("ix_verified_credential_type_assigned_kinds_verified_credential"); + + b.HasIndex("VerifiedCredentialTypeKindId") + .HasDatabaseName("ix_verified_credential_type_assigned_kinds_verified_credential1"); + + b.ToTable("verified_credential_type_assigned_kinds", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedUseCase", b => + { + b.Property("VerifiedCredentialTypeId") + .HasColumnType("integer") + .HasColumnName("verified_credential_type_id"); + + b.Property("UseCaseId") + .HasColumnType("uuid") + .HasColumnName("use_case_id"); + + b.HasKey("VerifiedCredentialTypeId", "UseCaseId") + .HasName("pk_verified_credential_type_assigned_use_cases"); + + b.HasIndex("UseCaseId") + .IsUnique() + .HasDatabaseName("ix_verified_credential_type_assigned_use_cases_use_case_id"); + + b.HasIndex("VerifiedCredentialTypeId") + .IsUnique() + .HasDatabaseName("ix_verified_credential_type_assigned_use_cases_verified_creden"); + + b.ToTable("verified_credential_type_assigned_use_cases", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeKind", b => + { + b.Property("Id") + .HasColumnType("integer") + .HasColumnName("id"); + + b.Property("Label") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("label"); + + b.HasKey("Id") + .HasName("pk_verified_credential_type_kinds"); + + b.ToTable("verified_credential_type_kinds", "portal"); + + b.HasData( + new + { + Id = 1, + Label = "USE_CASE" + }, + new + { + Id = 2, + Label = "CERTIFICATE" + }); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompaniesLinkedServiceAccount", b => + { + b.Property("ServiceAccountId") + .HasColumnType("uuid") + .HasColumnName("service_account_id"); + + b.Property("Owners") + .HasColumnType("uuid") + .HasColumnName("owners"); + + b.Property("Provider") + .HasColumnType("uuid") + .HasColumnName("provider"); + + b.HasKey("ServiceAccountId"); + + b.ToTable((string)null); + + b.ToView("company_linked_service_accounts", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompanyConnectorView", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("company_name"); + + b.Property("ConnectorStatus") + .IsRequired() + .HasColumnType("text") + .HasColumnName("connector_status"); + + b.Property("ConnectorUrl") + .IsRequired() + .HasColumnType("text") + .HasColumnName("connector_url"); + + b.ToTable((string)null); + + b.ToView("company_connector_view", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompanyIdpView", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("company_name"); + + b.Property("IdpAlias") + .IsRequired() + .HasColumnType("text") + .HasColumnName("idp_alias"); + + b.ToTable((string)null); + + b.ToView("company_idp_view", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompanyRoleCollectionRolesView", b => + { + b.Property("ClientName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("client_name"); + + b.Property("CollectionName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("collection_name"); + + b.Property("UserRole") + .IsRequired() + .HasColumnType("text") + .HasColumnName("user_role"); + + b.ToTable((string)null); + + b.ToView("companyrole_collectionroles_view", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompanyUsersView", b => + { + b.Property("CompanyId") + .HasColumnType("uuid") + .HasColumnName("company_id"); + + b.Property("CompanyName") + .IsRequired() + .HasColumnType("text") + .HasColumnName("company_name"); + + b.Property("FirstName") + .HasColumnType("text") + .HasColumnName("first_name"); + + b.Property("LastName") + .HasColumnType("text") + .HasColumnName("last_name"); + + b.Property("UserEmail") + .HasColumnType("text") + .HasColumnName("user_email"); + + b.Property("UserStatus") + .IsRequired() + .HasColumnType("text") + .HasColumnName("user_status"); + + b.ToTable((string)null); + + b.ToView("company_users_view", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.OfferSubscriptionView", b => + { + b.Property("AppInstance") + .HasColumnType("uuid") + .HasColumnName("app_instance"); + + b.Property("Connector") + .HasColumnType("uuid") + .HasColumnName("connector"); + + b.Property("OfferTypeId") + .HasColumnType("integer") + .HasColumnName("offer_type_id"); + + b.Property("SubscriptionId") + .HasColumnType("uuid") + .HasColumnName("subscription_id"); + + b.Property("TechnicalUser") + .HasColumnType("uuid") + .HasColumnName("technical_user"); + + b.ToTable((string)null); + + b.ToView("offer_subscription_view", "portal"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Address", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", "Country") + .WithMany("Addresses") + .HasForeignKey("CountryAlpha2Code") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_addresses_countries_country_temp_id"); + + b.Navigation("Country"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementCategory", "AgreementCategory") + .WithMany("Agreements") + .HasForeignKey("AgreementCategoryId") + .IsRequired() + .HasConstraintName("fk_agreements_agreement_categories_agreement_category_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "Document") + .WithMany("Agreements") + .HasForeignKey("DocumentId") + .HasConstraintName("fk_agreements_documents_document_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "IssuerCompany") + .WithMany("Agreements") + .HasForeignKey("IssuerCompanyId") + .IsRequired() + .HasConstraintName("fk_agreements_companies_issuer_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", "UseCase") + .WithMany("Agreements") + .HasForeignKey("UseCaseId") + .HasConstraintName("fk_agreements_use_cases_use_case_id"); + + b.Navigation("AgreementCategory"); + + b.Navigation("Document"); + + b.Navigation("IssuerCompany"); + + b.Navigation("UseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedCompanyRole", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", "Agreement") + .WithMany("AgreementAssignedCompanyRoles") + .HasForeignKey("AgreementId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_company_roles_agreements_agreement_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", "CompanyRole") + .WithMany("AgreementAssignedCompanyRoles") + .HasForeignKey("CompanyRoleId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_company_roles_company_roles_company_role"); + + b.Navigation("Agreement"); + + b.Navigation("CompanyRole"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedOffer", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", "Agreement") + .WithMany("AgreementAssignedOffers") + .HasForeignKey("AgreementId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_offers_agreements_agreement_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("AgreementAssignedOffers") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_offers_offers_offer_id"); + + b.Navigation("Agreement"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementAssignedOfferType", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", "Agreement") + .WithMany("AgreementAssignedOfferTypes") + .HasForeignKey("AgreementId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_offer_types_agreements_agreement_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferType", "OfferType") + .WithMany("AgreementAssignedOfferTypes") + .HasForeignKey("OfferTypeId") + .IsRequired() + .HasConstraintName("fk_agreement_assigned_offer_types_offer_types_offer_type_id"); + + b.Navigation("Agreement"); + + b.Navigation("OfferType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppAssignedUseCase", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "App") + .WithMany() + .HasForeignKey("AppId") + .IsRequired() + .HasConstraintName("fk_app_assigned_use_cases_offers_app_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", "UseCase") + .WithMany() + .HasForeignKey("UseCaseId") + .IsRequired() + .HasConstraintName("fk_app_assigned_use_cases_use_cases_use_case_id"); + + b.Navigation("App"); + + b.Navigation("UseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstance", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "App") + .WithMany("AppInstances") + .HasForeignKey("AppId") + .OnDelete(DeleteBehavior.SetNull) + .IsRequired() + .HasConstraintName("fk_app_instances_offers_app_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamClient", "IamClient") + .WithMany("AppInstances") + .HasForeignKey("IamClientId") + .OnDelete(DeleteBehavior.SetNull) + .IsRequired() + .HasConstraintName("fk_app_instances_iam_clients_iam_client_id"); + + b.Navigation("App"); + + b.Navigation("IamClient"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstanceAssignedCompanyServiceAccount", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstance", "AppInstance") + .WithMany("ServiceAccounts") + .HasForeignKey("AppInstanceId") + .IsRequired() + .HasConstraintName("fk_app_instance_assigned_service_accounts_app_instances_app_in"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", "CompanyServiceAccount") + .WithMany("AppInstances") + .HasForeignKey("CompanyServiceAccountId") + .IsRequired() + .HasConstraintName("fk_app_instance_assigned_service_accounts_company_service_acco"); + + b.Navigation("AppInstance"); + + b.Navigation("CompanyServiceAccount"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstanceSetup", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "App") + .WithOne("AppInstanceSetup") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstanceSetup", "AppId") + .IsRequired() + .HasConstraintName("fk_app_instance_setups_offers_app_id"); + + b.Navigation("App"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppLanguage", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "App") + .WithMany() + .HasForeignKey("AppId") + .IsRequired() + .HasConstraintName("fk_app_languages_offers_app_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany() + .HasForeignKey("LanguageShortName") + .IsRequired() + .HasConstraintName("fk_app_languages_languages_language_temp_id"); + + b.Navigation("App"); + + b.Navigation("Language"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppSubscriptionDetail", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstance", "AppInstance") + .WithMany("AppSubscriptionDetails") + .HasForeignKey("AppInstanceId") + .HasConstraintName("fk_app_subscription_details_app_instances_app_instance_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_app_subscription_details_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "OfferSubscription") + .WithOne("AppSubscriptionDetail") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppSubscriptionDetail", "OfferSubscriptionId") + .IsRequired() + .HasConstraintName("fk_app_subscription_details_offer_subscriptions_offer_subscrip"); + + b.Navigation("AppInstance"); + + b.Navigation("LastEditor"); + + b.Navigation("OfferSubscription"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntry", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryStatus", "ApplicationChecklistEntryStatus") + .WithMany("ApplicationChecklistEntries") + .HasForeignKey("ApplicationChecklistEntryStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_application_checklist_application_checklist_statuses_applic"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryType", "ApplicationChecklistEntryType") + .WithMany("ApplicationChecklistEntries") + .HasForeignKey("ApplicationChecklistEntryTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_application_checklist_application_checklist_types_applicati"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", "Application") + .WithMany("ApplicationChecklistEntries") + .HasForeignKey("ApplicationId") + .IsRequired() + .HasConstraintName("fk_application_checklist_company_applications_application_id"); + + b.Navigation("Application"); + + b.Navigation("ApplicationChecklistEntryStatus"); + + b.Navigation("ApplicationChecklistEntryType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Address", "Address") + .WithMany("Companies") + .HasForeignKey("AddressId") + .HasConstraintName("fk_companies_addresses_address_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyStatus", "CompanyStatus") + .WithMany("Companies") + .HasForeignKey("CompanyStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_companies_company_statuses_company_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "SelfDescriptionDocument") + .WithMany("Companies") + .HasForeignKey("SelfDescriptionDocumentId") + .HasConstraintName("fk_companies_documents_self_description_document_id"); + + b.Navigation("Address"); + + b.Navigation("CompanyStatus"); + + b.Navigation("SelfDescriptionDocument"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationStatus", "ApplicationStatus") + .WithMany("CompanyApplications") + .HasForeignKey("ApplicationStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_applications_company_application_statuses_applicati"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", "ChecklistProcess") + .WithOne("CompanyApplication") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", "ChecklistProcessId") + .HasConstraintName("fk_company_applications_processes_checklist_process_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationType", "CompanyApplicationType") + .WithMany("CompanyApplications") + .HasForeignKey("CompanyApplicationTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_applications_company_application_types_company_appl"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("CompanyApplications") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_applications_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_company_applications_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "OnboardingServiceProvider") + .WithMany("ProvidedApplications") + .HasForeignKey("OnboardingServiceProviderId") + .HasConstraintName("fk_company_applications_companies_onboarding_service_provider_"); + + b.Navigation("ApplicationStatus"); + + b.Navigation("ChecklistProcess"); + + b.Navigation("Company"); + + b.Navigation("CompanyApplicationType"); + + b.Navigation("LastEditor"); + + b.Navigation("OnboardingServiceProvider"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyAssignedRole", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("CompanyAssignedRoles") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_assigned_roles_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", "CompanyRole") + .WithMany("CompanyAssignedRoles") + .HasForeignKey("CompanyRoleId") + .IsRequired() + .HasConstraintName("fk_company_assigned_roles_company_roles_company_role_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_company_assigned_roles_identities_last_editor_id"); + + b.Navigation("Company"); + + b.Navigation("CompanyRole"); + + b.Navigation("LastEditor"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyAssignedUseCase", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("CompanyAssignedUseCase") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_assigned_use_cases_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", "UseCase") + .WithMany("CompanyAssignedUseCase") + .HasForeignKey("UseCaseId") + .IsRequired() + .HasConstraintName("fk_company_assigned_use_cases_use_cases_use_case_id"); + + b.Navigation("Company"); + + b.Navigation("UseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyIdentifier", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("CompanyIdentifiers") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_identifiers_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UniqueIdentifier", "UniqueIdentifier") + .WithMany("CompanyIdentifiers") + .HasForeignKey("UniqueIdentifierId") + .IsRequired() + .HasConstraintName("fk_company_identifiers_unique_identifiers_unique_identifier_id"); + + b.Navigation("Company"); + + b.Navigation("UniqueIdentifier"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyIdentityProvider", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany() + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_identity_providers_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", "IdentityProvider") + .WithMany("CompanyIdentityProviders") + .HasForeignKey("IdentityProviderId") + .IsRequired() + .HasConstraintName("fk_company_identity_providers_identity_providers_identity_prov"); + + b.Navigation("Company"); + + b.Navigation("IdentityProvider"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleAssignedRoleCollection", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", "CompanyRole") + .WithOne("CompanyRoleAssignedRoleCollection") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleAssignedRoleCollection", "CompanyRoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_role_assigned_role_collections_company_roles_compan"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollection", "UserRoleCollection") + .WithOne("CompanyRoleAssignedRoleCollection") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleAssignedRoleCollection", "UserRoleCollectionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_role_assigned_role_collections_user_role_collection"); + + b.Navigation("CompanyRole"); + + b.Navigation("UserRoleCollection"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleDescription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", "CompanyRole") + .WithMany("CompanyRoleDescriptions") + .HasForeignKey("CompanyRoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_role_descriptions_company_roles_company_role_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("CompanyRoleDescriptions") + .HasForeignKey("LanguageShortName") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_role_descriptions_languages_language_temp_id1"); + + b.Navigation("CompanyRole"); + + b.Navigation("Language"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleRegistrationData", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", "CompanyRole") + .WithOne("CompanyRoleRegistrationData") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRoleRegistrationData", "CompanyRoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_role_registration_data_company_roles_company_role_id"); + + b.Navigation("CompanyRole"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccountType", "CompanyServiceAccountType") + .WithMany("CompanyServiceAccounts") + .HasForeignKey("CompanyServiceAccountTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_service_accounts_company_service_account_types_comp"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "Identity") + .WithOne("CompanyServiceAccount") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", "Id") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_service_accounts_identities_identity_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "OfferSubscription") + .WithMany("CompanyServiceAccounts") + .HasForeignKey("OfferSubscriptionId") + .HasConstraintName("fk_company_service_accounts_offer_subscriptions_offer_subscrip"); + + b.Navigation("CompanyServiceAccountType"); + + b.Navigation("Identity"); + + b.Navigation("OfferSubscription"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetail", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("CompanySsiDetails") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_company_ssi_details_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetailStatus", "CompanySsiDetailStatus") + .WithMany("CompanySsiDetails") + .HasForeignKey("CompanySsiDetailStatusId") + .IsRequired() + .HasConstraintName("fk_company_ssi_details_company_ssi_detail_statuses_company_ssi"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CreatorUser") + .WithMany("CompanySsiDetails") + .HasForeignKey("CreatorUserId") + .IsRequired() + .HasConstraintName("fk_company_ssi_details_company_users_creator_user_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "Document") + .WithOne("CompanySsiDetail") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetail", "DocumentId") + .IsRequired() + .HasConstraintName("fk_company_ssi_details_documents_document_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_company_ssi_details_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalTypeUseCaseDetailVersion", "VerifiedCredentialExternalTypeUseCaseDetailVersion") + .WithMany("CompanySsiDetails") + .HasForeignKey("VerifiedCredentialExternalTypeUseCaseDetailId") + .HasConstraintName("fk_company_ssi_details_verified_credential_external_type_use_c"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", "VerifiedCredentialType") + .WithMany("CompanySsiDetails") + .HasForeignKey("VerifiedCredentialTypeId") + .IsRequired() + .HasConstraintName("fk_company_ssi_details_verified_credential_types_verified_cred"); + + b.Navigation("Company"); + + b.Navigation("CompanySsiDetailStatus"); + + b.Navigation("CreatorUser"); + + b.Navigation("Document"); + + b.Navigation("LastEditor"); + + b.Navigation("VerifiedCredentialExternalTypeUseCaseDetailVersion"); + + b.Navigation("VerifiedCredentialType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "Identity") + .WithOne("CompanyUser") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "Id") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_users_identities_identity_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_company_users_identities_last_editor_id"); + + b.Navigation("Identity"); + + b.Navigation("LastEditor"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedAppFavourite", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "App") + .WithMany() + .HasForeignKey("AppId") + .IsRequired() + .HasConstraintName("fk_company_user_assigned_app_favourites_offers_app_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany() + .HasForeignKey("CompanyUserId") + .IsRequired() + .HasConstraintName("fk_company_user_assigned_app_favourites_company_users_company_"); + + b.Navigation("App"); + + b.Navigation("CompanyUser"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedBusinessPartner", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany("CompanyUserAssignedBusinessPartners") + .HasForeignKey("CompanyUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_user_assigned_business_partners_company_users_compa"); + + b.Navigation("CompanyUser"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUserAssignedIdentityProvider", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany("CompanyUserAssignedIdentityProviders") + .HasForeignKey("CompanyUserId") + .IsRequired() + .HasConstraintName("fk_company_user_assigned_identity_providers_company_users_comp"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", "IdentityProvider") + .WithMany("CompanyUserAssignedIdentityProviders") + .HasForeignKey("IdentityProviderId") + .IsRequired() + .HasConstraintName("fk_company_user_assigned_identity_providers_identity_providers"); + + b.Navigation("CompanyUser"); + + b.Navigation("IdentityProvider"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", "CompanyServiceAccount") + .WithOne("Connector") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", "CompanyServiceAccountId") + .HasConstraintName("fk_connectors_company_service_accounts_company_service_account"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Host") + .WithMany("HostedConnectors") + .HasForeignKey("HostId") + .HasConstraintName("fk_connectors_companies_host_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_connectors_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", "Location") + .WithMany("Connectors") + .HasForeignKey("LocationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_connectors_countries_location_temp_id1"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Provider") + .WithMany("ProvidedConnectors") + .HasForeignKey("ProviderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_connectors_companies_provider_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "SelfDescriptionDocument") + .WithOne("Connector") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", "SelfDescriptionDocumentId") + .HasConstraintName("fk_connectors_documents_self_description_document_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorStatus", "Status") + .WithMany("Connectors") + .HasForeignKey("StatusId") + .IsRequired() + .HasConstraintName("fk_connectors_connector_statuses_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorType", "Type") + .WithMany("Connectors") + .HasForeignKey("TypeId") + .IsRequired() + .HasConstraintName("fk_connectors_connector_types_type_id"); + + b.Navigation("CompanyServiceAccount"); + + b.Navigation("Host"); + + b.Navigation("LastEditor"); + + b.Navigation("Location"); + + b.Navigation("Provider"); + + b.Navigation("SelfDescriptionDocument"); + + b.Navigation("Status"); + + b.Navigation("Type"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorAssignedOfferSubscription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", "Connector") + .WithMany("ConnectorAssignedOfferSubscriptions") + .HasForeignKey("ConnectorId") + .IsRequired() + .HasConstraintName("fk_connector_assigned_offer_subscriptions_connectors_connector"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "OfferSubscription") + .WithMany("ConnectorAssignedOfferSubscriptions") + .HasForeignKey("OfferSubscriptionId") + .IsRequired() + .HasConstraintName("fk_connector_assigned_offer_subscriptions_offer_subscriptions_"); + + b.Navigation("Connector"); + + b.Navigation("OfferSubscription"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Consent", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", "Agreement") + .WithMany("Consents") + .HasForeignKey("AgreementId") + .IsRequired() + .HasConstraintName("fk_consents_agreements_agreement_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("Consents") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_consents_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany("Consents") + .HasForeignKey("CompanyUserId") + .IsRequired() + .HasConstraintName("fk_consents_company_users_company_user_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentStatus", "ConsentStatus") + .WithMany("Consents") + .HasForeignKey("ConsentStatusId") + .IsRequired() + .HasConstraintName("fk_consents_consent_statuses_consent_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "Document") + .WithMany("Consents") + .HasForeignKey("DocumentId") + .HasConstraintName("fk_consents_documents_document_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_consents_identities_last_editor_id"); + + b.Navigation("Agreement"); + + b.Navigation("Company"); + + b.Navigation("CompanyUser"); + + b.Navigation("ConsentStatus"); + + b.Navigation("Document"); + + b.Navigation("LastEditor"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentAssignedOffer", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Consent", "Consent") + .WithMany("ConsentAssignedOffers") + .HasForeignKey("ConsentId") + .IsRequired() + .HasConstraintName("fk_consent_assigned_offers_consents_consent_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("ConsentAssignedOffers") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_consent_assigned_offers_offers_offer_id"); + + b.Navigation("Consent"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentAssignedOfferSubscription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Consent", "Consent") + .WithMany("ConsentAssignedOfferSubscriptions") + .HasForeignKey("ConsentId") + .IsRequired() + .HasConstraintName("fk_consent_assigned_offer_subscriptions_consents_consent_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "OfferSubscription") + .WithMany("ConsentAssignedOfferSubscriptions") + .HasForeignKey("OfferSubscriptionId") + .IsRequired() + .HasConstraintName("fk_consent_assigned_offer_subscriptions_offer_subscriptions_of"); + + b.Navigation("Consent"); + + b.Navigation("OfferSubscription"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CountryAssignedIdentifier", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.BpdmIdentifier", "BpdmIdentifier") + .WithMany("CountryAssignedIdentifiers") + .HasForeignKey("BpdmIdentifierId") + .HasConstraintName("fk_country_assigned_identifiers_bpdm_identifiers_bpdm_identifi"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", "Country") + .WithMany("CountryAssignedIdentifiers") + .HasForeignKey("CountryAlpha2Code") + .IsRequired() + .HasConstraintName("fk_country_assigned_identifiers_countries_country_alpha2code"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UniqueIdentifier", "UniqueIdentifier") + .WithMany("CountryAssignedIdentifiers") + .HasForeignKey("UniqueIdentifierId") + .IsRequired() + .HasConstraintName("fk_country_assigned_identifiers_unique_identifiers_unique_iden"); + + b.Navigation("BpdmIdentifier"); + + b.Navigation("Country"); + + b.Navigation("UniqueIdentifier"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CountryLongName", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", "Country") + .WithMany("CountryLongNames") + .HasForeignKey("Alpha2Code") + .IsRequired() + .HasConstraintName("fk_country_long_names_countries_country_alpha2code"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("CountryLongNames") + .HasForeignKey("ShortName") + .IsRequired() + .HasConstraintName("fk_country_long_names_languages_language_temp_id2"); + + b.Navigation("Country"); + + b.Navigation("Language"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany("Documents") + .HasForeignKey("CompanyUserId") + .HasConstraintName("fk_documents_company_users_company_user_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentStatus", "DocumentStatus") + .WithMany("Documents") + .HasForeignKey("DocumentStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_documents_document_status_document_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentType", "DocumentType") + .WithMany("Documents") + .HasForeignKey("DocumentTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_documents_document_types_document_type_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.MediaType", "MediaType") + .WithMany("Documents") + .HasForeignKey("MediaTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_documents_media_types_media_type_id"); + + b.Navigation("CompanyUser"); + + b.Navigation("DocumentStatus"); + + b.Navigation("DocumentType"); + + b.Navigation("MediaType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamIdentityProvider", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", "IdentityProvider") + .WithOne("IamIdentityProvider") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamIdentityProvider", "IdentityProviderId") + .IsRequired() + .HasConstraintName("fk_iam_identity_providers_identity_providers_identity_provider"); + + b.Navigation("IdentityProvider"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("Identities") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_identities_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityType", "IdentityType") + .WithMany("Identities") + .HasForeignKey("IdentityTypeId") + .IsRequired() + .HasConstraintName("fk_identities_identity_type_identity_type_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_identities_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityUserStatus", "IdentityStatus") + .WithMany("Identities") + .HasForeignKey("UserStatusId") + .IsRequired() + .HasConstraintName("fk_identities_identity_user_statuses_identity_status_id"); + + b.Navigation("Company"); + + b.Navigation("IdentityStatus"); + + b.Navigation("IdentityType"); + + b.Navigation("LastEditor"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityAssignedRole", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "Identity") + .WithMany("IdentityAssignedRoles") + .HasForeignKey("IdentityId") + .IsRequired() + .HasConstraintName("fk_identity_assigned_roles_identities_identity_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_identity_assigned_roles_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", "UserRole") + .WithMany("IdentityAssignedRoles") + .HasForeignKey("UserRoleId") + .IsRequired() + .HasConstraintName("fk_identity_assigned_roles_user_roles_user_role_id"); + + b.Navigation("Identity"); + + b.Navigation("LastEditor"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderCategory", "IdentityProviderCategory") + .WithMany("IdentityProviders") + .HasForeignKey("IdentityProviderCategoryId") + .IsRequired() + .HasConstraintName("fk_identity_providers_identity_provider_categories_identity_pr"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderType", "IdentityProviderType") + .WithMany("IdentityProviders") + .HasForeignKey("IdentityProviderTypeId") + .IsRequired() + .HasConstraintName("fk_identity_providers_identity_provider_types_identity_provide"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Owner") + .WithMany("OwnedIdentityProviders") + .HasForeignKey("OwnerId") + .IsRequired() + .HasConstraintName("fk_identity_providers_companies_owner_id"); + + b.Navigation("IdentityProviderCategory"); + + b.Navigation("IdentityProviderType"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Invitation", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", "CompanyApplication") + .WithMany("Invitations") + .HasForeignKey("CompanyApplicationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_invitations_company_applications_company_application_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "CompanyUser") + .WithMany("Invitations") + .HasForeignKey("CompanyUserId") + .IsRequired() + .HasConstraintName("fk_invitations_company_users_company_user_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.InvitationStatus", "InvitationStatus") + .WithMany("Invitations") + .HasForeignKey("InvitationStatusId") + .IsRequired() + .HasConstraintName("fk_invitations_invitation_statuses_invitation_status_id"); + + b.Navigation("CompanyApplication"); + + b.Navigation("CompanyUser"); + + b.Navigation("InvitationStatus"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.LanguageLongName", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "LongNameLanguage") + .WithMany("LanguageLongNameLanguages") + .HasForeignKey("LanguageShortName") + .IsRequired() + .HasConstraintName("fk_language_long_names_languages_long_name_language_short_name"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("LanguageLongNames") + .HasForeignKey("ShortName") + .IsRequired() + .HasConstraintName("fk_language_long_names_languages_language_short_name"); + + b.Navigation("Language"); + + b.Navigation("LongNameLanguage"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NetworkRegistration", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", "CompanyApplication") + .WithOne("NetworkRegistration") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NetworkRegistration", "ApplicationId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_network_registrations_company_applications_application_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithOne("NetworkRegistration") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NetworkRegistration", "CompanyId") + .IsRequired() + .HasConstraintName("fk_network_registrations_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "OnboardingServiceProvider") + .WithMany("OnboardedNetworkRegistrations") + .HasForeignKey("OnboardingServiceProviderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_network_registrations_companies_onboarding_service_provider"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", "Process") + .WithOne("NetworkRegistration") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NetworkRegistration", "ProcessId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_network_registrations_processes_process_id"); + + b.Navigation("Company"); + + b.Navigation("CompanyApplication"); + + b.Navigation("OnboardingServiceProvider"); + + b.Navigation("Process"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Notification", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "Creator") + .WithMany("CreatedNotifications") + .HasForeignKey("CreatorUserId") + .HasConstraintName("fk_notifications_identities_creator_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationType", "NotificationType") + .WithMany("Notifications") + .HasForeignKey("NotificationTypeId") + .IsRequired() + .HasConstraintName("fk_notifications_notification_type_notification_type_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "Receiver") + .WithMany("Notifications") + .HasForeignKey("ReceiverUserId") + .IsRequired() + .HasConstraintName("fk_notifications_company_users_receiver_id"); + + b.Navigation("Creator"); + + b.Navigation("NotificationType"); + + b.Navigation("Receiver"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTypeAssignedTopic", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTopic", "NotificationTopic") + .WithMany("NotificationTypeAssignedTopics") + .HasForeignKey("NotificationTopicId") + .IsRequired() + .HasConstraintName("fk_notification_type_assigned_topics_notification_topic_notifi"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationType", "NotificationType") + .WithOne("NotificationTypeAssignedTopic") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTypeAssignedTopic", "NotificationTypeId") + .IsRequired() + .HasConstraintName("fk_notification_type_assigned_topics_notification_type_notific"); + + b.Navigation("NotificationTopic"); + + b.Navigation("NotificationType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_offers_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.LicenseType", "LicenseType") + .WithMany("Offers") + .HasForeignKey("LicenseTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_offers_license_types_license_type_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferStatus", "OfferStatus") + .WithMany("Offers") + .HasForeignKey("OfferStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_offers_offer_statuses_offer_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferType", "OfferType") + .WithMany("Offers") + .HasForeignKey("OfferTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_offers_offer_types_offer_type_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "ProviderCompany") + .WithMany("ProvidedOffers") + .HasForeignKey("ProviderCompanyId") + .HasConstraintName("fk_offers_companies_provider_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "SalesManager") + .WithMany("SalesManagerOfOffers") + .HasForeignKey("SalesManagerId") + .HasConstraintName("fk_offers_company_users_sales_manager_id"); + + b.Navigation("LastEditor"); + + b.Navigation("LicenseType"); + + b.Navigation("OfferStatus"); + + b.Navigation("OfferType"); + + b.Navigation("ProviderCompany"); + + b.Navigation("SalesManager"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedDocument", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", "Document") + .WithMany() + .HasForeignKey("DocumentId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_documents_documents_document_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany() + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_documents_offers_offer_id"); + + b.Navigation("Document"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedLicense", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany() + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_licenses_offers_offer_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferLicense", "OfferLicense") + .WithMany() + .HasForeignKey("OfferLicenseId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_licenses_offer_licenses_offer_license_id"); + + b.Navigation("Offer"); + + b.Navigation("OfferLicense"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferAssignedPrivacyPolicy", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("OfferAssignedPrivacyPolicies") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_privacy_policies_offers_offer_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.PrivacyPolicy", "PrivacyPolicy") + .WithMany("OfferAssignedPrivacyPolicies") + .HasForeignKey("PrivacyPolicyId") + .IsRequired() + .HasConstraintName("fk_offer_assigned_privacy_policies_privacy_policies_privacy_po"); + + b.Navigation("Offer"); + + b.Navigation("PrivacyPolicy"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferDescription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("AppDescriptions") + .HasForeignKey("LanguageShortName") + .IsRequired() + .HasConstraintName("fk_offer_descriptions_languages_language_short_name"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("OfferDescriptions") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_descriptions_offers_offer_id"); + + b.Navigation("Language"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithMany("OfferSubscriptions") + .HasForeignKey("CompanyId") + .IsRequired() + .HasConstraintName("fk_offer_subscriptions_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_offer_subscriptions_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("OfferSubscriptions") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_subscriptions_offers_offer_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionStatus", "OfferSubscriptionStatus") + .WithMany("OfferSubscriptions") + .HasForeignKey("OfferSubscriptionStatusId") + .IsRequired() + .HasConstraintName("fk_offer_subscriptions_offer_subscription_statuses_offer_subsc"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", "Process") + .WithOne("OfferSubscription") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "ProcessId") + .HasConstraintName("fk_offer_subscriptions_processes_process_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", "Requester") + .WithMany("RequestedSubscriptions") + .HasForeignKey("RequesterId") + .IsRequired() + .HasConstraintName("fk_offer_subscriptions_company_users_requester_id"); + + b.Navigation("Company"); + + b.Navigation("LastEditor"); + + b.Navigation("Offer"); + + b.Navigation("OfferSubscriptionStatus"); + + b.Navigation("Process"); + + b.Navigation("Requester"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionProcessData", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", "OfferSubscription") + .WithOne("OfferSubscriptionProcessData") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionProcessData", "OfferSubscriptionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_offer_subscriptions_process_datas_offer_subscriptions_offer"); + + b.Navigation("OfferSubscription"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferTag", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("Tags") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_offer_tags_offers_offer_id"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OnboardingServiceProviderDetail", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithOne("OnboardingServiceProviderDetail") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OnboardingServiceProviderDetail", "CompanyId") + .IsRequired() + .HasConstraintName("fk_onboarding_service_provider_details_companies_company_id"); + + b.Navigation("Company"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessType", "ProcessType") + .WithMany("Processes") + .HasForeignKey("ProcessTypeId") + .IsRequired() + .HasConstraintName("fk_processes_process_types_process_type_id"); + + b.Navigation("ProcessType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStep", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", "Process") + .WithMany("ProcessSteps") + .HasForeignKey("ProcessId") + .IsRequired() + .HasConstraintName("fk_process_steps_processes_process_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepStatus", "ProcessStepStatus") + .WithMany("ProcessSteps") + .HasForeignKey("ProcessStepStatusId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_process_steps_process_step_statuses_process_step_status_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepType", "ProcessStepType") + .WithMany("ProcessSteps") + .HasForeignKey("ProcessStepTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_process_steps_process_step_types_process_step_type_id"); + + b.Navigation("Process"); + + b.Navigation("ProcessStepStatus"); + + b.Navigation("ProcessStepType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProviderCompanyDetail", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", "Company") + .WithOne("ProviderCompanyDetail") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProviderCompanyDetail", "CompanyId") + .IsRequired() + .HasConstraintName("fk_provider_company_details_companies_company_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_provider_company_details_identities_last_editor_id"); + + b.Navigation("Company"); + + b.Navigation("LastEditor"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ServiceDetail", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Service") + .WithMany("ServiceDetails") + .HasForeignKey("ServiceId") + .IsRequired() + .HasConstraintName("fk_service_details_offers_service_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ServiceType", "ServiceType") + .WithMany("ServiceDetails") + .HasForeignKey("ServiceTypeId") + .IsRequired() + .HasConstraintName("fk_service_details_service_types_service_type_id"); + + b.Navigation("Service"); + + b.Navigation("ServiceType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfile", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("TechnicalUserProfiles") + .HasForeignKey("OfferId") + .IsRequired() + .HasConstraintName("fk_technical_user_profiles_offers_offer_id"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfileAssignedUserRole", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfile", "TechnicalUserProfile") + .WithMany("TechnicalUserProfileAssignedUserRoles") + .HasForeignKey("TechnicalUserProfileId") + .IsRequired() + .HasConstraintName("fk_technical_user_profile_assigned_user_roles_technical_user_p"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", "UserRole") + .WithMany("TechnicalUserProfileAssignedUserRole") + .HasForeignKey("UserRoleId") + .IsRequired() + .HasConstraintName("fk_technical_user_profile_assigned_user_roles_user_roles_user_r"); + + b.Navigation("TechnicalUserProfile"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCaseDescription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("UseCases") + .HasForeignKey("LanguageShortName") + .IsRequired() + .HasConstraintName("fk_use_case_descriptions_languages_language_short_name"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", "UseCase") + .WithMany("UseCaseDescriptions") + .HasForeignKey("UseCaseId") + .IsRequired() + .HasConstraintName("fk_use_case_descriptions_use_cases_use_case_id"); + + b.Navigation("Language"); + + b.Navigation("UseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", "LastEditor") + .WithMany() + .HasForeignKey("LastEditorId") + .HasConstraintName("fk_user_roles_identities_last_editor_id"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", "Offer") + .WithMany("UserRoles") + .HasForeignKey("OfferId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_roles_offers_offer_id"); + + b.Navigation("LastEditor"); + + b.Navigation("Offer"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleAssignedCollection", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollection", "UserRoleCollection") + .WithMany() + .HasForeignKey("UserRoleCollectionId") + .IsRequired() + .HasConstraintName("fk_user_role_assigned_collections_user_role_collections_user_r"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", "UserRole") + .WithMany() + .HasForeignKey("UserRoleId") + .IsRequired() + .HasConstraintName("fk_user_role_assigned_collections_user_roles_user_role_id"); + + b.Navigation("UserRole"); + + b.Navigation("UserRoleCollection"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollectionDescription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany() + .HasForeignKey("LanguageShortName") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_role_collection_descriptions_languages_language_short_"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollection", "UserRoleCollection") + .WithMany("UserRoleCollectionDescriptions") + .HasForeignKey("UserRoleCollectionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_role_collection_descriptions_user_role_collections_use"); + + b.Navigation("Language"); + + b.Navigation("UserRoleCollection"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleDescription", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", "Language") + .WithMany("UserRoleDescriptions") + .HasForeignKey("LanguageShortName") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_role_descriptions_languages_language_short_name"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", "UserRole") + .WithMany("UserRoleDescriptions") + .HasForeignKey("UserRoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_role_descriptions_user_roles_user_role_id"); + + b.Navigation("Language"); + + b.Navigation("UserRole"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalTypeUseCaseDetailVersion", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalType", "VerifiedCredentialExternalType") + .WithMany("VerifiedCredentialExternalTypeUseCaseDetailVersions") + .HasForeignKey("VerifiedCredentialExternalTypeId") + .IsRequired() + .HasConstraintName("fk_verified_credential_external_type_use_case_detail_versions_"); + + b.Navigation("VerifiedCredentialExternalType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedExternalType", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalType", "VerifiedCredentialExternalType") + .WithMany("VerifiedCredentialTypeAssignedExternalTypes") + .HasForeignKey("VerifiedCredentialExternalTypeId") + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_external_types_verified_c"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", "VerifiedCredentialType") + .WithOne("VerifiedCredentialTypeAssignedExternalType") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedExternalType", "VerifiedCredentialTypeId") + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_external_types_verified_c1"); + + b.Navigation("VerifiedCredentialExternalType"); + + b.Navigation("VerifiedCredentialType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedKind", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", "VerifiedCredentialType") + .WithOne("VerifiedCredentialTypeAssignedKind") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedKind", "VerifiedCredentialTypeId") + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_kinds_verified_credential"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeKind", "VerifiedCredentialTypeKind") + .WithMany("VerifiedCredentialTypeAssignedKinds") + .HasForeignKey("VerifiedCredentialTypeKindId") + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_kinds_verified_credential1"); + + b.Navigation("VerifiedCredentialType"); + + b.Navigation("VerifiedCredentialTypeKind"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedUseCase", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", "UseCase") + .WithOne("VerifiedCredentialAssignedUseCase") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedUseCase", "UseCaseId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_use_cases_use_cases_use_c"); + + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", "VerifiedCredentialType") + .WithOne("VerifiedCredentialTypeAssignedUseCase") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeAssignedUseCase", "VerifiedCredentialTypeId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_verified_credential_type_assigned_use_cases_verified_creden"); + + b.Navigation("UseCase"); + + b.Navigation("VerifiedCredentialType"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompaniesLinkedServiceAccount", b => + { + b.HasOne("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", "CompanyServiceAccount") + .WithOne("CompaniesLinkedServiceAccount") + .HasForeignKey("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Views.CompaniesLinkedServiceAccount", "ServiceAccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_company_linked_service_accounts_company_service_accounts_co"); + + b.Navigation("CompanyServiceAccount"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Address", b => + { + b.Navigation("Companies"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Agreement", b => + { + b.Navigation("AgreementAssignedCompanyRoles"); + + b.Navigation("AgreementAssignedOfferTypes"); + + b.Navigation("AgreementAssignedOffers"); + + b.Navigation("Consents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AgreementCategory", b => + { + b.Navigation("Agreements"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.AppInstance", b => + { + b.Navigation("AppSubscriptionDetails"); + + b.Navigation("ServiceAccounts"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryStatus", b => + { + b.Navigation("ApplicationChecklistEntries"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ApplicationChecklistEntryType", b => + { + b.Navigation("ApplicationChecklistEntries"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.BpdmIdentifier", b => + { + b.Navigation("CountryAssignedIdentifiers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Company", b => + { + b.Navigation("Agreements"); + + b.Navigation("CompanyApplications"); + + b.Navigation("CompanyAssignedRoles"); + + b.Navigation("CompanyAssignedUseCase"); + + b.Navigation("CompanyIdentifiers"); + + b.Navigation("CompanySsiDetails"); + + b.Navigation("Consents"); + + b.Navigation("HostedConnectors"); + + b.Navigation("Identities"); + + b.Navigation("NetworkRegistration"); + + b.Navigation("OfferSubscriptions"); + + b.Navigation("OnboardedNetworkRegistrations"); + + b.Navigation("OnboardingServiceProviderDetail"); + + b.Navigation("OwnedIdentityProviders"); + + b.Navigation("ProvidedApplications"); + + b.Navigation("ProvidedConnectors"); + + b.Navigation("ProvidedOffers"); + + b.Navigation("ProviderCompanyDetail"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplication", b => + { + b.Navigation("ApplicationChecklistEntries"); + + b.Navigation("Invitations"); + + b.Navigation("NetworkRegistration"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationStatus", b => + { + b.Navigation("CompanyApplications"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyApplicationType", b => + { + b.Navigation("CompanyApplications"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyRole", b => + { + b.Navigation("AgreementAssignedCompanyRoles"); + + b.Navigation("CompanyAssignedRoles"); + + b.Navigation("CompanyRoleAssignedRoleCollection"); + + b.Navigation("CompanyRoleDescriptions"); + + b.Navigation("CompanyRoleRegistrationData"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccount", b => + { + b.Navigation("AppInstances"); + + b.Navigation("CompaniesLinkedServiceAccount"); + + b.Navigation("Connector"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyServiceAccountType", b => + { + b.Navigation("CompanyServiceAccounts"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanySsiDetailStatus", b => + { + b.Navigation("CompanySsiDetails"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyStatus", b => + { + b.Navigation("Companies"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.CompanyUser", b => + { + b.Navigation("CompanySsiDetails"); + + b.Navigation("CompanyUserAssignedBusinessPartners"); + + b.Navigation("CompanyUserAssignedIdentityProviders"); + + b.Navigation("Consents"); + + b.Navigation("Documents"); + + b.Navigation("Invitations"); + + b.Navigation("Notifications"); + + b.Navigation("RequestedSubscriptions"); + + b.Navigation("SalesManagerOfOffers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Connector", b => + { + b.Navigation("ConnectorAssignedOfferSubscriptions"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorStatus", b => + { + b.Navigation("Connectors"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConnectorType", b => + { + b.Navigation("Connectors"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Consent", b => + { + b.Navigation("ConsentAssignedOfferSubscriptions"); + + b.Navigation("ConsentAssignedOffers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ConsentStatus", b => + { + b.Navigation("Consents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Country", b => + { + b.Navigation("Addresses"); + + b.Navigation("Connectors"); + + b.Navigation("CountryAssignedIdentifiers"); + + b.Navigation("CountryLongNames"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Document", b => + { + b.Navigation("Agreements"); + + b.Navigation("Companies"); + + b.Navigation("CompanySsiDetail"); + + b.Navigation("Connector"); + + b.Navigation("Consents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentStatus", b => + { + b.Navigation("Documents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.DocumentType", b => + { + b.Navigation("Documents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IamClient", b => + { + b.Navigation("AppInstances"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Identity", b => + { + b.Navigation("CompanyServiceAccount"); + + b.Navigation("CompanyUser"); + + b.Navigation("CreatedNotifications"); + + b.Navigation("IdentityAssignedRoles"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProvider", b => + { + b.Navigation("CompanyIdentityProviders"); + + b.Navigation("CompanyUserAssignedIdentityProviders"); + + b.Navigation("IamIdentityProvider"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderCategory", b => + { + b.Navigation("IdentityProviders"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityProviderType", b => + { + b.Navigation("IdentityProviders"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityType", b => + { + b.Navigation("Identities"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.IdentityUserStatus", b => + { + b.Navigation("Identities"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.InvitationStatus", b => + { + b.Navigation("Invitations"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Language", b => + { + b.Navigation("AppDescriptions"); + + b.Navigation("CompanyRoleDescriptions"); + + b.Navigation("CountryLongNames"); + + b.Navigation("LanguageLongNameLanguages"); + + b.Navigation("LanguageLongNames"); + + b.Navigation("UseCases"); + + b.Navigation("UserRoleDescriptions"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.LicenseType", b => + { + b.Navigation("Offers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.MediaType", b => + { + b.Navigation("Documents"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationTopic", b => + { + b.Navigation("NotificationTypeAssignedTopics"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.NotificationType", b => + { + b.Navigation("NotificationTypeAssignedTopic"); + + b.Navigation("Notifications"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Offer", b => + { + b.Navigation("AgreementAssignedOffers"); + + b.Navigation("AppInstanceSetup"); + + b.Navigation("AppInstances"); + + b.Navigation("ConsentAssignedOffers"); + + b.Navigation("OfferAssignedPrivacyPolicies"); + + b.Navigation("OfferDescriptions"); + + b.Navigation("OfferSubscriptions"); + + b.Navigation("ServiceDetails"); + + b.Navigation("Tags"); + + b.Navigation("TechnicalUserProfiles"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferStatus", b => + { + b.Navigation("Offers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscription", b => + { + b.Navigation("AppSubscriptionDetail"); + + b.Navigation("CompanyServiceAccounts"); + + b.Navigation("ConnectorAssignedOfferSubscriptions"); + + b.Navigation("ConsentAssignedOfferSubscriptions"); + + b.Navigation("OfferSubscriptionProcessData"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferSubscriptionStatus", b => + { + b.Navigation("OfferSubscriptions"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.OfferType", b => + { + b.Navigation("AgreementAssignedOfferTypes"); + + b.Navigation("Offers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.PrivacyPolicy", b => + { + b.Navigation("OfferAssignedPrivacyPolicies"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.Process", b => + { + b.Navigation("CompanyApplication"); + + b.Navigation("NetworkRegistration"); + + b.Navigation("OfferSubscription"); + + b.Navigation("ProcessSteps"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepStatus", b => + { + b.Navigation("ProcessSteps"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessStepType", b => + { + b.Navigation("ProcessSteps"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ProcessType", b => + { + b.Navigation("Processes"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.ServiceType", b => + { + b.Navigation("ServiceDetails"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.TechnicalUserProfile", b => + { + b.Navigation("TechnicalUserProfileAssignedUserRoles"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UniqueIdentifier", b => + { + b.Navigation("CompanyIdentifiers"); + + b.Navigation("CountryAssignedIdentifiers"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UseCase", b => + { + b.Navigation("Agreements"); + + b.Navigation("CompanyAssignedUseCase"); + + b.Navigation("UseCaseDescriptions"); + + b.Navigation("VerifiedCredentialAssignedUseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRole", b => + { + b.Navigation("IdentityAssignedRoles"); + + b.Navigation("TechnicalUserProfileAssignedUserRole"); + + b.Navigation("UserRoleDescriptions"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.UserRoleCollection", b => + { + b.Navigation("CompanyRoleAssignedRoleCollection"); + + b.Navigation("UserRoleCollectionDescriptions"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalType", b => + { + b.Navigation("VerifiedCredentialExternalTypeUseCaseDetailVersions"); + + b.Navigation("VerifiedCredentialTypeAssignedExternalTypes"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialExternalTypeUseCaseDetailVersion", b => + { + b.Navigation("CompanySsiDetails"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialType", b => + { + b.Navigation("CompanySsiDetails"); + + b.Navigation("VerifiedCredentialTypeAssignedExternalType"); + + b.Navigation("VerifiedCredentialTypeAssignedKind"); + + b.Navigation("VerifiedCredentialTypeAssignedUseCase"); + }); + + modelBuilder.Entity("Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities.VerifiedCredentialTypeKind", b => + { + b.Navigation("VerifiedCredentialTypeAssignedKinds"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.cs b/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.cs new file mode 100644 index 0000000000..41ec6fcc52 --- /dev/null +++ b/src/portalbackend/PortalBackend.Migrations/Migrations/20231213195802_CPLP-3091-remove-keycloak-identity-links.cs @@ -0,0 +1,50 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.Migrations.Migrations +{ + /// + public partial class CPLP3091removekeycloakidentitylinks : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "client_id", + schema: "portal", + table: "company_service_accounts"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "client_id", + schema: "portal", + table: "company_service_accounts", + type: "character varying(36)", + maxLength: 36, + nullable: true); + } + } +} diff --git a/src/portalbackend/PortalBackend.Migrations/Migrations/PortalDbContextModelSnapshot.cs b/src/portalbackend/PortalBackend.Migrations/Migrations/PortalDbContextModelSnapshot.cs index 3c2bcb6ce2..bd93e407d6 100644 --- a/src/portalbackend/PortalBackend.Migrations/Migrations/PortalDbContextModelSnapshot.cs +++ b/src/portalbackend/PortalBackend.Migrations/Migrations/PortalDbContextModelSnapshot.cs @@ -16,7 +16,7 @@ * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ - + // using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -3245,11 +3245,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasColumnType("character varying(255)") .HasColumnName("client_client_id"); - b.Property("ClientId") - .HasMaxLength(36) - .HasColumnType("character varying(36)") - .HasColumnName("client_id"); - b.Property("CompanyServiceAccountTypeId") .HasColumnType("integer") .HasColumnName("company_service_account_type_id"); diff --git a/src/portalbackend/PortalBackend.Migrations/Program.cs b/src/portalbackend/PortalBackend.Migrations/Program.cs index d3755ebb3b..f5ee9516ba 100644 --- a/src/portalbackend/PortalBackend.Migrations/Program.cs +++ b/src/portalbackend/PortalBackend.Migrations/Program.cs @@ -40,7 +40,7 @@ .ConfigureServices((hostContext, services) => { services - .AddConfigurationIdentityIdDetermination(hostContext.Configuration.GetSection("ProcessIdentity")) + .AddConfigurationProcessIdentityIdDetermination(hostContext.Configuration.GetSection("ProcessIdentity")) .AddDbAuditing() .AddDbContext(o => o.UseNpgsql(hostContext.Configuration.GetConnectionString("PortalDb"), diff --git a/src/portalbackend/PortalBackend.Migrations/Seeder/BatchUpdateSeeder.cs b/src/portalbackend/PortalBackend.Migrations/Seeder/BatchUpdateSeeder.cs index 5fd71b38dd..e8eed6d585 100644 --- a/src/portalbackend/PortalBackend.Migrations/Seeder/BatchUpdateSeeder.cs +++ b/src/portalbackend/PortalBackend.Migrations/Seeder/BatchUpdateSeeder.cs @@ -117,12 +117,12 @@ await SeedTable("verified_cr await SeedTable("company_service_accounts", x => x.Id, - x => x.dataEntity.Description != x.dbEntity.Description || x.dataEntity.Name != x.dbEntity.Name || x.dataEntity.ClientId != x.dbEntity.ClientId, + x => x.dataEntity.Description != x.dbEntity.Description || x.dataEntity.Name != x.dbEntity.Name || x.dataEntity.ClientClientId != x.dbEntity.ClientClientId, (dbEntry, entry) => { dbEntry.Description = entry.Description; dbEntry.Name = entry.Name; - dbEntry.ClientId = entry.ClientId; + dbEntry.ClientClientId = entry.ClientClientId; }, cancellationToken).ConfigureAwait(false); await SeedTable("companies", diff --git a/src/portalbackend/PortalBackend.PortalEntities/Auditing/AuditHandlerV1.cs b/src/portalbackend/PortalBackend.PortalEntities/Auditing/AuditHandlerV1.cs index aa2277a5bc..e6a7bcd3c6 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Auditing/AuditHandlerV1.cs +++ b/src/portalbackend/PortalBackend.PortalEntities/Auditing/AuditHandlerV1.cs @@ -30,12 +30,12 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Audit public class AuditHandlerV1 : IAuditHandler { - private readonly IIdentityIdDetermination _identityIdDetermination; + private readonly IIdentityData _identityData; private readonly IDateTimeProvider _dateTimeProvider; - public AuditHandlerV1(IIdentityIdDetermination identityIdDetermination, IDateTimeProvider dateTimeProvider) + public AuditHandlerV1(IIdentityService identityService, IDateTimeProvider dateTimeProvider) { - _identityIdDetermination = identityIdDetermination; + _identityData = identityService.IdentityData; _dateTimeProvider = dateTimeProvider; } @@ -60,7 +60,7 @@ public void HandleAuditForChangedEntries(IEnumerable changedEntries lastEditorNames, property => property.Metadata.Name)) { - prop.CurrentValue = _identityIdDetermination.IdentityId; + prop.CurrentValue = _identityData.IdentityId; } foreach (var prop in properties.IntersectBy( @@ -101,7 +101,7 @@ private void AddAuditEntry(EntityEntry entityEntry, Type entityType, DbContext c newAuditEntity.AuditV1Id = Guid.NewGuid(); newAuditEntity.AuditV1OperationId = entityEntry.State.ToAuditOperation(); newAuditEntity.AuditV1DateLastChanged = _dateTimeProvider.OffsetNow; - newAuditEntity.AuditV1LastEditorId = _identityIdDetermination.IdentityId; + newAuditEntity.AuditV1LastEditorId = _identityData.IdentityId; context.Add(newAuditEntity); } diff --git a/src/portalbackend/PortalBackend.PortalEntities/Entities/CompanyServiceAccount.cs b/src/portalbackend/PortalBackend.PortalEntities/Entities/CompanyServiceAccount.cs index cc1eba11bd..8272911752 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Entities/CompanyServiceAccount.cs +++ b/src/portalbackend/PortalBackend.PortalEntities/Entities/CompanyServiceAccount.cs @@ -39,9 +39,6 @@ public CompanyServiceAccount(Guid id, string name, string description, CompanySe /// public Guid Id { get; set; } - [StringLength(36)] - public string? ClientId { get; set; } - [StringLength(255)] public string? ClientClientId { get; set; } diff --git a/src/portalbackend/PortalBackend.PortalEntities/Entities/IdentityUserStatus.cs b/src/portalbackend/PortalBackend.PortalEntities/Entities/IdentityUserStatus.cs index 060fd7b7d1..3c4e22383f 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Entities/IdentityUserStatus.cs +++ b/src/portalbackend/PortalBackend.PortalEntities/Entities/IdentityUserStatus.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional diff --git a/src/portalbackend/PortalBackend.PortalEntities/Identities/IdentityData.cs b/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityData.cs similarity index 87% rename from src/portalbackend/PortalBackend.PortalEntities/Identities/IdentityData.cs rename to src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityData.cs index 614faec123..c501a35510 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Identities/IdentityData.cs +++ b/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityData.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -22,4 +21,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; -public record IdentityData(string UserEntityId, Guid UserId, IdentityTypeId IdentityType, Guid CompanyId); +public interface IIdentityData +{ + Guid IdentityId { get; } + IdentityTypeId IdentityTypeId { get; } + Guid CompanyId { get; } +} diff --git a/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityService.cs b/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityService.cs index 59be43cfee..c091141e32 100644 --- a/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityService.cs +++ b/src/portalbackend/PortalBackend.PortalEntities/Identities/IIdentityService.cs @@ -19,12 +19,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; -public interface IIdentityService : IIdentityIdDetermination +public interface IIdentityService { - /// - /// Information of the currently logged in user - /// - public ValueTask GetIdentityData(); - - public IdentityData IdentityData { get; } + IIdentityData IdentityData { get; } } diff --git a/src/processes/NetworkRegistration.Library/NetworkRegistrationHandler.cs b/src/processes/NetworkRegistration.Library/NetworkRegistrationHandler.cs index a1ce8b7039..a5d53a14e5 100644 --- a/src/processes/NetworkRegistration.Library/NetworkRegistrationHandler.cs +++ b/src/processes/NetworkRegistration.Library/NetworkRegistrationHandler.cs @@ -93,12 +93,10 @@ public NetworkRegistrationHandler( userRepository.AttachAndModifyIdentity(cu.CompanyUserId, i => { i.UserStatusId = UserStatusId.PENDING; - i.UserEntityId = null; }, i => { i.UserStatusId = UserStatusId.ACTIVE; - i.UserEntityId = userId; }); await _userProvisioningService.AssignRolesToNewUserAsync(userRoleRepository, roleData, (userId, cu.CompanyUserId)).ConfigureAwait(false); diff --git a/src/processes/Processes.Worker.Library/ProcessExecutionService.cs b/src/processes/Processes.Worker.Library/ProcessExecutionService.cs index 9170cf8840..fe49b031af 100644 --- a/src/processes/Processes.Worker.Library/ProcessExecutionService.cs +++ b/src/processes/Processes.Worker.Library/ProcessExecutionService.cs @@ -24,9 +24,9 @@ using Org.Eclipse.TractusX.Portal.Backend.Framework.DateTimeProvider; using Org.Eclipse.TractusX.Portal.Backend.Framework.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; namespace Org.Eclipse.TractusX.Portal.Backend.Processes.Worker.Library; @@ -70,9 +70,9 @@ public async Task ExecuteAsync(CancellationToken stoppingToken) using var processServiceScope = _serviceScopeFactory.CreateScope(); var executorRepositories = processServiceScope.ServiceProvider.GetRequiredService(); var processExecutor = processServiceScope.ServiceProvider.GetRequiredService(); - var identityService = processServiceScope.ServiceProvider.GetRequiredService(); - //call identityService once to initialize IdentityData for synchronous use: - await identityService.GetIdentityData().ConfigureAwait(false); + var processIdentityDataDetermination = processServiceScope.ServiceProvider.GetRequiredService(); + //call processIdentityDataDetermination.GetIdentityData() once to initialize IdentityService IdentityData for synchronous use: + await processIdentityDataDetermination.GetIdentityData().ConfigureAwait(false); using var outerLoopScope = _serviceScopeFactory.CreateScope(); var outerLoopRepositories = outerLoopScope.ServiceProvider.GetRequiredService(); diff --git a/src/processes/Processes.Worker.Library/Processes.Worker.Library.csproj b/src/processes/Processes.Worker.Library/Processes.Worker.Library.csproj index 05ef6d8a72..2081e7fd1d 100644 --- a/src/processes/Processes.Worker.Library/Processes.Worker.Library.csproj +++ b/src/processes/Processes.Worker.Library/Processes.Worker.Library.csproj @@ -25,6 +25,7 @@ + diff --git a/src/processes/Processes.Worker/Program.cs b/src/processes/Processes.Worker/Program.cs index f14f10d03b..a17c015455 100644 --- a/src/processes/Processes.Worker/Program.cs +++ b/src/processes/Processes.Worker/Program.cs @@ -53,7 +53,7 @@ .AddApplicationChecklist(hostContext.Configuration.GetSection("ApplicationChecklist")) .AddApplicationChecklistCreation() .AddApplicationActivation(hostContext.Configuration) - .AddConfigurationIdentityService(hostContext.Configuration.GetSection("ProcessIdentity")) + .AddConfigurationProcessIdentityService(hostContext.Configuration.GetSection("ProcessIdentity")) .AddNetworkRegistrationProcessExecutor(hostContext.Configuration) .AddServiceAccountSyncProcessExecutor(hostContext.Configuration); diff --git a/src/provisioning/Provisioning.Library/Extensions/ClientManager.cs b/src/provisioning/Provisioning.Library/Extensions/ClientManager.cs index aade145d44..cf7e57c51f 100644 --- a/src/provisioning/Provisioning.Library/Extensions/ClientManager.cs +++ b/src/provisioning/Provisioning.Library/Extensions/ClientManager.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -20,6 +19,7 @@ using Org.Eclipse.TractusX.Portal.Backend.Keycloak.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Library; +using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Library.Models.Clients; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Library.Models.ProtocolMappers; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Enums; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; @@ -44,16 +44,22 @@ public partial class ProvisioningManager { IamClientAuthMethod.SECRET_JWT, "client-secret-jwt" } }; - public async Task UpdateCentralClientAsync(string internalClientId, ClientConfigData config) + public async Task UpdateCentralClientAsync(string clientId, ClientConfigData config) { - var client = await _CentralIdp.GetClientAsync(_Settings.CentralRealm, internalClientId).ConfigureAwait(false); + var client = await GetCentralClientAsync(clientId).ConfigureAwait(false); + if (client.Id == null) + throw new KeycloakEntityConflictException($"id of client {clientId} is null"); client.Name = config.Name; client.ClientAuthenticatorType = IamClientAuthMethodToInternal(config.IamClientAuthMethod); - await _CentralIdp.UpdateClientAsync(_Settings.CentralRealm, internalClientId, client).ConfigureAwait(false); + await _CentralIdp.UpdateClientAsync(_Settings.CentralRealm, client.Id, client).ConfigureAwait(false); + return client.Id; } - public Task DeleteCentralClientAsync(string internalClientId) => - _CentralIdp.DeleteClientAsync(_Settings.CentralRealm, internalClientId); + public async Task DeleteCentralClientAsync(string clientId) + { + var idOfClient = await GetIdOfCentralClientAsync(clientId).ConfigureAwait(false) ?? throw new KeycloakEntityNotFoundException($"client {clientId} not found in keycloak"); + await _CentralIdp.DeleteClientAsync(_Settings.CentralRealm, idOfClient).ConfigureAwait(false); + } public async Task UpdateClient(string clientId, string url, string redirectUrl) { @@ -83,9 +89,10 @@ public async Task GetCentralClientAuthDataAsync(string internalC }; } - public async Task ResetCentralClientAuthDataAsync(string internalClientId) + public async Task ResetCentralClientAuthDataAsync(string clientId) { - var credentials = await _CentralIdp.GenerateClientSecretAsync(_Settings.CentralRealm, internalClientId).ConfigureAwait(false); + var idOfClient = await GetIdOfCentralClientAsync(clientId).ConfigureAwait(false); + var credentials = await _CentralIdp.GenerateClientSecretAsync(_Settings.CentralRealm, idOfClient).ConfigureAwait(false); return new ClientAuthData( CredentialsTypeToIamClientAuthMethod(credentials.Type)) { @@ -93,21 +100,19 @@ public async Task ResetCentralClientAuthDataAsync(string interna }; } - private async Task GetIdOfCentralClientAsync(string clientId) - { - var idOfClient = (await _CentralIdp.GetClientsAsync(_Settings.CentralRealm, clientId: clientId, viewableOnly: true).ConfigureAwait(false)) - .SingleOrDefault()?.Id; - if (idOfClient == null) - { - throw new KeycloakEntityNotFoundException($"clientId {clientId} not found in central keycloak"); - } - return idOfClient; - } + public async Task GetIdOfCentralClientAsync(string clientId) => + (await _CentralIdp.GetClientsAsync(_Settings.CentralRealm, clientId: clientId, viewableOnly: true).ConfigureAwait(false)) + .SingleOrDefault()?.Id ?? throw new KeycloakEntityNotFoundException($"clientId {clientId} not found in central keycloak"); + + private async Task GetCentralClientAsync(string clientId) => + (await _CentralIdp.GetClientsAsync(_Settings.CentralRealm, clientId: clientId, viewableOnly: true).ConfigureAwait(false)) + .SingleOrDefault() ?? throw new KeycloakEntityNotFoundException($"clientId {clientId} not found in central keycloak"); private async Task CreateSharedRealmIdentityProviderClientAsync(KeycloakClient keycloak, string realm, IdentityProviderClientConfig config) { var newClient = Clone(_Settings.SharedRealmClient); - newClient.RedirectUris = Enumerable.Repeat(config.RedirectUri, 1); + newClient.RedirectUris = Enumerable.Repeat(config.RedirectUri, 1); + newClient.Attributes ??= new Dictionary(); newClient.Attributes["jwks.url"] = config.JwksUrl; await keycloak.CreateClientAsync(realm, newClient).ConfigureAwait(false); } @@ -122,12 +127,7 @@ private async Task CreateCentralOIDCClientAsync(string clientId, string { newClient.BaseUrl = baseUrl; } - var newClientId = await _CentralIdp.CreateClientAndRetrieveClientIdAsync(_Settings.CentralRealm, newClient).ConfigureAwait(false); - if (newClientId == null) - { - throw new KeycloakNoSuccessException($"failed to create new client {clientId} in central realm"); - } - return newClientId; + return await _CentralIdp.CreateClientAndRetrieveClientIdAsync(_Settings.CentralRealm, newClient).ConfigureAwait(false) ?? throw new KeycloakNoSuccessException($"failed to create new client {clientId} in central realm"); } private Task CreateCentralOIDCClientAudienceMapperAsync(string internalClientId, string clientAudienceId) => diff --git a/src/provisioning/Provisioning.Library/Extensions/ServiceAccountManager.cs b/src/provisioning/Provisioning.Library/Extensions/ServiceAccountManager.cs index fdcbe5a039..e941541d1d 100644 --- a/src/provisioning/Provisioning.Library/Extensions/ServiceAccountManager.cs +++ b/src/provisioning/Provisioning.Library/Extensions/ServiceAccountManager.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional diff --git a/src/provisioning/Provisioning.Library/Extensions/UserManager.cs b/src/provisioning/Provisioning.Library/Extensions/UserManager.cs index b699544327..d3c5dee7ea 100644 --- a/src/provisioning/Provisioning.Library/Extensions/UserManager.cs +++ b/src/provisioning/Provisioning.Library/Extensions/UserManager.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -56,8 +55,7 @@ public async Task UpdateCentralUserAsync(string userId, string firstName, string { try { - var users = await _CentralIdp.GetUsersAsync(_Settings.CentralRealm, username: userName).ConfigureAwait(false); - return users.Count() != 1 ? null : users.Single().Id; + return (await _CentralIdp.GetUsersAsync(_Settings.CentralRealm, username: userName).ConfigureAwait(false)).SingleOrDefault(user => user.UserName == userName)?.Id; } catch (FlurlHttpException ex) { @@ -68,6 +66,10 @@ public async Task UpdateCentralUserAsync(string userId, string firstName, string throw; } + catch (InvalidOperationException) + { + throw new UnexpectedConditionException($"there should never be multiple users in keycloak having the same username '{userName}'"); + } } public async Task DeleteSharedRealmUserAsync(string realm, string userId) diff --git a/src/provisioning/Provisioning.Library/IProvisioningManager.cs b/src/provisioning/Provisioning.Library/IProvisioningManager.cs index cf59cbb4f6..1346ad699c 100644 --- a/src/provisioning/Provisioning.Library/IProvisioningManager.cs +++ b/src/provisioning/Provisioning.Library/IProvisioningManager.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -43,12 +42,13 @@ public interface IProvisioningManager Task SetupClientAsync(string redirectUrl, string? baseUrl = null, IEnumerable? optionalRoleNames = null, bool enabled = true); Task SetupCentralServiceAccountClientAsync(string clientId, ClientConfigRolesData config, bool enabled); Task GetServiceAccountUserId(string clientId); - Task UpdateCentralClientAsync(string internalClientId, ClientConfigData config); - Task DeleteCentralClientAsync(string internalClientId); + Task UpdateCentralClientAsync(string clientId, ClientConfigData config); + Task DeleteCentralClientAsync(string clientId); Task UpdateClient(string clientId, string url, string redirectUrl); Task EnableClient(string clientId); Task GetCentralClientAuthDataAsync(string internalClientId); - Task ResetCentralClientAuthDataAsync(string internalClientId); + Task ResetCentralClientAuthDataAsync(string clientId); + Task GetIdOfCentralClientAsync(string clientId); Task AddBpnAttributetoUserAsync(string centralUserId, IEnumerable bpns); Task AddProtocolMapperAsync(string clientId); Task DeleteCentralUserBusinessPartnerNumberAsync(string centralUserId, string businessPartnerNumber); diff --git a/src/provisioning/Provisioning.Library/Models/ServiceAccountData.cs b/src/provisioning/Provisioning.Library/Models/ServiceAccountData.cs index 1bc1e8960f..b010234520 100644 --- a/src/provisioning/Provisioning.Library/Models/ServiceAccountData.cs +++ b/src/provisioning/Provisioning.Library/Models/ServiceAccountData.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -20,16 +19,8 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; -public class ServiceAccountData -{ - public ServiceAccountData(string internalClientId, string userEntityId, ClientAuthData authData) - { - InternalClientId = internalClientId; - UserEntityId = userEntityId; - AuthData = authData; - } - - public string InternalClientId { get; set; } - public string UserEntityId { get; set; } - public ClientAuthData AuthData { get; set; } -} +public record ServiceAccountData( + string InternalClientId, + string IamUserId, + ClientAuthData AuthData +); diff --git a/src/provisioning/Provisioning.Library/ProvisioningManager.cs b/src/provisioning/Provisioning.Library/ProvisioningManager.cs index 7731efc384..54a725aec4 100644 --- a/src/provisioning/Provisioning.Library/ProvisioningManager.cs +++ b/src/provisioning/Provisioning.Library/ProvisioningManager.cs @@ -93,11 +93,11 @@ public async Task CreateOwnIdpAsync(string displayName, string organisat var attributes = new List<(string, IEnumerable)>(); if (organisationName != null) { - attributes.Add(new(_Settings.MappedCompanyAttribute, Enumerable.Repeat(organisationName, 1))); + attributes.Add(new(_Settings.MappedCompanyAttribute, Enumerable.Repeat(organisationName, 1))); } if (businessPartnerNumber != null) { - attributes.Add(new(_Settings.MappedBpnAttribute, Enumerable.Repeat(businessPartnerNumber, 1))); + attributes.Add(new(_Settings.MappedBpnAttribute, Enumerable.Repeat(businessPartnerNumber, 1))); } return attributes; } diff --git a/src/provisioning/Provisioning.Library/Service/IUserProvisioningService.cs b/src/provisioning/Provisioning.Library/Service/IUserProvisioningService.cs index 3dc302b5db..55d8b98a0a 100644 --- a/src/provisioning/Provisioning.Library/Service/IUserProvisioningService.cs +++ b/src/provisioning/Provisioning.Library/Service/IUserProvisioningService.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -35,6 +34,6 @@ public interface IUserProvisioningService Task GetIdentityProviderDisplayName(string idpAlias); IAsyncEnumerable GetRoleDatas(IEnumerable clientRoles); Task> GetOwnCompanyPortalRoleDatas(string clientId, IEnumerable roles, Guid companyId); - Task<(Identity? identity, Guid companyUserId)> GetOrCreateCompanyUser(IUserRepository userRepository, string alias, UserCreationRoleDataIdpInfo user, Guid companyId, Guid identityProviderId, string? businessPartnerNumber); - Task AssignRolesToNewUserAsync(IUserRolesRepository userRolesRepository, IEnumerable roleDatas, (string UserEntityId, Guid CompanyUserId) userdata); + Task<(Identity? Identity, Guid CompanyUserId)> GetOrCreateCompanyUser(IUserRepository userRepository, string alias, UserCreationRoleDataIdpInfo user, Guid companyId, Guid identityProviderId, string? businessPartnerNumber); + Task AssignRolesToNewUserAsync(IUserRolesRepository userRolesRepository, IEnumerable roleDatas, (string IamUserId, Guid CompanyUserId) userdata); } diff --git a/src/provisioning/Provisioning.Library/Service/ServiceAccountCreation.cs b/src/provisioning/Provisioning.Library/Service/ServiceAccountCreation.cs index aec5161329..fc2d1a72d2 100644 --- a/src/provisioning/Provisioning.Library/Service/ServiceAccountCreation.cs +++ b/src/provisioning/Provisioning.Library/Service/ServiceAccountCreation.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -101,21 +100,16 @@ public ServiceAccountCreation( if (bpns.Any()) { - await _provisioningManager.AddBpnAttributetoUserAsync(serviceAccountData.UserEntityId, bpns).ConfigureAwait(false); + await _provisioningManager.AddBpnAttributetoUserAsync(serviceAccountData.IamUserId, bpns).ConfigureAwait(false); await _provisioningManager.AddProtocolMapperAsync(serviceAccountData.InternalClientId).ConfigureAwait(false); } - var identity = _portalRepositories.GetInstance().CreateIdentity(companyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_SERVICE_ACCOUNT, - i => - { - i.UserEntityId = serviceAccountData.UserEntityId; - }); + var identity = _portalRepositories.GetInstance().CreateIdentity(companyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_SERVICE_ACCOUNT, null); var serviceAccount = serviceAccountsRepository.CreateCompanyServiceAccount( identity.Id, enhancedName, description, - serviceAccountData.InternalClientId, clientId, companyServiceAccountTypeId, setOptionalParameter); diff --git a/src/provisioning/Provisioning.Library/Service/UserProvisioningService.cs b/src/provisioning/Provisioning.Library/Service/UserProvisioningService.cs index f2113807c4..392b039ef2 100644 --- a/src/provisioning/Provisioning.Library/Service/UserProvisioningService.cs +++ b/src/provisioning/Provisioning.Library/Service/UserProvisioningService.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -65,19 +64,13 @@ public UserProvisioningService(IProvisioningManager provisioningManager, IPortal await foreach (var user in userCreationInfos) { - (string UserEntityId, Guid CompanyUserId) userdata = default; + var companyUserId = Guid.Empty; Exception? error = null; var nextPassword = passwordProvider.NextOptionalPassword(); try { - var (identity, companyUserId) = await GetOrCreateCompanyUser(userRepository, alias, user, companyId, identityProviderId, businessPartnerNumber); - - userdata.CompanyUserId = companyUserId; - if (!string.IsNullOrWhiteSpace(identity?.UserEntityId)) - { - userdata.UserEntityId = identity.UserEntityId; - } + (var identity, companyUserId) = await GetOrCreateCompanyUser(userRepository, alias, user, companyId, identityProviderId, businessPartnerNumber); cancellationToken.ThrowIfCancellationRequested(); @@ -89,14 +82,14 @@ public UserProvisioningService(IProvisioningManager provisioningManager, IPortal error = e; } - if (userdata == default && error == null) + if (companyUserId == Guid.Empty && error == null) { error = new UnexpectedConditionException($"failed to create companyUser for provider userid {user.UserId}, username {user.UserName} while not throwing any error"); } await _portalRepositories.SaveAsync().ConfigureAwait(false); - yield return new(userdata.CompanyUserId, user.UserName, nextPassword, error); + yield return new(companyUserId, user.UserName, nextPassword, error); } } @@ -107,13 +100,11 @@ public async Task HandleCentralKeycloakCreation(UserCreationRoleDataIdpInfo user { userRepository.AttachAndModifyIdentity(companyUserId, null, cu => { - cu.UserEntityId = centralUserId; cu.UserStatusId = user.UserStatusId; }); } else { - identity.UserEntityId = centralUserId; identity.UserStatusId = user.UserStatusId; } @@ -145,7 +136,7 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync(centralUserId, return centralUserId; } - public async Task<(Identity? identity, Guid companyUserId)> GetOrCreateCompanyUser( + public async Task<(Identity? Identity, Guid CompanyUserId)> GetOrCreateCompanyUser( IUserRepository userRepository, string alias, UserCreationRoleDataIdpInfo user, @@ -155,14 +146,13 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync(centralUserId, { var businessPartnerRepository = _portalRepositories.GetInstance(); - Identity? identity = null; var companyUserId = await ValidateDuplicateIdpUsersAsync(userRepository, alias, user, companyId).ConfigureAwait(false); if (companyUserId != Guid.Empty) { - return (identity, companyUserId); + return (null, companyUserId); } - identity = userRepository.CreateIdentity(companyId, user.UserStatusId, IdentityTypeId.COMPANY_USER, null); + var identity = userRepository.CreateIdentity(companyId, user.UserStatusId, IdentityTypeId.COMPANY_USER, null); companyUserId = userRepository.CreateCompanyUser(identity.Id, user.FirstName, user.LastName, user.Email).Id; if (businessPartnerNumber != null) { @@ -283,24 +273,21 @@ private async Task ValidateDuplicateIdpUsersAsync(IUserRepository userRepo { var existingCompanyUserId = Guid.Empty; - await foreach (var (userEntityId, companyUserId) in userRepository.GetMatchingCompanyIamUsersByNameEmail(user.FirstName, user.LastName, user.Email, companyId, ValidCompanyUserStatusIds).ConfigureAwait(false)) + await foreach (var (companyUserId, isFullMatch) in userRepository.GetMatchingCompanyIamUsersByNameEmail(user.FirstName, user.LastName, user.Email, companyId, ValidCompanyUserStatusIds).ConfigureAwait(false)) { - if (userEntityId == null) + if (isFullMatch) { - if (companyUserId != Guid.Empty) - { - existingCompanyUserId = companyUserId; - } - + existingCompanyUserId = companyUserId; continue; } try { - if (await _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId).AnyAsync(link => + var userId = await _provisioningManager.GetUserByUserName(companyUserId.ToString()).ConfigureAwait(false); + if (userId != null && await _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userId).AnyAsync(link => alias == link.Alias && (user.UserId == link.UserId || user.UserName == link.UserName)).ConfigureAwait(false)) { - throw new ConflictException($"existing user {userEntityId} in keycloak for provider userid {user.UserId}, {user.UserName}"); + throw new ConflictException($"existing user {companyUserId} in keycloak for provider userid {user.UserId}, {user.UserName}"); } } catch (KeycloakEntityNotFoundException) @@ -312,7 +299,7 @@ private async Task ValidateDuplicateIdpUsersAsync(IUserRepository userRepo return existingCompanyUserId; } - public async Task AssignRolesToNewUserAsync(IUserRolesRepository userRolesRepository, IEnumerable roleDatas, (string UserEntityId, Guid CompanyUserId) userdata) + public async Task AssignRolesToNewUserAsync(IUserRolesRepository userRolesRepository, IEnumerable roleDatas, (string IamUserId, Guid CompanyUserId) userdata) { if (roleDatas.Any()) { @@ -320,7 +307,7 @@ public async Task AssignRolesToNewUserAsync(IUserRolesRepository userRolesReposi var messages = new List(); - await foreach (var assigned in _provisioningManager.AssignClientRolesToCentralUserAsync(userdata.UserEntityId, clientRoleNames)) + await foreach (var assigned in _provisioningManager.AssignClientRolesToCentralUserAsync(userdata.IamUserId, clientRoleNames)) { foreach (var role in assigned.Roles) { diff --git a/src/registration/ApplicationActivation.Library/ApplicationActivationService.cs b/src/registration/ApplicationActivation.Library/ApplicationActivationService.cs index ebf4824bce..cf21821206 100644 --- a/src/registration/ApplicationActivation.Library/ApplicationActivationService.cs +++ b/src/registration/ApplicationActivation.Library/ApplicationActivationService.cs @@ -179,13 +179,10 @@ private bool InProcessingTime() .GetInvitedUsersDataByApplicationIdUntrackedAsync(applicationId); await foreach (var userData in invitedUsersData.ConfigureAwait(false)) { - if (string.IsNullOrWhiteSpace(userData.UserEntityId)) - { - throw new ConflictException($"UserEntityId must be set for company user {userData.CompanyUserId}."); - } + var iamUserId = await _provisioningManager.GetUserByUserName(userData.CompanyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {userData.CompanyUserId} not found in keycloak"); assignedRoles = await _provisioningManager - .AssignClientRolesToCentralUserAsync(userData.UserEntityId, approvalInitialRoles.ToDictionary(x => x.ClientId, x => x.UserRoleNames)) + .AssignClientRolesToCentralUserAsync(iamUserId, approvalInitialRoles.ToDictionary(x => x.ClientId, x => x.UserRoleNames)) .ToDictionaryAsync(assigned => assigned.Client, assigned => assigned.Roles) .ConfigureAwait(false); @@ -200,7 +197,7 @@ private bool InProcessingTime() userBusinessPartnersRepository.CreateCompanyUserAssignedBusinessPartner(userData.CompanyUserId, businessPartnerNumber); await _provisioningManager - .AddBpnAttributetoUserAsync(userData.UserEntityId, Enumerable.Repeat(businessPartnerNumber, 1)) + .AddBpnAttributetoUserAsync(iamUserId, Enumerable.Repeat(businessPartnerNumber, 1)) .ConfigureAwait(false); } @@ -226,6 +223,8 @@ private async Task RemoveRegistrationRoles(Guid applicationId, IUserRolesReposit throw new UnexpectedConditionException("userRoleIds should never be empty here"); } + var iamUserId = await _provisioningManager.GetUserByUserName(userData.CompanyUserId.ToString()).ConfigureAwait(false) ?? throw new ConflictException($"user {userData.CompanyUserId} not found in keycloak"); + var roleNamesToDelete = userData.UserRoleIds .Select(roleId => userRoles[roleId]) .GroupBy(clientRoleData => clientRoleData.ClientClientId) @@ -233,7 +232,7 @@ private async Task RemoveRegistrationRoles(Guid applicationId, IUserRolesReposit clientRoleDataGroup => clientRoleDataGroup.Key, clientRoleData => clientRoleData.Select(y => y.UserRoleText)); - await _provisioningManager.DeleteClientRolesFromCentralUserAsync(userData.UserEntityId, roleNamesToDelete) + await _provisioningManager.DeleteClientRolesFromCentralUserAsync(iamUserId, roleNamesToDelete) .ConfigureAwait(false); userRolesRepository.DeleteCompanyUserAssignedRoles(userData.UserRoleIds.Select(roleId => (userData.CompanyUserId, roleId))); } @@ -277,7 +276,7 @@ private async Task PostRegistrationWelcomeEmailAsync(IApplicationRepository appl throw new ConflictException($"user(s) {string.Join(",", failedUserNames)} has no assigned email"); } - private static async Task> GetRoleData(IUserRolesRepository userRolesRepository, IEnumerable roles) + private static async Task> GetRoleData(IUserRolesRepository userRolesRepository, IEnumerable roles) { var roleData = await userRolesRepository .GetUserRoleDataUntrackedAsync(roles) diff --git a/src/registration/Registration.Service/BusinessLogic/NetworkBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/NetworkBusinessLogic.cs index 0a8d154d46..fcf62407f4 100644 --- a/src/registration/Registration.Service/BusinessLogic/NetworkBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/NetworkBusinessLogic.cs @@ -32,20 +32,20 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.BusinessLogic public class NetworkBusinessLogic : INetworkBusinessLogic { private readonly IPortalRepositories _portalRepositories; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IApplicationChecklistCreationService _checklistService; public NetworkBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IApplicationChecklistCreationService checklistService) { _portalRepositories = portalRepositories; - _identityService = identityService; + _identityData = identityService.IdentityData; _checklistService = checklistService; } public async Task Submit(PartnerSubmitData submitData) { - var companyId = _identityService.IdentityData.CompanyId; - var userId = _identityService.IdentityId; + var companyId = _identityData.CompanyId; + var userId = _identityData.IdentityId; var data = await _portalRepositories.GetInstance() .GetSubmitData(companyId) .ConfigureAwait(false); diff --git a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs index 1567223243..f2131a1cef 100644 --- a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs @@ -48,12 +48,11 @@ public class RegistrationBusinessLogic : IRegistrationBusinessLogic private readonly RegistrationSettings _settings; private readonly IMailingService _mailingService; private readonly IBpnAccess _bpnAccess; - private readonly IProvisioningManager _provisioningManager; private readonly IUserProvisioningService _userProvisioningService; private readonly IPortalRepositories _portalRepositories; private readonly ILogger _logger; private readonly IApplicationChecklistCreationService _checklistService; - private readonly IIdentityService _identityService; + private readonly IIdentityData _identityData; private readonly IDateTimeProvider _dateTimeProvider; private static readonly Regex bpnRegex = new(@"(\w|\d){16}", RegexOptions.None, TimeSpan.FromSeconds(1)); @@ -62,7 +61,6 @@ public RegistrationBusinessLogic( IOptions settings, IMailingService mailingService, IBpnAccess bpnAccess, - IProvisioningManager provisioningManager, IUserProvisioningService userProvisioningService, ILogger logger, IPortalRepositories portalRepositories, @@ -73,12 +71,11 @@ public RegistrationBusinessLogic( _settings = settings.Value; _mailingService = mailingService; _bpnAccess = bpnAccess; - _provisioningManager = provisioningManager; _userProvisioningService = userProvisioningService; _logger = logger; _portalRepositories = portalRepositories; _checklistService = checklistService; - _identityService = identityService; + _identityData = identityService.IdentityData; _dateTimeProvider = dateTimeProvider; } @@ -165,8 +162,7 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen throw new ControllerArgumentException($"documentType must be either: {string.Join(",", _settings.DocumentTypeIds)}"); } - var identity = _identityService.IdentityData; - var validApplicationForCompany = await _portalRepositories.GetInstance().IsValidApplicationForCompany(applicationId, identity.CompanyId).ConfigureAwait(false); + var validApplicationForCompany = await _portalRepositories.GetInstance().IsValidApplicationForCompany(applicationId, _identityData.CompanyId).ConfigureAwait(false); if (!validApplicationForCompany) { throw new ForbiddenException($"The users company is not assigned with application {applicationId}"); @@ -180,7 +176,7 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen _portalRepositories.GetInstance().CreateDocument(document.FileName, content, hash, mediaTypeId, documentTypeId, doc => { - doc.CompanyUserId = identity.UserId; + doc.CompanyUserId = _identityData.IdentityId; }); return await _portalRepositories.SaveAsync().ConfigureAwait(false); } @@ -188,7 +184,7 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId) { var documentRepository = _portalRepositories.GetInstance(); - var documentDetails = await documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identityService.IdentityId).ConfigureAwait(false); + var documentDetails = await documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identityData.IdentityId).ConfigureAwait(false); if (documentDetails.DocumentId == Guid.Empty) { throw new NotFoundException($"document {documentId} does not exist."); @@ -208,11 +204,11 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen } public IAsyncEnumerable GetAllApplicationsForUserWithStatus() => - _portalRepositories.GetInstance().GetApplicationsWithStatusUntrackedAsync(_identityService.IdentityData.CompanyId); + _portalRepositories.GetInstance().GetApplicationsWithStatusUntrackedAsync(_identityData.CompanyId); public async Task GetCompanyDetailData(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetCompanyApplicationDetailDataAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetCompanyApplicationDetailDataAsync(applicationId, _identityData.CompanyId).ConfigureAwait(false); if (result == null) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -274,7 +270,7 @@ await companyDetails.ValidateDatabaseData( private async Task GetAndValidateApplicationData(Guid applicationId, CompanyDetailData companyDetails, IApplicationRepository applicationRepository) { var companyApplicationData = await applicationRepository - .GetCompanyApplicationDetailDataAsync(applicationId, _identityService.IdentityData.CompanyId, companyDetails.CompanyId) + .GetCompanyApplicationDetailDataAsync(applicationId, _identityData.CompanyId, companyDetails.CompanyId) .ConfigureAwait(false); if (companyApplicationData == null) @@ -367,13 +363,12 @@ public Task InviteNewUserAsync(Guid applicationId, UserCreationInfoWithMess private async Task InviteNewUserInternalAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo) { - var identity = _identityService.IdentityData; - if (await _portalRepositories.GetInstance().IsOwnCompanyUserWithEmailExisting(userCreationInfo.eMail, identity.CompanyId)) + if (await _portalRepositories.GetInstance().IsOwnCompanyUserWithEmailExisting(userCreationInfo.eMail, _identityData.CompanyId)) { throw new ControllerArgumentException($"user with email {userCreationInfo.eMail} does already exist"); } - var (companyNameIdpAliasData, createdByName) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(identity.UserId, applicationId).ConfigureAwait(false); + var (companyNameIdpAliasData, createdByName) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identityData.IdentityId, applicationId).ConfigureAwait(false); IEnumerable? userRoleDatas = null; @@ -441,7 +436,7 @@ public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, C } var applicationRepository = _portalRepositories.GetInstance(); - var applicationUserData = await applicationRepository.GetOwnCompanyApplicationUserDataAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var applicationUserData = await applicationRepository.GetOwnCompanyApplicationUserDataAsync(applicationId, _identityData.CompanyId).ConfigureAwait(false); if (!applicationUserData.Exists) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -454,7 +449,7 @@ public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, C public async Task GetOwnCompanyApplicationStatusAsync(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetOwnCompanyApplicationStatusUserDataUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetOwnCompanyApplicationStatusUserDataUntrackedAsync(applicationId, _identityData.CompanyId).ConfigureAwait(false); if (!result.Exists) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -481,8 +476,8 @@ public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgr throw new NotFoundException($"application {applicationId} does not exist"); } - var companyId = _identityService.IdentityData.CompanyId; - var userId = _identityService.IdentityId; + var companyId = _identityData.CompanyId; + var userId = _identityData.IdentityId; var (applicationCompanyId, applicationStatusId, companyAssignedRoleIds, consents) = companyRoleAgreementConsentData; if (applicationCompanyId != companyId) { @@ -525,7 +520,7 @@ public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgr public async Task GetRoleAgreementConsentsAsync(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetCompanyRoleAgreementConsentStatusUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetCompanyRoleAgreementConsentStatusUntrackedAsync(applicationId, _identityData.CompanyId).ConfigureAwait(false); if (result == null) { throw new ForbiddenException($"user is not assigned with CompanyApplication {applicationId}"); @@ -587,7 +582,7 @@ public async Task SubmitRegistrationAsync(Guid applicationId) } else { - _logger.LogInformation("user {userId} has no email-address", _identityService.IdentityId); + _logger.LogInformation("user {userId} has no email-address", _identityData.IdentityId); } return true; @@ -595,7 +590,7 @@ public async Task SubmitRegistrationAsync(Guid applicationId) private async ValueTask GetAndValidateCompanyDataDetails(Guid applicationId, IEnumerable docTypeIds) { - var userId = _identityService.IdentityId; + var userId = _identityData.IdentityId; var applicationUserData = await _portalRepositories.GetInstance() .GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, docTypeIds).ConfigureAwait(false); @@ -646,27 +641,18 @@ private async ValueTask GetAndValidateCompanyDa return applicationUserData; } - public async IAsyncEnumerable GetInvitedUsersAsync(Guid applicationId) - { - await foreach (var item in _portalRepositories.GetInstance().GetInvitedUserDetailsUntrackedAsync(applicationId).ConfigureAwait(false)) - { - if (string.IsNullOrWhiteSpace(item.UserId)) - { - throw new ConflictException("UserEntityId must be set."); - } - - var userRoles = await _provisioningManager.GetClientRoleMappingsForUserAsync(item.UserId, _settings.KeycloakClientID).ConfigureAwait(false); - yield return new InvitedUser( - item.InvitationStatus, - item.EmailId, - userRoles - ); - } - } + public IAsyncEnumerable GetInvitedUsersAsync(Guid applicationId) => + _portalRepositories.GetInstance() + .GetInvitedUserDetailsUntrackedAsync(applicationId) + .Select(x => + new InvitedUser( + x.InvitationStatus, + x.EmailId, + x.Roles)); public async Task> GetUploadedDocumentsAsync(Guid applicationId, DocumentTypeId documentTypeId) { - var result = await _portalRepositories.GetInstance().GetUploadedDocumentsAsync(applicationId, documentTypeId, _identityService.IdentityId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetUploadedDocumentsAsync(applicationId, documentTypeId, _identityData.IdentityId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"application {applicationId} not found"); @@ -680,7 +666,7 @@ public async Task> GetUploadedDocumentsAsync(Guid a public async Task SetInvitationStatusAsync() { - var invitationData = await _portalRepositories.GetInstance().GetInvitationStatusAsync(_identityService.IdentityId).ConfigureAwait(false); + var invitationData = await _portalRepositories.GetInstance().GetInvitationStatusAsync(_identityData.IdentityId).ConfigureAwait(false); if (invitationData == null) { @@ -700,7 +686,7 @@ public async Task SetInvitationStatusAsync() public async Task GetRegistrationDataAsync(Guid applicationId) { - var (isValidApplicationId, isValidCompany, data) = await _portalRepositories.GetInstance().GetRegistrationDataUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId, _settings.DocumentTypeIds).ConfigureAwait(false); + var (isValidApplicationId, isValidCompany, data) = await _portalRepositories.GetInstance().GetRegistrationDataUntrackedAsync(applicationId, _identityData.CompanyId, _settings.DocumentTypeIds).ConfigureAwait(false); if (!isValidApplicationId) { throw new NotFoundException($"application {applicationId} does not exist"); @@ -818,28 +804,28 @@ private static CompanyApplicationStatusId GetAndValidateUpdateApplicationStatus( return type switch { UpdateApplicationSteps.CompanyWithAddress - when (applicationStatusId == CompanyApplicationStatusId.CREATED || - applicationStatusId == CompanyApplicationStatusId.ADD_COMPANY_DATA) => CompanyApplicationStatusId.INVITE_USER, + when applicationStatusId == CompanyApplicationStatusId.CREATED || + applicationStatusId == CompanyApplicationStatusId.ADD_COMPANY_DATA => CompanyApplicationStatusId.INVITE_USER, UpdateApplicationSteps.CompanyRoleAgreementConsents - when (applicationStatusId == CompanyApplicationStatusId.CREATED || + when applicationStatusId == CompanyApplicationStatusId.CREATED || applicationStatusId == CompanyApplicationStatusId.ADD_COMPANY_DATA || applicationStatusId == CompanyApplicationStatusId.INVITE_USER || - applicationStatusId == CompanyApplicationStatusId.SELECT_COMPANY_ROLE) => CompanyApplicationStatusId.UPLOAD_DOCUMENTS, + applicationStatusId == CompanyApplicationStatusId.SELECT_COMPANY_ROLE => CompanyApplicationStatusId.UPLOAD_DOCUMENTS, UpdateApplicationSteps.SubmitRegistration - when (applicationStatusId == CompanyApplicationStatusId.CREATED || + when applicationStatusId == CompanyApplicationStatusId.CREATED || applicationStatusId == CompanyApplicationStatusId.ADD_COMPANY_DATA || applicationStatusId == CompanyApplicationStatusId.INVITE_USER || applicationStatusId == CompanyApplicationStatusId.SELECT_COMPANY_ROLE || - applicationStatusId == CompanyApplicationStatusId.UPLOAD_DOCUMENTS) => throw new ForbiddenException($"Application status is not fitting to the pre-requisite"), + applicationStatusId == CompanyApplicationStatusId.UPLOAD_DOCUMENTS => throw new ForbiddenException($"Application status is not fitting to the pre-requisite"), UpdateApplicationSteps.SubmitRegistration when applicationStatusId == CompanyApplicationStatusId.VERIFY => CompanyApplicationStatusId.SUBMITTED, - _ when (applicationStatusId == CompanyApplicationStatusId.SUBMITTED || + _ when applicationStatusId == CompanyApplicationStatusId.SUBMITTED || applicationStatusId == CompanyApplicationStatusId.CONFIRMED || - applicationStatusId == CompanyApplicationStatusId.DECLINED) => throw new ForbiddenException($"Application is already closed"), + applicationStatusId == CompanyApplicationStatusId.DECLINED => throw new ForbiddenException($"Application is already closed"), _ => default }; @@ -852,7 +838,7 @@ public async Task DeleteRegistrationDocumentAsync(Guid documentId) throw new ControllerArgumentException($"documentId must not be empty"); } var documentRepository = _portalRepositories.GetInstance(); - var details = await documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, _identityService.IdentityData.CompanyId, _settings.ApplicationStatusIds).ConfigureAwait(false); + var details = await documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, _identityData.CompanyId, _settings.ApplicationStatusIds).ConfigureAwait(false); if (details == default) { throw new NotFoundException("Document does not exist."); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/CompanyDataBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/CompanyDataBusinessLogicTests.cs index b296910a26..724c71f21b 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/CompanyDataBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/CompanyDataBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -38,7 +37,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Busin public class CompanyDataBusinessLogicTests { - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly Guid _traceabilityExternalTypeDetailId = Guid.NewGuid(); private readonly Guid _validCredentialId = Guid.NewGuid(); private readonly IFixture _fixture; @@ -78,6 +77,7 @@ public CompanyDataBusinessLogicTests() _custodianService = A.Fake(); _dateTimeProvider = A.Fake(); _identityService = A.Fake(); + _identity = A.Fake(); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_companyRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_consentRepository); @@ -87,8 +87,10 @@ public CompanyDataBusinessLogicTests() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_languageRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_notificationRepository); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); var options = Options.Create(new CompanyDataSettings { MaxPageSize = 20, UseCaseParticipationMediaTypes = new[] { MediaTypeId.PDF }, SsiCertificateMediaTypes = new[] { MediaTypeId.PDF } }); _sut = new CompanyDataBusinessLogic(_portalRepositories, _mailingService, _custodianService, _dateTimeProvider, _identityService, options); @@ -151,7 +153,7 @@ public async Task GetCompanyRoleAndConsentAgreementDetails_CallsExpected() _fixture.Create(), }; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusDataAsync(A._)) .Returns((true, true)); @@ -187,7 +189,7 @@ public async Task GetCompanyRoleAndConsentAgreementDetails_ThrowsNotFoundExcepti // Arrange const string languageShortName = "en"; var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusDataAsync(A._)) .Returns((false, false)); @@ -210,7 +212,7 @@ public async Task GetCompanyRoleAndConsentAgreementDetails_ThrowsConflictExcepti // Arrange var companyId = Guid.NewGuid(); const string languageShortName = "en"; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusDataAsync(A._)) .Returns((false, true)); @@ -232,8 +234,8 @@ public async Task GetCompanyRoleAndConsentAgreementDetails_Throws() { // Arrange const string languageShortName = "eng"; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _languageRepository.IsValidLanguageCode(languageShortName)) .Returns(false); @@ -255,7 +257,7 @@ public async Task CreateCompanyRoleAndConsentAgreementDetailsAsync_ReturnsExpect { // Arrange var companyId = _identity.CompanyId; - var companyUserId = _identity.UserId; + var companyUserId = _identity.IdentityId; var agreementId1 = _fixture.Create(); var agreementId2 = _fixture.Create(); var agreementId3 = _fixture.Create(); @@ -575,7 +577,7 @@ public async Task GetCompanyAssigendUseCaseDetailsAsync_ResturnsExpected() // Arrange var companyId = Guid.NewGuid(); var companyAssignedUseCaseData = _fixture.CreateMany(2).ToAsyncEnumerable(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyAssigendUseCaseDetailsAsync(A._)) .Returns(companyAssignedUseCaseData); @@ -595,7 +597,7 @@ public async Task CreateCompanyAssignedUseCaseDetailsAsync_NoContent_ReturnsExpe var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((false, true, true)); @@ -616,7 +618,7 @@ public async Task CreateCompanyAssignedUseCaseDetailsAsync_AlreadyReported_Retur var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((true, true, true)); @@ -638,7 +640,7 @@ public async Task CreateCompanyAssignedUseCaseDetailsAsync_ThrowsConflictExcepti var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((false, false, true)); @@ -658,7 +660,7 @@ public async Task RemoveCompanyAssignedUseCaseDetailsAsync_ReturnsExpected() var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((true, true, true)); @@ -678,7 +680,7 @@ public async Task RemoveCompanyAssignedUseCaseDetailsAsync_companyStatus_ThrowsC var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((true, false, true)); @@ -698,7 +700,7 @@ public async Task RemoveCompanyAssignedUseCaseDetailsAsync_useCaseId_ThrowsConfl var useCaseId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _companyRepository.GetCompanyStatusAndUseCaseIdAsync(A._, A._)) .Returns((false, true, true)); @@ -836,7 +838,7 @@ public async Task CreateUseCaseParticipation_WithValidCall_CreatesExpected() A.CallTo(() => _companySsiDetailsRepository.CheckSsiDetailsExistsForCompany(_identity.CompanyId, VerifiedCredentialTypeId.TRACEABILITY_FRAMEWORK, VerifiedCredentialTypeKindId.USE_CASE, _traceabilityExternalTypeDetailId)) .Returns(false); - A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.TRACEABILITY_FRAMEWORK, A._, CompanySsiDetailStatusId.PENDING, _identity.UserId, A>._)) + A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.TRACEABILITY_FRAMEWORK, A._, CompanySsiDetailStatusId.PENDING, _identity.IdentityId, A>._)) .Invokes((Guid companyId, VerifiedCredentialTypeId verifiedCredentialTypeId, Guid docId, CompanySsiDetailStatusId companySsiDetailStatusId, Guid userId, Action? setOptionalFields) => { var ssiDetail = new CompanySsiDetail(Guid.NewGuid(), companyId, verifiedCredentialTypeId, companySsiDetailStatusId, docId, userId, DateTimeOffset.UtcNow); @@ -861,9 +863,9 @@ public async Task CreateUseCaseParticipation_WithValidCall_CreatesExpected() documents.Should().ContainSingle(); var document = documents.Single(); document.DocumentTypeId.Should().Be(DocumentTypeId.PRESENTATION); - document.CompanyUserId.Should().Be(_identity.UserId); + document.CompanyUserId.Should().Be(_identity.IdentityId); document.DocumentStatusId.Should().Be(DocumentStatusId.PENDING); - A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.TRACEABILITY_FRAMEWORK, document.Id, CompanySsiDetailStatusId.PENDING, _identity.UserId, A>._)) + A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.TRACEABILITY_FRAMEWORK, document.Id, CompanySsiDetailStatusId.PENDING, _identity.IdentityId, A>._)) .MustHaveHappenedOnceExactly(); ssiDetails.Should().ContainSingle(); var detail = ssiDetails.Single(); @@ -941,7 +943,7 @@ public async Task CreateSsiCertificate_WithValidCall_CreatesExpected() A.CallTo(() => _companySsiDetailsRepository.CheckSsiDetailsExistsForCompany(_identity.CompanyId, VerifiedCredentialTypeId.DISMANTLER_CERTIFICATE, VerifiedCredentialTypeKindId.CERTIFICATE, null)) .Returns(false); - A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.DISMANTLER_CERTIFICATE, A._, CompanySsiDetailStatusId.PENDING, _identity.UserId, A>._)) + A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.DISMANTLER_CERTIFICATE, A._, CompanySsiDetailStatusId.PENDING, _identity.IdentityId, A>._)) .Invokes((Guid companyId, VerifiedCredentialTypeId verifiedCredentialTypeId, Guid docId, CompanySsiDetailStatusId companySsiDetailStatusId, Guid userId, Action? setOptionalFields) => { var ssiDetail = new CompanySsiDetail(Guid.NewGuid(), companyId, verifiedCredentialTypeId, companySsiDetailStatusId, docId, userId, DateTimeOffset.UtcNow); @@ -966,9 +968,9 @@ public async Task CreateSsiCertificate_WithValidCall_CreatesExpected() documents.Should().ContainSingle(); var document = documents.Single(); document.DocumentTypeId.Should().Be(DocumentTypeId.PRESENTATION); - document.CompanyUserId.Should().Be(_identity.UserId); + document.CompanyUserId.Should().Be(_identity.IdentityId); document.DocumentStatusId.Should().Be(DocumentStatusId.PENDING); - A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.DISMANTLER_CERTIFICATE, document.Id, CompanySsiDetailStatusId.PENDING, _identity.UserId, A>._)) + A.CallTo(() => _companySsiDetailsRepository.CreateSsiDetails(_identity.CompanyId, VerifiedCredentialTypeId.DISMANTLER_CERTIFICATE, document.Id, CompanySsiDetailStatusId.PENDING, _identity.IdentityId, A>._)) .MustHaveHappenedOnceExactly(); ssiDetails.Should().ContainSingle(); var detail = ssiDetails.Single(); @@ -1190,7 +1192,7 @@ public async Task ApproveCredential_WithValidRequest_ReturnsExpected(VerifiedCre notifications.Should().ContainSingle(); var notification = notifications.Single(); notification.NotificationTypeId.Should().Be(NotificationTypeId.CREDENTIAL_APPROVAL); - notification.CreatorUserId.Should().Be(_identity.UserId); + notification.CreatorUserId.Should().Be(_identity.IdentityId); detail.CompanySsiDetailStatusId.Should().Be(CompanySsiDetailStatusId.ACTIVE); detail.DateLastChanged.Should().Be(now); @@ -1317,7 +1319,7 @@ public async Task ApproveCredential_WithoutUserMail_ReturnsExpected(VerifiedCred notifications.Should().ContainSingle(); var notification = notifications.Single(); notification.NotificationTypeId.Should().Be(NotificationTypeId.CREDENTIAL_APPROVAL); - notification.CreatorUserId.Should().Be(_identity.UserId); + notification.CreatorUserId.Should().Be(_identity.IdentityId); detail.CompanySsiDetailStatusId.Should().Be(CompanySsiDetailStatusId.ACTIVE); detail.DateLastChanged.Should().Be(now); @@ -1405,7 +1407,7 @@ public async Task RejectCredential_WithValidRequest_ReturnsExpected() notifications.Should().ContainSingle(); var notification = notifications.Single(); notification.NotificationTypeId.Should().Be(NotificationTypeId.CREDENTIAL_REJECTED); - notification.CreatorUserId.Should().Be(_identity.UserId); + notification.CreatorUserId.Should().Be(_identity.IdentityId); detail.CompanySsiDetailStatusId.Should().Be(CompanySsiDetailStatusId.INACTIVE); detail.DateLastChanged.Should().Be(now); @@ -1448,7 +1450,7 @@ public async Task RejectCredential_WithoutUserMail_ReturnsExpected() notifications.Should().ContainSingle(); var notification = notifications.Single(); notification.NotificationTypeId.Should().Be(NotificationTypeId.CREDENTIAL_REJECTED); - notification.CreatorUserId.Should().Be(_identity.UserId); + notification.CreatorUserId.Should().Be(_identity.IdentityId); detail.CompanySsiDetailStatusId.Should().Be(CompanySsiDetailStatusId.INACTIVE); detail.DateLastChanged.Should().Be(now); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/ConnectorsBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/ConnectorsBusinessLogicTests.cs index 5025ebdea7..74d86d2d98 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/ConnectorsBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/ConnectorsBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -46,15 +45,8 @@ public class ConnectorsBusinessLogicTests private static readonly Guid CompanyIdWithoutSdDocument = Guid.NewGuid(); private static readonly Guid ExistingConnectorId = Guid.NewGuid(); private static readonly Guid CompanyWithoutBpnId = Guid.NewGuid(); - private static readonly string IamUserId = Guid.NewGuid().ToString(); - private static readonly string IamUserWithoutSdDocumentId = Guid.NewGuid().ToString(); - private static readonly string UserWithoutBpn = Guid.NewGuid().ToString(); - private static readonly string TechnicalUserId = Guid.NewGuid().ToString(); private readonly Guid ValidOfferSubscriptionId = Guid.NewGuid(); - private readonly IdentityData _identity = new(IamUserId, CompanyUserId, IdentityTypeId.COMPANY_USER, ValidCompanyId); - private readonly IdentityData _identityWithoutSdDocument = new(IamUserWithoutSdDocumentId, CompanyUserId, IdentityTypeId.COMPANY_USER, CompanyIdWithoutSdDocument); - private readonly IdentityData _identityWithoutBpn = new(UserWithoutBpn, CompanyUserId, IdentityTypeId.COMPANY_USER, CompanyWithoutBpnId); - private readonly IdentityData _technicalUserIdentity = new(TechnicalUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_SERVICE_ACCOUNT, ValidCompanyId); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly List _connectors; private readonly ICountryRepository _countryRepository; @@ -86,6 +78,7 @@ public ConnectorsBusinessLogicTests() _serviceAccountRepository = A.Fake(); _offerSubscriptionRepository = A.Fake(); _identityService = A.Fake(); + _identity = A.Fake(); _connectors = new List(); var options = A.Fake>(); _settings = new ConnectorsSettings @@ -103,9 +96,10 @@ public ConnectorsBusinessLogicTests() A.CallTo(() => options.Value).Returns(_settings); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); var logger = A.Fake>(); + SetupIdentity(); + _logic = new ConnectorsBusinessLogic(_portalRepositories, options, _sdFactoryBusinessLogic, _identityService, logger); } @@ -191,7 +185,7 @@ public async Task CreateConnectorAsync_WithoutSelfDescriptionDocument_ThrowsUnex { // Arrange var connectorInput = new ConnectorInputModel("connectorName", "https://test.de", "de", null); - A.CallTo(() => _identityService.IdentityData).Returns(_identityWithoutSdDocument); + A.CallTo(() => _identity.CompanyId).Returns(CompanyIdWithoutSdDocument); // Act async Task Act() => await _logic.CreateConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -220,7 +214,7 @@ public async Task CreateConnectorAsync_WithCompanyWithoutBpn_ThrowsUnexpectedCon { // Arrange var connectorInput = new ConnectorInputModel("connectorName", "https://test.de", "de", null); - A.CallTo(() => _identityService.IdentityData).Returns(_identityWithoutBpn); + A.CallTo(() => _identity.CompanyId).Returns(CompanyWithoutBpnId); // Act async Task Act() => await _logic.CreateConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -269,7 +263,8 @@ public async Task CreateManagedConnectorAsync_WithTechnicalUser_ReturnsCreatedCo { // Arrange var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", ValidOfferSubscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act var result = await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -299,10 +294,11 @@ public async Task CreateManagedConnectorAsync_WithNotExistingSubscription_Throws { // Arrange var subscriptionId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, _technicalUserIdentity.CompanyId)) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, ValidCompanyId)) .Returns((false, default, default, default, default, default, default)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act async Task Act() => await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -317,10 +313,11 @@ public async Task CreateManagedConnectorAsync_WithCallerNotOfferProvider_ThrowsF { // Arrange var subscriptionId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, _technicalUserIdentity.CompanyId)) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, ValidCompanyId)) .Returns((true, false, default, default, default, default, default)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act async Task Act() => await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -335,10 +332,11 @@ public async Task CreateManagedConnectorAsync_WithOfferAlreadyLinked_ThrowsUnexp { // Arrange var subscriptionId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, _technicalUserIdentity.CompanyId)) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, ValidCompanyId)) .Returns((true, true, true, default, default, default, default)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act async Task Act() => await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -353,10 +351,11 @@ public async Task CreateManagedConnectorAsync_WithInactiveSubscription_ThrowsUne { // Arrange var subscriptionId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, _technicalUserIdentity.CompanyId)) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, ValidCompanyId)) .Returns((true, true, false, OfferSubscriptionStatusId.INACTIVE, default, default, default)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act async Task Act() => await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -371,7 +370,7 @@ public async Task CreateManagedConnectorAsync_WithoutExistingSelfDescriptionDocu { // Arrange var subscriptionId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, A.That.Matches(x => x == _identity.CompanyId || x == _technicalUserIdentity.CompanyId))) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, A.That.Matches(x => x == ValidCompanyId))) .Returns((true, true, false, OfferSubscriptionStatusId.ACTIVE, null, ValidCompanyId, ValidCompanyBpn)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); @@ -389,10 +388,11 @@ public async Task CreateManagedConnectorAsync_WithSubscribingCompanyWithoutBpn_T // Arrange var subscriptionId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, _technicalUserIdentity.CompanyId)) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(subscriptionId, ValidCompanyId)) .Returns((true, true, false, OfferSubscriptionStatusId.ACTIVE, Guid.NewGuid(), companyId, null)); var connectorInput = new ManagedConnectorInputModel("connectorName", "https://test.de", "de", subscriptionId, null); - A.CallTo(() => _identityService.IdentityData).Returns(_technicalUserIdentity); + + SetupTechnicalIdentity(); // Act async Task Act() => await _logic.CreateManagedConnectorAsync(connectorInput, CancellationToken.None).ConfigureAwait(false); @@ -927,7 +927,7 @@ public async Task UpdateConnectorUrl_WithCompanyBpnNotSet_ThrowsConflictExceptio .Create(); A.CallTo(() => _connectorsRepository.GetConnectorUpdateInformation(connectorId, _identity.CompanyId)) .Returns(data); - A.CallTo(() => _userRepository.GetCompanyBpnForIamUserAsync(_identity.UserId)) + A.CallTo(() => _userRepository.GetCompanyBpnForIamUserAsync(_identity.IdentityId)) .Returns((string?)null); // Act @@ -1118,7 +1118,7 @@ private void SetupRepositoryMethods() .Returns((ValidCompanyBpn, null)); A.CallTo(() => _companyRepository.GetCompanyBpnAndSelfDescriptionDocumentByIdAsync(A.That.Not.Matches(x => x == ValidCompanyId || x == CompanyIdWithoutSdDocument))) .Returns((null, null)); - A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(ValidOfferSubscriptionId, A.That.Matches(x => x == _identity.CompanyId || x == _technicalUserIdentity.CompanyId))) + A.CallTo(() => _offerSubscriptionRepository.CheckOfferSubscriptionWithOfferProvider(ValidOfferSubscriptionId, ValidCompanyId)) .Returns((true, true, false, OfferSubscriptionStatusId.ACTIVE, Guid.NewGuid(), ValidCompanyId, ValidCompanyBpn)); A.CallTo(() => _connectorsRepository.CreateConnector(A._, A._, A._, A?>._)) @@ -1160,5 +1160,18 @@ private void SetupRepositoryMethods() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerSubscriptionRepository); } + private void SetupIdentity() + { + A.CallTo(() => _identity.IdentityId).Returns(CompanyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(ValidCompanyId); + } + + private void SetupTechnicalIdentity() + { + A.CallTo(() => _identity.IdentityId).Returns(ServiceAccountUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_SERVICE_ACCOUNT); + } + #endregion } diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs index dbd2f0718e..e40189cfee 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -32,13 +31,11 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Busin public class DocumentsBusinessLogicTests { private static readonly Guid ValidDocumentId = Guid.NewGuid(); - private static readonly string IamUserId = Guid.NewGuid().ToString(); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly IDocumentRepository _documentRepository; private readonly IPortalRepositories _portalRepositories; private readonly IOptions _options; - private readonly DocumentsBusinessLogic _sut; private readonly IIdentityService _identityService; public DocumentsBusinessLogicTests() @@ -54,11 +51,14 @@ public DocumentsBusinessLogicTests() { EnableSeedEndpoint = true }); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_documentRepository); - _sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); } #region GetSeedData @@ -118,9 +118,10 @@ public async Task GetDocumentAsync_WithValidData_ReturnsExpected() { // Arrange SetupFakesForGetDocument(); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act - var result = await _sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); + var result = await sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -134,9 +135,10 @@ public async Task GetDocumentAsync_WithNotExistingDocument_ThrowsNotFoundExcepti // Arrange var documentId = Guid.NewGuid(); SetupFakesForGetDocument(); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act - async Task Act() => await _sut.GetDocumentAsync(documentId).ConfigureAwait(false); + async Task Act() => await sut.GetDocumentAsync(documentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -147,12 +149,13 @@ public async Task GetDocumentAsync_WithNotExistingDocument_ThrowsNotFoundExcepti public async Task GetDocumentAsync_WithWrongUser_ThrowsForbiddenException() { // Arrange - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); SetupFakesForGetDocument(); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act - async Task Act() => await _sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); + async Task Act() => await sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -170,9 +173,10 @@ public async Task GetSelfDescriptionDocumentAsync_WithValidData_ReturnsExpected( var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentDataByIdAndTypeAsync(ValidDocumentId, DocumentTypeId.SELF_DESCRIPTION)) .ReturnsLazily(() => new ValueTuple(content, "test.json", MediaTypeId.JSON)); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act - var result = await _sut.GetSelfDescriptionDocumentAsync(ValidDocumentId).ConfigureAwait(false); + var result = await sut.GetSelfDescriptionDocumentAsync(ValidDocumentId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -188,9 +192,10 @@ public async Task GetSelfDescriptionDocumentAsync_WithNotExistingDocument_Throws var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentDataByIdAndTypeAsync(documentId, DocumentTypeId.SELF_DESCRIPTION)) .ReturnsLazily(() => new ValueTuple()); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act - async Task Act() => await _sut.GetSelfDescriptionDocumentAsync(documentId).ConfigureAwait(false); + async Task Act() => await sut.GetSelfDescriptionDocumentAsync(documentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -207,9 +212,10 @@ public async Task GetFrameDocumentAsync_ReturnsExpectedResult() var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple(content, "test.json", true, MediaTypeId.JSON)); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); //Act - var result = await _sut.GetFrameDocumentAsync(documentId).ConfigureAwait(false); + var result = await sut.GetFrameDocumentAsync(documentId).ConfigureAwait(false); // Assert A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)).MustHaveHappenedOnceExactly(); @@ -225,9 +231,10 @@ public async Task GetFrameDocumentAsync_WithInvalidDocumentTypeId_ThrowsNotFound var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple(content, "test.json", false, MediaTypeId.JSON)); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); //Act - var Act = () => _sut.GetFrameDocumentAsync(documentId); + var Act = () => sut.GetFrameDocumentAsync(documentId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -241,9 +248,10 @@ public async Task GetFrameDocumentAsync_WithInvalidDocumentId_ThrowsNotFoundExce var documentId = Guid.NewGuid(); A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple()); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); //Act - var Act = () => _sut.GetFrameDocumentAsync(documentId); + var Act = () => sut.GetFrameDocumentAsync(documentId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs index 91b1ee0a53..7f370cae3d 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs @@ -57,7 +57,7 @@ public class IdentityProviderBusinessLogicTests private readonly Encoding _encoding; private readonly Guid _companyId; private readonly Guid _invalidCompanyId; - private readonly IdentityData _identity; + private readonly IIdentityData _identity; private readonly Guid _sharedIdentityProviderId; private readonly string _sharedIdpAlias; private readonly Guid _otherIdentityProviderId; @@ -80,6 +80,7 @@ public IdentityProviderBusinessLogicTests() _options = A.Fake>(); _document = A.Fake(); _logger = A.Fake>(); + _identity = A.Fake(); _companyId = _fixture.Create(); _invalidCompanyId = _fixture.Create(); @@ -89,8 +90,10 @@ public IdentityProviderBusinessLogicTests() _otherIdentityProviderId = _fixture.Create(); _otherIdpAlias = _fixture.Create(); _encoding = _fixture.Create(); - _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, _companyId); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(_companyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _errorMessageService = A.Fake(); @@ -454,7 +457,7 @@ public async Task CreateOwnCompanyIdentityProviderAsync_WithInvalidCompany_Throw // Arrange var companyId = Guid.NewGuid(); SetupCreateOwnCompanyIdentityProvider(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identity.CompanyId).Returns(companyId); var sut = new IdentityProviderBusinessLogic( _portalRepositories, @@ -486,7 +489,7 @@ public async Task CreateOwnCompanyIdentityProviderAsync_WithNotAllowedCompanyFor _logger); SetupCreateOwnCompanyIdentityProvider(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = _invalidCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(_invalidCompanyId); // Act async Task Act() => await sut.CreateOwnCompanyIdentityProviderAsync(IamIdentityProviderProtocol.SAML, IdentityProviderTypeId.MANAGED, null).ConfigureAwait(false); @@ -1546,7 +1549,7 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns(((string?, string?, bool))default); + .Returns(((bool, string?, bool))default); // Act async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); @@ -1573,7 +1576,9 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((null, "cl1", false)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns((string?)null); // Act async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); @@ -1588,7 +1593,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias { // Arrange var identityProviderId = Guid.NewGuid(); - var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) @@ -1601,7 +1605,7 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), null, false)); + .Returns((true, null, false)); // Act async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); @@ -1616,7 +1620,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameC { // Arrange var identityProviderId = Guid.NewGuid(); - var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) @@ -1629,7 +1632,7 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameC _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", false)); + .Returns((true, "cl1", false)); // Act async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); @@ -1644,7 +1647,7 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithKeycloak { // Arrange var identityProviderId = Guid.NewGuid(); - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) @@ -1657,8 +1660,9 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithKeycloak _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); - A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId.ToString(), A._)) + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())).Returns(iamUserId); + A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(iamUserId, A._)) .Throws(new KeycloakEntityConflictException("test")); // Act @@ -1674,7 +1678,7 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Ca { // Arrange var identityProviderId = Guid.NewGuid(); - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) @@ -1688,13 +1692,14 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Ca _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())).Returns(iamUserId); // Act var result = await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert - A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId.ToString(), A._)) + A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(iamUserId, A._)) .MustHaveHappenedOnceExactly(); result.userName.Should().Be("test-user"); } @@ -1720,7 +1725,7 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns(((string?, string?, bool))default); + .Returns(((bool, string?, bool))default); // Act async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); @@ -1747,7 +1752,9 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((null, "cl1", false)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns((string?)null); // Act async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); @@ -1761,7 +1768,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias_ThrowsNotFoundException() { // Arrange - var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() @@ -1775,7 +1781,7 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), null, false)); + .Returns((true, null, false)); // Act async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); @@ -1789,7 +1795,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameCompany_ThrowsForbiddenException() { // Arrange - var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() @@ -1803,7 +1808,7 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", false)); + .Returns((true, "cl1", false)); // Act async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); @@ -1817,7 +1822,7 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_CallsExpected() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var data = _fixture.Build() @@ -1831,15 +1836,17 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); // Act var result = await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert - A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) + A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, "cl1")) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId.ToString(), A._)) + A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(iamUserId, A._)) .MustHaveHappenedOnceExactly(); result.userName.Should().Be("user-name"); } @@ -1862,7 +1869,7 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUserI _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns(((string?, string?, bool))default); + .Returns(((bool, string?, bool))default); // Act async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); @@ -1886,7 +1893,9 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUserI _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((null, "cl1", false)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns((string?)null); // Act async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); @@ -1900,7 +1909,6 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUserI public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias_ThrowsNotFoundException() { // Arrange - var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -1911,7 +1919,7 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias_Th _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), null, false)); + .Returns((true, null, false)); // Act async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); @@ -1925,7 +1933,6 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias_Th public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameCompany_ThrowsForbiddenException() { // Arrange - var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -1936,7 +1943,7 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameComp _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", false)); + .Returns((true, "cl1", false)); // Act async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); @@ -1950,7 +1957,7 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameComp public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutExistingCompanyUser_ThrowsNotFound() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -1961,8 +1968,10 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutExisting _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); - A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId.ToString())) + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId)) .Returns(Enumerable.Empty().ToAsyncEnumerable()); // Act @@ -1971,13 +1980,16 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutExisting // Assert var ex = await Assert.ThrowsAsync(Act); ex.Message.Should().Be($"identityProviderLink for identityProvider {identityProviderId} not found in keycloak for user {companyUserId}"); + + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId)) + .MustHaveHappenedOnceExactly(); } [Fact] public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_CallsExpected() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -1988,9 +2000,11 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Calls _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); - A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId.ToString())) - .Returns(Enumerable.Repeat(new IdentityProviderLink("cl1", userEntityId.ToString(), "user-name"), 1).ToAsyncEnumerable()); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId)) + .Returns(Enumerable.Repeat(new IdentityProviderLink("cl1", iamUserId, "user-name"), 1).ToAsyncEnumerable()); // Act var result = await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); @@ -2007,7 +2021,7 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Calls public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithKeycloakError_ThrowsNotFound() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -2018,8 +2032,10 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithKeycloakErro _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); - A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); + A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, "cl1")) .Throws(new KeycloakEntityNotFoundException("just a test")); // Act @@ -2034,7 +2050,7 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithKeycloakErro public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithValid_CallsExpected() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = _fixture.Create(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -2045,13 +2061,15 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithValid_CallsE _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); + .Returns((true, "cl1", true)); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); // Act await sut.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert - A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) + A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(iamUserId, "cl1")) .MustHaveHappenedOnceExactly(); } @@ -2063,7 +2081,7 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithValid_CallsE public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutIdentityProviderIds_ThrowsControllerArgumentException() { // Arrange - var userEntityId = Guid.NewGuid(); + var iamUserId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( @@ -2074,7 +2092,7 @@ public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutIdentityPro _options, _logger); A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) - .Returns((userEntityId.ToString(), "cl1", true)); + .Returns((true, "cl1", true)); // Act async Task Act() => await sut.GetOwnCompanyUsersIdentityProviderDataAsync(Enumerable.Empty(), false).ToListAsync().ConfigureAwait(false); @@ -2351,12 +2369,14 @@ private void SetupFakes(IEnumerable userData, IEnumerable userData.Where(d => d.CompanyUserId == companyUserId) .Select(d => ( - d.UserEntityId, d.FirstName, d.LastName, d.Email )).FirstOrDefault()); + A.CallTo(() => _provisioningManager.GetUserByUserName(A._)).ReturnsLazily((string userName) => + userData.SingleOrDefault(x => x.CompanyUserId == Guid.Parse(userName))?.IamUserId); + A.CallTo(() => _identityProviderRepository.GetCompanyIdentityProviderCategoryDataUntracked(A.That.Not.IsEqualTo(_companyId))).Returns( Enumerable.Empty<(Guid, IdentityProviderCategoryId, string?, IdentityProviderTypeId)>().ToAsyncEnumerable()); A.CallTo(() => _identityProviderRepository.GetCompanyIdentityProviderCategoryDataUntracked(A.That.IsEqualTo(_companyId))).Returns( @@ -2373,10 +2393,10 @@ private void SetupFakes(IEnumerable userData, IEnumerable return idp; }); - A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(A._)).ReturnsLazily((string userEntityId) => + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(A._)).ReturnsLazily((Func>)((string iamUserId) => { - var user = userData.First(u => u.UserEntityId == userEntityId); - return new[] { + var user = userData.First((Func)(u => u.IamUserId == iamUserId)); + return (new[] { new IdentityProviderLink( _sharedIdpAlias, user.SharedIdpUserId, @@ -2387,8 +2407,8 @@ private void SetupFakes(IEnumerable userData, IEnumerable user.OtherIdpUserId, user.OtherIdpUserName ) - }.ToAsyncEnumerable(); - }); + }).ToAsyncEnumerable(); + })); } private string HeaderLine() @@ -2423,7 +2443,7 @@ private string NextLine(TestUserData userData) }); } - private record TestUserData(Guid CompanyUserId, string UserEntityId, string FirstName, string LastName, string Email, string SharedIdpUserId, string SharedIdpUserName, string OtherIdpUserId, string OtherIdpUserName); + private record TestUserData(Guid CompanyUserId, string IamUserId, string FirstName, string LastName, string Email, string SharedIdpUserId, string SharedIdpUserName, string OtherIdpUserId, string OtherIdpUserName); #endregion } diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs index 299342c91b..6efddffcf0 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs @@ -50,7 +50,7 @@ public class NetworkBusinessLogicTests private readonly IFixture _fixture; - private readonly IdentityData _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IIdentityService _identityService; private readonly IUserProvisioningService _userProvisioningService; private readonly INetworkRegistrationProcessHelper _networkRegistrationProcessHelper; @@ -84,6 +84,7 @@ public NetworkBusinessLogicTests() _networkRepository = A.Fake(); _identityProviderRepository = A.Fake(); _countryRepository = A.Fake(); + _identity = A.Fake(); var settings = new PartnerRegistrationSettings { @@ -92,6 +93,9 @@ public NetworkBusinessLogicTests() var options = A.Fake>(); A.CallTo(() => options.Value).Returns(settings); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_companyRepository); @@ -274,7 +278,7 @@ public async Task HandlePartnerRegistration_WithNoIdpIdSetAndNoManagedIdps_Throw .With(x => x.CountryAlpha2Code, "DE") .With(x => x.UserDetails, new[] { new UserDetailData(null, "123", "test", "test", "test", "test@email.com") }) .Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = NoIdpCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(NoIdpCompanyId); // Act async Task Act() => await _sut.HandlePartnerRegistration(data).ConfigureAwait(false); @@ -294,7 +298,7 @@ public async Task HandlePartnerRegistration_WithNoIdpIdSetAndMultipleManagedIdps .With(x => x.CountryAlpha2Code, "DE") .With(x => x.UserDetails, new[] { new UserDetailData(null, "123", "test", "test", "test", "test@email.com") }) .Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = MultiIdpCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(MultiIdpCompanyId); // Act async Task Act() => await _sut.HandlePartnerRegistration(data).ConfigureAwait(false); @@ -402,8 +406,7 @@ public async Task HandlePartnerRegistration_WithSingleIdpWithoutAlias_ThrowsServ new[] { new UserDetailData(null, "123", "ironman", "tony", "stark", "tony@stark.com") }, new[] { CompanyRoleId.APP_PROVIDER, CompanyRoleId.SERVICE_PROVIDER } ); - A.CallTo(() => _identityService.IdentityData) - .Returns(_identity with { CompanyId = NoAliasIdpCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(NoAliasIdpCompanyId); // Act async Task Act() => await _sut.HandlePartnerRegistration(data).ConfigureAwait(false); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/RegistrationStatusBusinessLogicTest.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/RegistrationStatusBusinessLogicTest.cs index c3e4caf8cc..9391a644da 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/RegistrationStatusBusinessLogicTest.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/RegistrationStatusBusinessLogicTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -28,12 +27,13 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.BusinessLogic; public class RegistrationStatusBusinessLogicTest { - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IPortalRepositories _portalRepositories; private readonly ICompanyRepository _companyRepository; @@ -41,7 +41,11 @@ public class RegistrationStatusBusinessLogicTest public RegistrationStatusBusinessLogicTest() { + _identity = A.Fake(); var identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => identityService.IdentityData).Returns(_identity); _portalRepositories = A.Fake(); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs index ad0c9b6643..9b5fa5f48b 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -46,8 +45,7 @@ public class ServiceAccountBusinessLogicTests private static readonly Guid ValidConnectorId = Guid.NewGuid(); private static readonly Guid ValidServiceAccountId = Guid.NewGuid(); private static readonly Guid InactiveServiceAccount = Guid.NewGuid(); - private static readonly string ValidAdminId = Guid.NewGuid().ToString(); - private readonly IdentityData _identity = new(ValidAdminId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, ValidCompanyId); + private readonly IIdentityData _identity; private readonly IEnumerable _userRoleIds = Enumerable.Repeat(Guid.NewGuid(), 1); private readonly IServiceAccountCreation _serviceAccountCreation; private readonly ICompanyRepository _companyRepository; @@ -77,7 +75,11 @@ public ServiceAccountBusinessLogicTests() _portalRepositories = A.Fake(); _serviceAccountCreation = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(ValidCompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _options = Options.Create(new ServiceAccountSettings @@ -108,7 +110,7 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithValidInput_ReturnsCrea public async Task CreateOwnCompanyServiceAccountAsync_WithInvalidUser_NotFoundException() { // Arrange - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); SetupCreateOwnCompanyServiceAccount(); var serviceAccountCreationInfos = new ServiceAccountCreationInfo("TheName", "Just a short description", IamClientAuthMethod.SECRET, Enumerable.Repeat(UserRoleId1, 1)); @@ -199,7 +201,7 @@ public async Task GetOwnCompanyServiceAccountDetailsAsync_WithInvalidUser_NotFou // Arrange SetupGetOwnCompanyServiceAccountDetails(); var invalidCompanyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = invalidCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(invalidCompanyId); var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act @@ -250,7 +252,7 @@ public async Task ResetOwnCompanyServiceAccountSecretAsync_WithInvalidUser_NotFo { // Arrange SetupResetOwnCompanyServiceAccountSecret(); - var invalidUser = _fixture.Create(); + var invalidUser = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(invalidUser); var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); @@ -336,7 +338,7 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithNotExistingServ // Arrange SetupUpdateOwnCompanyServiceAccountDetails(); var invalidServiceAccountId = Guid.NewGuid(); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(invalidServiceAccountId, _identity.CompanyId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(invalidServiceAccountId, ValidCompanyId)) .Returns((CompanyServiceAccountWithRoleDataClientId?)null); var data = new ServiceAccountEditableDetails(invalidServiceAccountId, "new name", "changed description", IamClientAuthMethod.SECRET); var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); @@ -357,7 +359,7 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithInactiveService var inactive = _fixture.Build() .With(x => x.UserStatusId, UserStatusId.INACTIVE) .Create(); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(InactiveServiceAccount, _identity.CompanyId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(InactiveServiceAccount, ValidCompanyId)) .Returns(inactive); var data = new ServiceAccountEditableDetails(InactiveServiceAccount, "new name", "changed description", IamClientAuthMethod.SECRET); var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); @@ -381,7 +383,7 @@ public async Task GetOwnCompanyServiceAccountsDataAsync_GetsExpectedData(UserSta { // Arrange var data = _fixture.CreateMany(15); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountsUntracked(_identity.CompanyId, null, null, userStatusId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountsUntracked(ValidCompanyId, null, null, userStatusId)) .Returns((int skip, int take) => Task.FromResult((Pagination.Source?)new Pagination.Source(data.Count(), data.Skip(skip).Take(take)))); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_serviceAccountRepository); @@ -523,9 +525,9 @@ public async Task GetServiceAccountRolesAsync_GetsExpectedData() private void SetupCreateOwnCompanyServiceAccount() { - A.CallTo(() => _companyRepository.GetBpnAndTechnicalUserRoleIds(_identity.CompanyId, ClientId)) + A.CallTo(() => _companyRepository.GetBpnAndTechnicalUserRoleIds(ValidCompanyId, ClientId)) .Returns((ValidBpn, new[] { UserRoleId1, UserRoleId2 })); - A.CallTo(() => _companyRepository.GetBpnAndTechnicalUserRoleIds(A.That.Not.Matches(x => x == _identity.CompanyId), ClientId)) + A.CallTo(() => _companyRepository.GetBpnAndTechnicalUserRoleIds(A.That.Not.Matches(x => x == ValidCompanyId), ClientId)) .Returns(((string?, IEnumerable))default); A.CallTo(() => _serviceAccountCreation.CreateServiceAccountAsync(A._, A.That.Matches(x => x == ValidCompanyId), A>._, CompanyServiceAccountTypeId.OWN, A._, true, null)) @@ -539,6 +541,11 @@ private void SetupGetOwnCompanyServiceAccountDetails() var authData = new ClientAuthData(IamClientAuthMethod.SECRET) { Secret = "topsecret" }; SetupGetOwnCompanyServiceAccount(); + var internalId = Guid.NewGuid().ToString(); + + A.CallTo(() => _provisioningManager.GetIdOfCentralClientAsync(A._)) + .Returns(internalId); + A.CallTo(() => _provisioningManager.GetCentralClientAuthDataAsync(A._)) .Returns(authData); @@ -562,9 +569,9 @@ private void SetupUpdateOwnCompanyServiceAccountDetails() var data = _fixture.Build() .With(x => x.UserStatusId, UserStatusId.ACTIVE) .Create(); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(ValidServiceAccountId, A.That.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(ValidServiceAccountId, ValidCompanyId)) .Returns(data); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(ValidServiceAccountId, A.That.Not.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(ValidServiceAccountId, A.That.Not.Matches(x => x == ValidCompanyId))) .Returns((CompanyServiceAccountWithRoleDataClientId?)null); A.CallTo(() => _provisioningManager.ResetCentralClientAuthDataAsync(A._)) @@ -577,20 +584,18 @@ private void SetupGetOwnCompanyServiceAccount() { var data = _fixture.Create(); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountDetailedDataUntrackedAsync( - A.That.Matches(x => x == ValidServiceAccountId), A.That.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(ValidServiceAccountId, ValidCompanyId)) .Returns(data); A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountDetailedDataUntrackedAsync( - A.That.Not.Matches(x => x == ValidServiceAccountId), A.That.Matches(x => x == _identity.CompanyId))) + A.That.Not.Matches(x => x == ValidServiceAccountId), ValidCompanyId)) .Returns((CompanyServiceAccountDetailedData?)null); - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountDetailedDataUntrackedAsync( - A.That.Matches(x => x == ValidServiceAccountId), A.That.Not.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(ValidServiceAccountId, A.That.Not.Matches(x => x == ValidCompanyId))) .Returns((CompanyServiceAccountDetailedData?)null); } private void SetupDeleteOwnCompanyServiceAccount(bool withServiceAccount, bool withClient, Connector? connector = null, Identity? identity = null) { - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, _identity.CompanyId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, ValidCompanyId)) .Returns((_userRoleIds, withServiceAccount ? ValidConnectorId : null, withClient ? ClientId : null, statusId: ConnectorStatusId.INACTIVE, OfferStatusId: OfferSubscriptionStatusId.PENDING)); A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(A.That.Not.Matches(x => x == ValidServiceAccountId), A._)) .Returns(((IEnumerable, Guid?, string?, ConnectorStatusId?, OfferSubscriptionStatusId?))default); @@ -622,7 +627,7 @@ private void SetupDeleteOwnCompanyServiceAccount(bool withServiceAccount, bool w private void SetupDeleteOwnCompanyServiceAccountForInvalidConnectorStatus() { - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, _identity.CompanyId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, ValidCompanyId)) .Returns((_userRoleIds, null, null, statusId: ConnectorStatusId.ACTIVE, OfferStatusId: OfferSubscriptionStatusId.PENDING)); A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(A.That.Not.Matches(x => x == ValidServiceAccountId), A._)) .Returns(((IEnumerable, Guid?, string?, ConnectorStatusId?, OfferSubscriptionStatusId?))default); @@ -633,7 +638,7 @@ private void SetupDeleteOwnCompanyServiceAccountForInvalidConnectorStatus() private void SetupDeleteOwnCompanyServiceAccountForValidOfferSubscription() { - A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, _identity.CompanyId)) + A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(ValidServiceAccountId, ValidCompanyId)) .Returns((_userRoleIds, null, null, statusId: ConnectorStatusId.INACTIVE, OfferSubscriptionStatusId.ACTIVE)); A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(A.That.Not.Matches(x => x == ValidServiceAccountId), A._)) .Returns(((IEnumerable, Guid?, string?, ConnectorStatusId?, OfferSubscriptionStatusId))default); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs index a5deb6ffb6..51f9f0e471 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -33,10 +32,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Busin public class SubscriptionConfigurationBusinessLogicTests { - private static readonly string IamUserId = new Guid("4C1A6851-D4E7-4E10-A011-3732CD045E8A").ToString(); private static readonly Guid ExistingCompanyId = new("857b93b1-8fcb-4141-81b0-ae81950d489e"); - private readonly IdentityData _noServiceProviderIdentity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8B", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, ExistingCompanyId); + private static readonly Guid NoServiceProviderCompanyId = Guid.NewGuid(); + private readonly IIdentityData _identity; private readonly ICompanyRepository _companyRepository; private readonly ICollection _serviceProviderDetails; @@ -63,7 +61,11 @@ public SubscriptionConfigurationBusinessLogicTests() _serviceProviderDetails = new HashSet(); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(ExistingCompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_companyRepository); @@ -189,7 +191,7 @@ public async Task SetProviderCompanyDetailsAsync_EmptyProviderDetailsId_ReturnsE // Arrange SetupProviderCompanyDetails(); var providerDetailData = new ProviderDetailData("https://www.service-url.com", "https://www.test.com"); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(_identity.CompanyId)) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(ExistingCompanyId)) .Returns((Guid.Empty, null!)); // Act @@ -215,7 +217,7 @@ public async Task SetProviderCompanyDetailsAsync_WithServiceProviderDetailsId_Re ProviderCompanyDetail? initialDetail = null; ProviderCompanyDetail? modifyDetail = null; - A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(_identity.CompanyId)) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(ExistingCompanyId)) .Returns((detailsId, existingUrl)); A.CallTo(() => _companyRepository.AttachAndModifyProviderCompanyDetails(A._, A>._, A>._)) @@ -244,7 +246,7 @@ public async Task SetProviderCompanyDetailsAsync_WithServiceProviderDetailsId_Re public async Task SetServiceProviderCompanyDetailsAsync_WithUnknownUser_ThrowsException() { //Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); SetupProviderCompanyDetails(); var providerDetailData = new ProviderDetailData("https://www.service-url.com", null); @@ -261,7 +263,8 @@ public async Task SetServiceProviderCompanyDetailsAsync_WithUnknownUser_ThrowsEx public async Task SetServiceProviderCompanyDetailsAsync_WithNotServiceProvider_ThrowsException() { //Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_noServiceProviderIdentity); + A.CallTo(() => _identity.CompanyId).Returns(NoServiceProviderCompanyId); + SetupProviderCompanyDetails(); var providerDetailData = new ProviderDetailData("https://www.service-url.com", null); @@ -270,7 +273,7 @@ public async Task SetServiceProviderCompanyDetailsAsync_WithNotServiceProvider_T //Assert var ex = await Assert.ThrowsAsync(Action); - ex.Message.Should().Be($"Company {_noServiceProviderIdentity.CompanyId} is not an app- or service-provider"); + ex.Message.Should().Be($"Company {NoServiceProviderCompanyId} is not an app- or service-provider"); _serviceProviderDetails.Should().BeEmpty(); A.CallTo(() => _portalRepositories.SaveAsync()).MustNotHaveHappened(); } @@ -318,7 +321,7 @@ public async Task GetProviderCompanyDetailsAsync_WithValidUser_ReturnsDetails() public async Task GetProviderCompanyDetailsAsync_WithInvalidUser_ThrowsException() { //Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); SetupProviderCompanyDetails(); //Act @@ -333,7 +336,7 @@ public async Task GetProviderCompanyDetailsAsync_WithInvalidServiceProvider_Thro { //Arrange SetupProviderCompanyDetails(); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(CompanyRoleId.SERVICE_PROVIDER, _identity.CompanyId)) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(CompanyRoleId.SERVICE_PROVIDER, ExistingCompanyId)) .ReturnsLazily(() => (new ProviderDetailReturnData(Guid.NewGuid(), Guid.NewGuid(), "https://new-test-service.de"), false)); //Act @@ -349,11 +352,11 @@ public async Task GetProviderCompanyDetailsAsync_WithInvalidServiceProvider_Thro private void SetupProviderCompanyDetails() { - A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Matches(x => x == _identity.CompanyId), A>._)) + A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Matches(x => x == ExistingCompanyId), A>._)) .Returns((true, true)); - A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Matches(x => x == _noServiceProviderIdentity.CompanyId), A>._)) + A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Matches(x => x == NoServiceProviderCompanyId), A>._)) .Returns((true, false)); - A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Not.Matches(x => x == _identity.CompanyId || x == _noServiceProviderIdentity.CompanyId), A>._)) + A.CallTo(() => _companyRepository.IsValidCompanyRoleOwner(A.That.Not.Matches(x => x == ExistingCompanyId || x == NoServiceProviderCompanyId), A>._)) .Returns(((bool, bool))default); A.CallTo(() => _companyRepository.CreateProviderCompanyDetail(A._, A._, A?>._)) @@ -364,14 +367,14 @@ private void SetupProviderCompanyDetails() _serviceProviderDetails.Add(providerCompanyDetail); }); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(A.That.Matches(x => x == CompanyRoleId.SERVICE_PROVIDER), A.That.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(A.That.Matches(x => x == CompanyRoleId.SERVICE_PROVIDER), A.That.Matches(x => x == ExistingCompanyId))) .ReturnsLazily(() => (new ProviderDetailReturnData(Guid.NewGuid(), Guid.NewGuid(), "https://new-test-service.de"), true)); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(A.That.Matches(x => x == CompanyRoleId.SERVICE_PROVIDER), A.That.Not.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailAsync(A.That.Matches(x => x == CompanyRoleId.SERVICE_PROVIDER), A.That.Not.Matches(x => x == ExistingCompanyId))) .ReturnsLazily(() => ((ProviderDetailReturnData, bool))default); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(A.That.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(A.That.Matches(x => x == ExistingCompanyId))) .ReturnsLazily(() => (Guid.NewGuid(), _fixture.Create())); - A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(A.That.Not.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _companyRepository.GetProviderCompanyDetailsExistsForUser(A.That.Not.Matches(x => x == ExistingCompanyId))) .Returns((Guid.Empty, null!)); } diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs index b5718dfe13..052391fbdb 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -59,16 +58,20 @@ public class UserBusinessLogicTests private readonly IOptions _options; private readonly CompanyUser _companyUser; private readonly Guid _identityProviderId; + private readonly string _identityProviderAlias; + private readonly string _identityProviderUserId; private readonly string _iamUserId; - private readonly string _adminIamUser; + private readonly string _createdCentralIamUserId; private readonly Guid _companyUserId; + private readonly Guid _companyId; private readonly Guid _validOfferId; private readonly Guid _offerWithoutNameId; - private readonly string _createdCentralUserId; + private readonly Guid _adminUserId; + private readonly Guid _adminCompanyId; + private readonly Guid _createdCentralUserId; + private readonly Guid _createdCentralCompanyId; private readonly string _displayName; - private readonly IdentityData _identity; - private readonly IdentityData _adminIdentity; - private readonly IdentityData _createdCentralIdentity; + private readonly IIdentityData _identity; private readonly ICollection _companyUserAssignedRole = new HashSet(); private readonly Func _processLine; private readonly Func _companyUserSelectFunction; @@ -101,23 +104,30 @@ public UserBusinessLogicTests() _options = Options.Create(_fixture.Create()); _identityProviderId = _fixture.Create(); + _identityProviderAlias = _fixture.Create(); + _identityProviderUserId = _fixture.Create(); _iamUserId = _fixture.Create(); - _adminIamUser = _fixture.Create(); - _companyUserId = _fixture.Create(); + _createdCentralIamUserId = _fixture.Create(); + _companyUserId = Guid.NewGuid(); + _companyId = Guid.NewGuid(); _validOfferId = _fixture.Create(); _offerWithoutNameId = _fixture.Create(); - _createdCentralUserId = _fixture.Create(); + _adminUserId = Guid.NewGuid(); + _adminCompanyId = Guid.NewGuid(); + _createdCentralUserId = Guid.NewGuid(); + _createdCentralCompanyId = Guid.NewGuid(); _displayName = _fixture.Create(); - _identity = new(_iamUserId, _companyUserId, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); - _adminIdentity = new(_adminIamUser, _companyUserId, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); - _createdCentralIdentity = new(_createdCentralUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); _processLine = A.Fake>(); _companyUserSelectFunction = A.Fake>(); + _identity = A.Fake(); _identityService = A.Fake(); + + A.CallTo(() => _identity.IdentityId).Returns(_companyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(_companyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); _settings = new UserSettings { @@ -532,14 +542,15 @@ public async Task TestDeleteOwnUserSuccess() _options ); - var identity = new Identity(_identity.UserId, DateTimeOffset.UtcNow, _identity.CompanyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER); - A.CallTo(() => _userRepository.AttachAndModifyIdentity(_identity.UserId, A>._, A>._)) + var identity = new Identity(_companyUserId, DateTimeOffset.UtcNow, _companyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER); + + A.CallTo(() => _userRepository.AttachAndModifyIdentity(_companyUserId, A>._, A>._)) .Invokes((Guid _, Action? init, Action modify) => { init?.Invoke(identity); modify.Invoke(identity); }); - A.CallTo(() => _userRepository.AttachAndModifyCompanyUser(_identity.UserId, null, A>._)) + A.CallTo(() => _userRepository.AttachAndModifyCompanyUser(_companyUserId, null, A>._)) .Invokes((Guid _, Action? init, Action modify) => { init?.Invoke(_companyUser); @@ -548,14 +559,15 @@ public async Task TestDeleteOwnUserSuccess() await sut.DeleteOwnUserAsync(_companyUserId).ConfigureAwait(false); - A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(A._, A._)).MustHaveHappened(); - A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(A._, A._)).MustHaveHappened(); - A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A._)).MustHaveHappened(); - A.CallTo(() => _userBusinessPartnerRepository.DeleteCompanyUserAssignedBusinessPartners(A>._)).MustHaveHappened(); - A.CallTo(() => _offerRepository.DeleteAppFavourites(A>._)).MustHaveHappened(); - A.CallTo(() => _userRolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustHaveHappened(); - A.CallTo(() => _applicationRepository.DeleteInvitations(A>._)).MustHaveHappened(); - A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappened(); + A.CallTo(() => _provisioningManager.GetUserByUserName(_companyUserId.ToString())).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(_identityProviderAlias, _iamUserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(_identityProviderAlias, _identityProviderUserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(_iamUserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _userBusinessPartnerRepository.DeleteCompanyUserAssignedBusinessPartners(A>.That.Matches(x => x.All(y => y.CompanyUserId == _companyUserId)))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerRepository.DeleteAppFavourites(A>.That.Matches(x => x.All(y => y.CompanyUserId == _companyUserId)))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _userRolesRepository.DeleteCompanyUserAssignedRoles(A>.That.Matches(x => x.All(y => y.CompanyUserId == _companyUserId)))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _applicationRepository.DeleteInvitations(A>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); identity.UserStatusId.Should().Be(UserStatusId.DELETED); } @@ -565,11 +577,10 @@ public async Task TestDeleteOwnUserInvalidUserThrows() { SetupFakesForUserDeletion(); - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); - A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(identity.UserId)) + A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(identity.IdentityId)) .Returns(((string?, CompanyUserAccountData))default!); var sut = new UserBusinessLogic( @@ -583,11 +594,12 @@ public async Task TestDeleteOwnUserInvalidUserThrows() _options ); - Task Act() => sut.DeleteOwnUserAsync(identity.UserId); + Task Act() => sut.DeleteOwnUserAsync(identity.IdentityId); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - error.Message.Should().Be($"user {identity.UserId} does not exist"); + error.Message.Should().Be($"user {identity.IdentityId} does not exist"); + A.CallTo(() => _provisioningManager.GetUserByUserName(A._)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(A._, A._)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A._)).MustNotHaveHappened(); A.CallTo(() => _userRolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustNotHaveHappened(); @@ -599,9 +611,8 @@ public async Task TestDeleteOwnUserInvalidCompanyUserThrows() { SetupFakesForUserDeletion(); - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); var sut = new UserBusinessLogic( _provisioningManager, @@ -617,8 +628,9 @@ public async Task TestDeleteOwnUserInvalidCompanyUserThrows() Task Act() => sut.DeleteOwnUserAsync(_companyUserId); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - error.Message.Should().Be($"companyUser {_companyUserId} is not the id of user {identity.UserId}"); + error.Message.Should().Be($"companyUser {_companyUserId} is not the id of user {identity.IdentityId}"); + A.CallTo(() => _provisioningManager.GetUserByUserName(A._)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(A._, A._)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A._)).MustNotHaveHappened(); A.CallTo(() => _userRolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustNotHaveHappened(); @@ -633,7 +645,8 @@ public async Task TestDeleteOwnUserInvalidCompanyUserThrows() public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_createdCentralUserId); + A.CallTo(() => _identity.CompanyId).Returns(_createdCentralCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -661,7 +674,8 @@ public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase( public async Task ModifyUserRoleAsync_WithOneRoleToDelete_DeletesTheRole() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -686,7 +700,8 @@ public async Task ModifyUserRoleAsync_WithOneRoleToDelete_DeletesTheRole() public async Task ModifyUserRoleAsync_WithNotExistingRole_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -713,7 +728,8 @@ public async Task ModifyUserRoleAsync_WithNotExistingRole_ThrowsException() public async Task ModifyUserRoleAsync_WithNotFoundCompanyUser_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -734,14 +750,15 @@ public async Task ModifyUserRoleAsync_WithNotFoundCompanyUser_ThrowsException() // Assert var ex = await Assert.ThrowsAsync(Action); - ex.Message.Should().Be($"CompanyUserId {userRoleInfo.CompanyUserId} is not associated with company {_adminIdentity.CompanyId}"); + ex.Message.Should().Be($"CompanyUserId {userRoleInfo.CompanyUserId} is not associated with company {_adminCompanyId}"); } [Fact] public async Task ModifyUserRoleAsync_WithInvalidOfferId_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -775,7 +792,8 @@ public async Task ModifyCoreOfferUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTh { // Arrange var notifications = new List(); - A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_createdCentralUserId); + A.CallTo(() => _identity.CompanyId).Returns(_createdCentralCompanyId); SetupFakesForUserRoleModification(notifications); var sut = new UserRolesBusinessLogic( @@ -811,7 +829,8 @@ public async Task ModifyAppUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTheDatab { // Arrange var notifications = new List(); - A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_createdCentralUserId); + A.CallTo(() => _identity.CompanyId).Returns(_createdCentralCompanyId); SetupFakesForUserRoleModification(notifications); var sut = new UserRolesBusinessLogic( @@ -847,9 +866,10 @@ public async Task ModifyAppUserRoleAsync_WithMultipleClients_AddsTwoRolesToTheDa var adminRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); var buyerRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); var supplierRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47663"); - A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_createdCentralUserId); + A.CallTo(() => _identity.CompanyId).Returns(_createdCentralCompanyId); A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, _companyUserId, A._)) - .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, _iamUserId, true, "The offer", "Tony", "Stark")); + .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, true, "The offer", "Tony", "Stark")); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) .Returns(new UserRoleModificationData[] @@ -903,9 +923,12 @@ public async Task ModifyAppUserRoleAsync_WithFailingAssignement_ThrowsServiceExc var adminRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); var buyerRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); var supplierRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47663"); - A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_createdCentralUserId); + A.CallTo(() => _identity.CompanyId).Returns(_createdCentralCompanyId); + A.CallTo(() => _provisioningManager.GetUserByUserName(_companyUserId.ToString())) + .Returns(_iamUserId); A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, _companyUserId, A._)) - .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, _iamUserId, true, "The offer", "Tony", "Stark")); + .Returns(new OfferIamUserData(true, new[] { iamClientId, iamClientId1 }, true, "The offer", "Tony", "Stark")); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) .Returns(new UserRoleModificationData[] @@ -945,7 +968,8 @@ public async Task ModifyAppUserRoleAsync_WithFailingAssignement_ThrowsServiceExc public async Task ModifyAppUserRolesAsync_WithOneRoleToDelete_DeletesTheRole() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); var notifications = new List(); SetupFakesForUserRoleModification(notifications); @@ -974,7 +998,8 @@ public async Task ModifyAppUserRolesAsync_WithOneRoleToDelete_DeletesTheRole() public async Task ModifyAppUserRolesAsync_WithNotExistingRole_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -1003,7 +1028,8 @@ public async Task ModifyAppUserRolesAsync_WithNotExistingRole_ThrowsException() public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -1025,7 +1051,7 @@ public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsExceptio // Assert var ex = await Assert.ThrowsAsync(Action); - ex.Message.Should().Be($"CompanyUserId {companyUserId} is not associated with company {_adminIdentity.CompanyId}"); + ex.Message.Should().Be($"CompanyUserId {companyUserId} is not associated with company {_adminCompanyId}"); A.CallTo(() => _notificationRepository.CreateNotification(_companyUserId, NotificationTypeId.ROLE_UPDATE_CORE_OFFER, false, A>._)) .MustNotHaveHappened(); } @@ -1034,7 +1060,8 @@ public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsExceptio public async Task ModifyAppUserRolesAsync_WithInvalidOfferId_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -1065,7 +1092,8 @@ public async Task ModifyAppUserRolesAsync_WithInvalidOfferId_ThrowsException() public async Task ModifyAppUserRolesAsync_WithoutOfferName_ThrowsException() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( @@ -1171,7 +1199,7 @@ public async Task TestDeleteOwnCompanyUsersAsyncError() .Returns(sharedIdpAlias); var invalidUserId = _fixture.Create(); - var invalidUserEntityId = _fixture.Create(); + var invalidIamUserId = _fixture.Create(); var companyUserIds = new[] { _fixture.Create(), @@ -1185,14 +1213,16 @@ public async Task TestDeleteOwnCompanyUsersAsyncError() (CompanyUserAccountData u) => new CompanyUserAccountData( u.CompanyUserId, - invalidUserEntityId, u.BusinessPartnerNumbers, u.RoleIds, u.OfferIds, u.InvitationIds )); - A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A.That.IsEqualTo(invalidUserEntityId))).Throws(_error); + A.CallTo(() => _provisioningManager.GetUserByUserName(invalidUserId.ToString())) + .Returns(invalidIamUserId); + + A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A.That.IsEqualTo(invalidIamUserId))).Throws(_error); var sut = new UserBusinessLogic( _provisioningManager, @@ -1227,7 +1257,7 @@ public async Task TestDeleteOwnCompanyUsersAsyncNoSharedIdpError() .Returns((string?)null); var invalidUserId = _fixture.Create(); - var invalidUserEntityId = _fixture.Create(); + var invalidIamUserId = _fixture.Create(); var companyUserIds = new[] { _fixture.Create(), @@ -1240,14 +1270,16 @@ public async Task TestDeleteOwnCompanyUsersAsyncNoSharedIdpError() A.CallTo(() => _companyUserSelectFunction(A.That.Matches(u => u.CompanyUserId == invalidUserId))).ReturnsLazily( (CompanyUserAccountData u) => new CompanyUserAccountData( u.CompanyUserId, - invalidUserEntityId, u.BusinessPartnerNumbers, u.RoleIds, u.OfferIds, u.InvitationIds )); - A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A.That.IsEqualTo(invalidUserEntityId))).Throws(_error); + A.CallTo(() => _provisioningManager.GetUserByUserName(invalidUserId.ToString())) + .Returns(invalidIamUserId); + + A.CallTo(() => _provisioningManager.DeleteCentralRealmUserAsync(A.That.IsEqualTo(invalidIamUserId))).Throws(_error); var sut = new UserBusinessLogic( _provisioningManager, @@ -1265,6 +1297,7 @@ public async Task TestDeleteOwnCompanyUsersAsyncNoSharedIdpError() result.Should().HaveCount(companyUserIds.Length - 1); result.Should().Match(r => Enumerable.SequenceEqual(r, companyUserIds.Take(2).Concat(companyUserIds.Skip(3)))); + A.CallTo(() => _provisioningManager.GetUserByUserName(invalidUserId.ToString())).MustHaveHappenedOnceExactly(); A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(A._, A._)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(A._, A._)).MustNotHaveHappened(); @@ -1286,7 +1319,7 @@ public async Task GetOwnCompanyAppUsersAsync_ReturnsExpectedResult() var appId = _fixture.Create(); var userId = Guid.NewGuid(); var companyUsers = _fixture.CreateMany(5); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); + A.CallTo(() => _identity.IdentityId).Returns(userId); A.CallTo(() => _userRepository.GetOwnCompanyAppUsersPaginationSourceAsync(A._, A._, A>._, A>._, A._)) .Returns((int skip, int take) => Task.FromResult((Pagination.Source?)new Pagination.Source(companyUsers.Count(), companyUsers.Skip(skip).Take(take)))); @@ -1311,7 +1344,7 @@ public async Task GetOwnCompanyAppUsersAsync_SecondPage_ReturnsExpectedResult() var appId = _fixture.Create(); var userId = Guid.NewGuid(); var companyUsers = _fixture.CreateMany(5); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); + A.CallTo(() => _identity.IdentityId).Returns(userId); A.CallTo(() => _userRepository.GetOwnCompanyAppUsersPaginationSourceAsync(A._, A._, A>._, A>._, A._)) .Returns((int skip, int take) => Task.FromResult((Pagination.Source?)new Pagination.Source(companyUsers.Count(), companyUsers.Skip(skip).Take(take)))); @@ -1337,11 +1370,13 @@ public async Task GetOwnCompanyAppUsersAsync_SecondPage_ReturnsExpectedResult() public async Task GetOwnCompanyAppUsersAsync_WithNonExistingCompanyUser_ThrowsNotFoundException() { // Arrange - var companyUserId = _fixture.Create(); + var companyUserId = Guid.NewGuid(); var businessPartnerNumber = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); - A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) - .Returns(((string?, bool, bool))default); + + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); + A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminCompanyId, businessPartnerNumber)) + .Returns(((bool, bool, bool))default); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); @@ -1359,9 +1394,10 @@ public async Task GetOwnCompanyAppUsersAsync_WithUnassignedBusinessPartner_Throw // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); - A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) - .Returns((string.Empty, false, false)); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); + A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminCompanyId, businessPartnerNumber)) + .Returns((true, false, false)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); @@ -1379,11 +1415,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithoutUserForBpn_ThrowsArgumentExc // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); - A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) - .Returns(((string?)null, true, false)); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns((string?)null); + A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminCompanyId, businessPartnerNumber)) + .Returns((true, true, true)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); @@ -1399,9 +1438,10 @@ public async Task GetOwnCompanyAppUsersAsync_WithInvalidUser_ThrowsForbiddenExce // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); - A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) - .Returns((Guid.NewGuid().ToString(), true, false)); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); + A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminCompanyId, businessPartnerNumber)) + .Returns((true, true, false)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); @@ -1418,18 +1458,21 @@ public async Task GetOwnCompanyAppUsersAsync_WithValidData_ThrowsForbiddenExcept { // Arrange var companyUserId = _fixture.Create(); + var iamUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); - A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) - .Returns((Guid.NewGuid().ToString(), true, true)); + A.CallTo(() => _identity.IdentityId).Returns(_adminUserId); + A.CallTo(() => _identity.CompanyId).Returns(_adminCompanyId); + A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminCompanyId, businessPartnerNumber)) + .Returns((true, true, true)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())).Returns(iamUserId); var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert - A.CallTo(() => _provisioningManager.DeleteCentralUserBusinessPartnerNumberAsync(A._, A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteCentralUserBusinessPartnerNumberAsync(iamUserId, businessPartnerNumber)).MustHaveHappenedOnceExactly(); A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); } @@ -1442,10 +1485,11 @@ public async Task GetOwnUserDetails_ReturnsExpected() { // Arrange var companyOwnUserDetails = _fixture.Create(); - var identity = _fixture.Create(); + var userId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); var userRoleIds = new[] { _fixture.Create(), _fixture.Create() }; - A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); + A.CallTo(() => _identity.IdentityId).Returns(userId); + A.CallTo(() => _identity.CompanyId).Returns(companyId); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>._)) .Returns(userRoleIds.ToAsyncEnumerable()); @@ -1459,7 +1503,7 @@ public async Task GetOwnUserDetails_ReturnsExpected() // Assert A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A> .That.IsSameSequenceAs(_options.Value.UserAdminRoles))).MustHaveHappenedOnceExactly(); - A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(identity.UserId, A>.That.IsSameSequenceAs(userRoleIds))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(userId, A>.That.IsSameSequenceAs(userRoleIds))).MustHaveHappenedOnceExactly(); result.Should().Be(companyOwnUserDetails); } @@ -1467,10 +1511,11 @@ public async Task GetOwnUserDetails_ReturnsExpected() public async Task GetOwnUserDetails_ThrowsNotFoundException() { // Arrange - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); - A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(identity.UserId, A>._)) + var userId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); + A.CallTo(() => _identity.IdentityId).Returns(userId); + A.CallTo(() => _identity.CompanyId).Returns(companyId); + A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(userId, A>._)) .Returns((CompanyOwnUserDetails)default!); var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, _logger, _options); @@ -1479,7 +1524,7 @@ public async Task GetOwnUserDetails_ThrowsNotFoundException() // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - error.Message.Should().Be($"no company-user data found for user {identity.UserId}"); + error.Message.Should().Be($"no company-user data found for user {userId}"); } #endregion @@ -1519,21 +1564,20 @@ private void SetupFakesForUserDeletion() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_applicationRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerRepository); - A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(A._)).Returns(_fixture.Create<(string? SharedIdpAlias, CompanyUserAccountData AccountData)>()); - A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(_identity.UserId)).Returns(( - SharedIdpAlias: (string?)_fixture.Create(), + A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(_companyUserId)).Returns(( + SharedIdpAlias: _identityProviderAlias, AccountData: _fixture.Build() .With(x => x.CompanyUserId, _companyUserId) .Create())); A.CallTo(() => _identityProviderRepository.GetSharedIdentityProviderIamAliasDataUntrackedAsync(A._)) .Returns((string?)null); - A.CallTo(() => _identityProviderRepository.GetSharedIdentityProviderIamAliasDataUntrackedAsync(_identity.CompanyId)) - .Returns(_fixture.Create()); + A.CallTo(() => _identityProviderRepository.GetSharedIdentityProviderIamAliasDataUntrackedAsync(_companyId)) + .Returns(_identityProviderAlias); A.CallTo(() => _userRepository.GetCompanyUserAccountDataUntrackedAsync(A>._, A._)) .Returns(Enumerable.Empty().ToAsyncEnumerable()); - A.CallTo(() => _userRepository.GetCompanyUserAccountDataUntrackedAsync(A>._, A.That.IsEqualTo(_identity.CompanyId))) + A.CallTo(() => _userRepository.GetCompanyUserAccountDataUntrackedAsync(A>._, _companyId)) .ReturnsLazily((IEnumerable companyUserIds, Guid adminId) => companyUserIds.Select(id => _fixture.Build().With(x => x.CompanyUserId, id).Create()) .Select(u => _companyUserSelectFunction(u)) @@ -1541,7 +1585,8 @@ private void SetupFakesForUserDeletion() A.CallTo(() => _companyUserSelectFunction(A._)).ReturnsLazily((CompanyUserAccountData u) => u); - A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(A._, A._)).Returns(_fixture.Create()); + A.CallTo(() => _provisioningManager.GetUserByUserName(_companyUserId.ToString())).Returns(_iamUserId); + A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(_identityProviderAlias, _iamUserId)).Returns(_identityProviderUserId); } private void SetupFakesForUserRoleModification(List? notifications = null) @@ -1550,14 +1595,18 @@ private void SetupFakesForUserRoleModification(List? notifications var adminRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); var buyerRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); var supplierRoleId = new Guid("9aae7a3b-b188-4a42-b46b-fb2ea5f47663"); - A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, _companyUserId, A.That.Matches(x => x == _adminIdentity.CompanyId || x == _createdCentralIdentity.CompanyId))) - .Returns(new OfferIamUserData(true, new[] { iamClientId }, _iamUserId, true, "The offer", "Tony", "Stark")); - A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_offerWithoutNameId, _companyUserId, A.That.Matches(x => x == _adminIdentity.CompanyId || x == _createdCentralIdentity.CompanyId))) - .Returns(new OfferIamUserData(true, new[] { iamClientId }, _iamUserId, true, null, "Tony", "Stark")); - A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(A.That.Not.Matches(x => x == _validOfferId || x == _offerWithoutNameId), _companyUserId, _adminIdentity.CompanyId)) - .Returns(new OfferIamUserData(false, Enumerable.Empty(), _iamUserId, true, null, "Tony", "Stark")); - A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, A.That.Not.Matches(x => x == _companyUserId), _adminIdentity.CompanyId)) - .Returns(new OfferIamUserData(true, new[] { iamClientId }, _iamUserId, false, "The offer", "Tony", "Stark")); + A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, _companyUserId, A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) + .Returns(new OfferIamUserData(true, new[] { iamClientId }, true, "The offer", "Tony", "Stark")); + A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_offerWithoutNameId, _companyUserId, A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) + .Returns(new OfferIamUserData(true, new[] { iamClientId }, true, null, "Tony", "Stark")); + A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(A.That.Not.Matches(x => x == _validOfferId || x == _offerWithoutNameId), _companyUserId, _adminCompanyId)) + .Returns(new OfferIamUserData(false, Enumerable.Empty(), true, null, "Tony", "Stark")); + A.CallTo(() => _userRepository.GetAppAssignedIamClientUserDataUntrackedAsync(_validOfferId, A.That.Not.Matches(x => x == _companyUserId), _adminCompanyId)) + .Returns(new OfferIamUserData(true, new[] { iamClientId }, false, "The offer", "Tony", "Stark")); + A.CallTo(() => _provisioningManager.GetUserByUserName(_companyUserId.ToString())) + .Returns(_iamUserId); + A.CallTo(() => _provisioningManager.GetUserByUserName(_createdCentralUserId.ToString())) + .Returns(_createdCentralIamUserId); A.CallTo(() => _userRolesRepository.GetAssignedAndMatchingAppRoles(A._, A>._, A._)) .Returns(new UserRoleModificationData[] @@ -1577,8 +1626,8 @@ private void SetupFakesForUserRoleModification(List? notifications new("Supplier", supplierRoleId, false), }.ToAsyncEnumerable()); - A.CallTo(() => _userRepository.GetCoreOfferAssignedIamClientUserDataUntrackedAsync(A.That.Matches(x => x == _validOfferId), A.That.Matches(x => x == _companyUserId), A.That.Matches(x => x == _adminIdentity.CompanyId || x == _createdCentralIdentity.CompanyId))) - .Returns(new CoreOfferIamUserData(true, new[] { iamClientId }, _iamUserId, true, "Tony", "Stark")); + A.CallTo(() => _userRepository.GetCoreOfferAssignedIamClientUserDataUntrackedAsync(A.That.Matches(x => x == _validOfferId), A.That.Matches(x => x == _companyUserId), A.That.Matches(x => x == _adminCompanyId || x == _createdCentralCompanyId))) + .Returns(new CoreOfferIamUserData(true, new[] { iamClientId }, true, "Tony", "Stark")); A.CallTo(() => _userRolesRepository.CreateIdentityAssignedRole(A._, A._)) .Invokes(x => @@ -1593,11 +1642,11 @@ private void SetupFakesForUserRoleModification(List? notifications A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _iamUserId), A>>._)) .Returns(new[] { (Client: iamClientId, Roles: new[] { "Existing Role", "Supplier" }.AsEnumerable()) }.ToAsyncEnumerable()); - A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _createdCentralUserId), A>>._)) + A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(A.That.Matches(x => x == _createdCentralIamUserId), A>>._)) .Returns(new[] { (Client: iamClientId, Roles: new[] { "Company Admin" }.AsEnumerable()) }.ToAsyncEnumerable()); A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync( - A.That.Not.Matches(x => x == _createdCentralUserId || x == _iamUserId), A>>._)) + A.That.Not.Matches(x => x == _createdCentralIamUserId || x == _iamUserId), A>>._)) .Returns(new[] { (Client: iamClientId, Roles: Enumerable.Empty()) }.ToAsyncEnumerable()); if (notifications != null) diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs index 4266386aad..bb7baa6b4d 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -31,6 +30,7 @@ using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using System.Text; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLogic.Tests; @@ -42,7 +42,7 @@ public class UserUploadBusinessLogicTests private readonly IOptions _options; private readonly IFormFile _document; private readonly Guid _identityProviderId; - private readonly IdentityData _identity; + private readonly IIdentityData _identity; private readonly IMailingService _mailingService; private readonly UserSettings _settings; private readonly Encoding _encoding; @@ -70,9 +70,11 @@ public UserUploadBusinessLogicTests() var clientId = _fixture.Create(); _settings = _fixture.Build().With(x => x.Portal, _fixture.Build().With(x => x.KeycloakClientID, clientId).Create()).Create(); _encoding = _fixture.Create(); - _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); - + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _errorMessageService = A.Fake(); @@ -94,7 +96,7 @@ public async Task TestSetup() var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); - A.CallTo(() => _userProvisioningService.GetCompanyNameIdpAliasData(A.That.IsEqualTo(_identityProviderId), _identity.UserId)).MustHaveHappened(); + A.CallTo(() => _userProvisioningService.GetCompanyNameIdpAliasData(A.That.IsEqualTo(_identityProviderId), _identity.IdentityId)).MustHaveHappened(); result.Should().NotBeNull(); result.Created.Should().Be(0); result.Error.Should().Be(0); @@ -327,7 +329,7 @@ public async Task TestSetupSharedIdp() var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); - A.CallTo(() => _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identity.UserId, A._)).MustHaveHappened(); + A.CallTo(() => _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identity.IdentityId, A._)).MustHaveHappened(); result.Should().NotBeNull(); result.Created.Should().Be(0); result.Error.Should().Be(0); @@ -524,10 +526,10 @@ private void SetupFakes(IEnumerable lines) A.CallTo(() => _options.Value).Returns(_settings); - A.CallTo(() => _userProvisioningService.GetCompanyNameIdpAliasData(A.That.IsEqualTo(_identityProviderId), _identity.UserId)) + A.CallTo(() => _userProvisioningService.GetCompanyNameIdpAliasData(A.That.IsEqualTo(_identityProviderId), _identity.IdentityId)) .Returns((_fixture.Build().With(x => x.IsSharedIdp, false).Create(), _fixture.Create())); - A.CallTo(() => _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identity.UserId, A._)) + A.CallTo(() => _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identity.IdentityId, A._)) .Returns((_fixture.Build().With(x => x.IsSharedIdp, true).Create(), _fixture.Create())); A.CallTo(() => _userProvisioningService.GetOwnCompanyPortalRoleDatas(A._, A>._, A._)) diff --git a/tests/administration/Administration.Service.Tests/Controllers/ConnectorsControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/ConnectorsControllerTests.cs index 13d6572341..573770a926 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/ConnectorsControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/ConnectorsControllerTests.cs @@ -42,8 +42,11 @@ public ConnectorsControllerTests() { _fixture = new Fixture(); _logic = A.Fake(); - this._controller = new ConnectorsController(_logic); - var identity = new IdentityData("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + _controller = new ConnectorsController(_logic); + var identity = A.Fake(); + A.CallTo(() => identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identity.CompanyId).Returns(Guid.NewGuid()); _controller.AddControllerContextWithClaimAndBearer(AccessToken, identity); } diff --git a/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs index 2429d18f09..06c4dba48b 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs @@ -23,6 +23,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; using System.Text; @@ -30,8 +31,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Contr public class DocumentsControllerTests { - private const string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IDocumentsBusinessLogic _logic; private readonly DocumentsController _controller; private readonly Fixture _fixture; @@ -39,9 +39,13 @@ public class DocumentsControllerTests public DocumentsControllerTests() { _fixture = new Fixture(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); - this._controller = new DocumentsController(_logic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _controller = new DocumentsController(_logic); + _controller.AddControllerContextWithClaim(_identity); } [Fact] diff --git a/tests/administration/Administration.Service.Tests/Controllers/RegistrationControllerTest.cs b/tests/administration/Administration.Service.Tests/Controllers/RegistrationControllerTest.cs index e0282ded78..7ea62b2636 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/RegistrationControllerTest.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/RegistrationControllerTest.cs @@ -27,6 +27,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.SdFactory.Library.Models; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; using System.Text; @@ -35,7 +36,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Contr public class RegistrationControllerTest { private static readonly string AccessToken = "THISISTHEACCESSTOKEN"; - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IRegistrationBusinessLogic _logic; private readonly RegistrationController _controller; private readonly IFixture _fixture; @@ -45,8 +46,12 @@ public RegistrationControllerTest() _fixture.Behaviors.OfType().ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); - this._controller = new RegistrationController(_logic); + _controller = new RegistrationController(_logic); _controller.AddControllerContextWithClaimAndBearer(AccessToken, _identity); } diff --git a/tests/administration/Administration.Service.Tests/Controllers/RegistrationStatusControllerTest.cs b/tests/administration/Administration.Service.Tests/Controllers/RegistrationStatusControllerTest.cs index 06c22f51d3..eed7a51957 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/RegistrationStatusControllerTest.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/RegistrationStatusControllerTest.cs @@ -35,7 +35,7 @@ public RegistrationStatusControllerTest() { _logic = A.Fake(); _controller = new RegistrationStatusController(_logic); - _controller.AddControllerContextWithClaim("1234"); + _controller.AddControllerContextWithClaim(); } [Fact] diff --git a/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs index 76f23126d3..d344382713 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs @@ -27,14 +27,14 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Controllers; public class ServiceAccountControllerTests { - private const string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly IServiceAccountBusinessLogic _logic; private readonly ServiceAccountController _controller; @@ -46,9 +46,13 @@ public ServiceAccountControllerTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); - this._controller = new ServiceAccountController(_logic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _controller = new ServiceAccountController(_logic); + _controller.AddControllerContextWithClaim(_identity); } [Fact] diff --git a/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs index 76a87ae60a..cdf183a32c 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs @@ -24,16 +24,16 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Controllers; public class SubscriptionConfigurationControllerTests { - private const string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; private static readonly Guid OfferSubscriptionId = new("4C1A6851-D4E7-4E10-A011-3732CD049999"); private static readonly Guid CompanyId = new("4C1A6851-D4E7-4E10-A011-3732CD049999"); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly ISubscriptionConfigurationBusinessLogic _logic; private readonly SubscriptionConfigurationController _controller; private readonly Fixture _fixture; @@ -41,9 +41,13 @@ public class SubscriptionConfigurationControllerTests public SubscriptionConfigurationControllerTests() { _fixture = new Fixture(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); _controller = new SubscriptionConfigurationController(_logic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _controller.AddControllerContextWithClaim(_identity); } [Fact] diff --git a/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs b/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs index 7d7cdc2146..f2d1501705 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs @@ -24,15 +24,15 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; +using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.Extensions; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Tests.Controllers; public class UserControllerTest { - private const string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; private static readonly Guid CompanyUserId = new("05455d3a-fc86-4f5a-a89a-ba964ead163d"); - private readonly IdentityData _identity = new(IamUserId, CompanyUserId, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IUserBusinessLogic _logic; private readonly IUserRolesBusinessLogic _rolesLogic; private readonly UserController _controller; @@ -41,11 +41,15 @@ public class UserControllerTest public UserControllerTest() { _fixture = new Fixture(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); _rolesLogic = A.Fake(); var uploadBusinessLogic = A.Fake(); - this._controller = new UserController(_logic, uploadBusinessLogic, _rolesLogic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _controller = new UserController(_logic, uploadBusinessLogic, _rolesLogic); + _controller.AddControllerContextWithClaim(_identity); } [Fact] diff --git a/tests/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogicTests.cs b/tests/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogicTests.cs index 3433b9f808..c54a749a4f 100644 --- a/tests/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogicTests.cs +++ b/tests/externalsystems/OfferProvider.Library/BusinessLogic/OfferProviderBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -249,13 +248,16 @@ public async Task TriggerProviderCallback_WithValidData_ReturnsExpected() // Arrange var technicalUserId = Guid.NewGuid(); var technicalUserClientId = "sa1"; + var technicalUserInternalClientId = Guid.NewGuid().ToString(); var serviceAccounts = new (Guid, string?)[] { new(technicalUserId, technicalUserClientId) }; A.CallTo(() => _offerSubscriptionRepository.GetTriggerProviderCallbackInformation(_subscriptionId)) .Returns((serviceAccounts, "cl1", "https://callback.com", OfferSubscriptionStatusId.ACTIVE)); - A.CallTo(() => _provisioningManager.GetCentralClientAuthDataAsync(technicalUserClientId)) + A.CallTo(() => _provisioningManager.GetIdOfCentralClientAsync(technicalUserClientId)) + .Returns(technicalUserInternalClientId); + A.CallTo(() => _provisioningManager.GetCentralClientAuthDataAsync(technicalUserInternalClientId)) .Returns(new ClientAuthData(IamClientAuthMethod.SECRET) { Secret = "test123" }); // Act diff --git a/tests/framework/Framework.ProcessIdentity.Tests/Framework.ProcessIdentity.Tests.csproj b/tests/framework/Framework.ProcessIdentity.Tests/Framework.ProcessIdentity.Tests.csproj new file mode 100644 index 0000000000..f9ac7114cc --- /dev/null +++ b/tests/framework/Framework.ProcessIdentity.Tests/Framework.ProcessIdentity.Tests.csproj @@ -0,0 +1,48 @@ + + + + + Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.Tests + Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.Tests + net7.0 + enable + enable + false + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + diff --git a/tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataBuilderTests.cs b/tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataBuilderTests.cs new file mode 100644 index 0000000000..97a630d090 --- /dev/null +++ b/tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataBuilderTests.cs @@ -0,0 +1,103 @@ +/******************************************************************************** + * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity.DependencyInjection; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; + +namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.Framework.ProcessIdentity.Tests; + +public class ProcessIdentityDataBuilderTests +{ + private readonly IFixture _fixture; + private readonly Guid _identityId = Guid.NewGuid(); + private readonly ProcessIdentityDataBuilder _sut; + + public ProcessIdentityDataBuilderTests() + { + _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); + _fixture.Behaviors.OfType().ToList() + .ForEach(b => _fixture.Behaviors.Remove(b)); + _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + + var settings = _fixture.Build().With(x => x.ProcessUserId, _identityId).Create(); + var options = Options.Create(settings); + + _sut = new ProcessIdentityDataBuilder(options); + } + + [Fact] + public void IdentityId_ReturnsExpected() + { + // Act + var result = _sut.IdentityId; + + // Assert + result.Should().Be(_identityId); + } + + [Fact] + public void AddIdentityData_ReturnsExpected() + { + // Arrange + var identityType = _fixture.Create(); + var companyId = Guid.NewGuid(); + + // Act + _sut.AddIdentityData(identityType, companyId); + var identityTypeResult = _sut.IdentityTypeId; + var companyIdResult = _sut.CompanyId; + + // Assert + identityTypeResult.Should().Be(identityType); + companyIdResult.Should().Be(companyId); + } + + [Fact] + public void IdentityTypeId_WithoutCallToAddIdentityData_Throws() + { + // Act + var error = Assert.Throws(() => _sut.IdentityTypeId); + + // Assert + error.Message.Should().Be("identityType should never be null here (GetIdentityData must be called before)"); + } + + [Fact] + public void CompanyId_WithoutCallToAddIdentityData_Throws() + { + // Act + var error = Assert.Throws(() => _sut.CompanyId); + + // Assert + error.Message.Should().Be("companyId should never be null here (GetIdentityData must be called before)"); + } + + [Fact] + public void IdentityType_WithoutGetIdentitDataCalled_Throws() + { + // Act + var error = Assert.Throws(() => _sut.IdentityTypeId); + + // Assert + error.Message.Should().Be("identityType should never be null here (GetIdentityData must be called before)"); + } +} diff --git a/tests/portalbackend/PortalBackend.DBAccess.Tests/Identities/IdentityServiceTests.cs b/tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataDeterminationTests.cs similarity index 58% rename from tests/portalbackend/PortalBackend.DBAccess.Tests/Identities/IdentityServiceTests.cs rename to tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataDeterminationTests.cs index 5c3c0dc1ee..eb280220b4 100644 --- a/tests/portalbackend/PortalBackend.DBAccess.Tests/Identities/IdentityServiceTests.cs +++ b/tests/framework/Framework.ProcessIdentity.Tests/ProcessIdentityDataDeterminationTests.cs @@ -18,90 +18,70 @@ ********************************************************************************/ using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Identities; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Tests.Identities; +namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.Framework.ProcessIdentity.Tests; -public class IdentityServiceTests +public class ProcessIdentityDataDeterminationTests { private readonly IFixture _fixture; - private readonly Guid _identityId = Guid.NewGuid(); - private readonly IIdentityRepository _identityRepository; - private readonly IdentityService _sut; + private readonly IProcessIdentityDataBuilder _processIdentityDataBuilder; + private readonly ProcessIdentityDataDetermination _sut; - public IdentityServiceTests() + public ProcessIdentityDataDeterminationTests() { _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); _fixture.Behaviors.OfType().ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - var identityIdDetermination = A.Fake(); - A.CallTo(() => identityIdDetermination.IdentityId).Returns(_identityId); + _identityRepository = A.Fake(); + _processIdentityDataBuilder = A.Fake(); var portalRepositories = A.Fake(); - _identityRepository = A.Fake(); A.CallTo(() => portalRepositories.GetInstance()).Returns(_identityRepository); - _sut = new IdentityService(portalRepositories, identityIdDetermination); + _sut = new ProcessIdentityDataDetermination(portalRepositories, _processIdentityDataBuilder); } [Fact] - public async Task IdentityData_ReturnsExpected() + public async Task GetIdentityData_ReturnsExpected() { // Arrange - var sub = _fixture.Create(); + var identityId = Guid.NewGuid(); var identityType = _fixture.Create(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(_identityId)) - .Returns(new IdentityData(sub, _identityId, identityType, companyId)); - await _sut.GetIdentityData().ConfigureAwait(false); + A.CallTo(() => _processIdentityDataBuilder.IdentityId).Returns(identityId); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(A._)) + .Returns(new ValueTuple(identityType, companyId)); // Act - var first = _sut.IdentityData; - var second = _sut.IdentityData; + await _sut.GetIdentityData().ConfigureAwait(false); // Assert - first.Should().NotBeNull() - .And.BeSameAs(second) - .And.Match(x => - x.UserEntityId == sub && - x.UserId == _identityId && - x.IdentityType == identityType && - x.CompanyId == companyId); - - A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(_identityId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(identityId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _processIdentityDataBuilder.AddIdentityData(identityType, companyId)).MustHaveHappenedOnceExactly(); } [Fact] public async Task GetIdentityData_WithNotExistingIdentityId_Throws() { // Arrange - A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(_identityId)) - .Returns((IdentityData?)null); + var identityId = Guid.NewGuid(); + A.CallTo(() => _processIdentityDataBuilder.IdentityId).Returns(identityId); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(A._)) + .Returns(default((IdentityTypeId, Guid))); // Act var error = await Assert.ThrowsAsync(async () => await _sut.GetIdentityData().ConfigureAwait(false)).ConfigureAwait(false); // Assert - error.Message.Should().Be($"Identity {_identityId} could not be found"); - } - - [Fact] - public async Task IdentityData_WithoutGetIdentitDataCalled_Throws() - { - // Arrange - A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(_identityId)) - .Returns((IdentityData?)null); - - // Act - var error = Assert.Throws(() => _sut.IdentityData); - - // Assert - error.Message.Should().Be("identityData should never be null here (endpoint must be annotated with an identity policy / as an alternative GetIdentityData should be used)"); + error.Message.Should().Be($"Identity {identityId} could not be found"); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByIdentityId(identityId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _processIdentityDataBuilder.AddIdentityData(A._, A._)).MustNotHaveHappened(); } } diff --git a/src/portalbackend/PortalBackend.DBAccess/Models/IdpUser.cs b/tests/framework/Framework.ProcessIdentity.Tests/Usings.cs similarity index 79% rename from src/portalbackend/PortalBackend.DBAccess/Models/IdpUser.cs rename to tests/framework/Framework.ProcessIdentity.Tests/Usings.cs index d6d5c4e14c..65016aec51 100644 --- a/src/portalbackend/PortalBackend.DBAccess/Models/IdpUser.cs +++ b/tests/framework/Framework.ProcessIdentity.Tests/Usings.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -18,10 +17,8 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -namespace Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; - -public class IdpUser -{ - public string? TargetIamUserId { get; set; } - public string? IdpName { get; set; } -} +global using AutoFixture; +global using AutoFixture.AutoFakeItEasy; +global using FakeItEasy; +global using FluentAssertions; +global using Xunit; diff --git a/tests/framework/Framework.PublicInfos.Tests/PublicInformationBusinessLogicTests.cs b/tests/framework/Framework.PublicInfos.Tests/PublicInformationBusinessLogicTests.cs index e33e22d816..fe6e804aff 100644 --- a/tests/framework/Framework.PublicInfos.Tests/PublicInformationBusinessLogicTests.cs +++ b/tests/framework/Framework.PublicInfos.Tests/PublicInformationBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -36,12 +35,17 @@ public class PublicInformationBusinessLogicTests { private readonly Guid _participantCompany = Guid.NewGuid(); private readonly Guid _appProviderCompany = Guid.NewGuid(); + private readonly IIdentityData _identity; private readonly IIdentityService _identityService; private readonly IPublicInformationBusinessLogic _sut; public PublicInformationBusinessLogicTests() { + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); var companyRepository = A.Fake(); var portalRepositories = A.Fake(); @@ -57,7 +61,7 @@ public PublicInformationBusinessLogicTests() public async Task GetPublicUrls_ForParticipant_ReturnsExpected() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(new IdentityData("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, _participantCompany)); + A.CallTo(() => _identity.CompanyId).Returns(_participantCompany); // Act var result = await _sut.GetPublicUrls().ConfigureAwait(false); @@ -70,7 +74,7 @@ public async Task GetPublicUrls_ForParticipant_ReturnsExpected() public async Task GetPublicUrls_ForAppProvider_ReturnsExpected() { // Arrange - A.CallTo(() => _identityService.IdentityData).Returns(new IdentityData("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, _appProviderCompany)); + A.CallTo(() => _identity.CompanyId).Returns(_appProviderCompany); // Act var result = await _sut.GetPublicUrls().ConfigureAwait(false); diff --git a/tests/framework/Framework.Web.Tests/ClaimsIdentityIdDeterminationTests.cs b/tests/framework/Framework.Web.Tests/ClaimsIdentityIdDeterminationTests.cs deleted file mode 100644 index 574486b95a..0000000000 --- a/tests/framework/Framework.Web.Tests/ClaimsIdentityIdDeterminationTests.cs +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************** - * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation - * - * See the NOTICE file(s) distributed with this work for additional - * information regarding copyright ownership. - * - * This program and the accompanying materials are made available under the - * terms of the Apache License, Version 2.0 which is available at - * https://www.apache.org/licenses/LICENSE-2.0. - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - * - * SPDX-License-Identifier: Apache-2.0 - ********************************************************************************/ - -using Microsoft.AspNetCore.Http; -using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; -using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using System.Security.Claims; - -namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web.Tests; - -public class ClaimsIdentityIdDeterminationTests -{ - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly HttpContext _httpContext; - private readonly ClaimsPrincipal _user; - - public ClaimsIdentityIdDeterminationTests() - { - var fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); - fixture.Behaviors.OfType().ToList() - .ForEach(b => fixture.Behaviors.Remove(b)); - fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - - _httpContextAccessor = A.Fake(); - _httpContext = A.Fake(); - _user = A.Fake(); - A.CallTo(() => _httpContextAccessor.HttpContext).Returns(_httpContext); - } - - [Fact] - public void IdentityData_ReturnsExpected() - { - // Arrange - var identityId = Guid.NewGuid(); - - var sut = CreateSut(identityId.ToString()); - - // Act - var first = sut.IdentityId; - var second = sut.IdentityId; - - // Assert - first.Should().NotBeEmpty() - .And.Be(second) - .And.Be(identityId); - - A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); - } - - [Fact] - public void IdentityData_EmptyIdentityId_Throws() - { - // Arrange - var sut = CreateSut(""); - - // Act - var error = Assert.Throws(() => sut.IdentityId); - - // Assert - error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/identity_id must not be null or empty (Parameter 'claims')"); - A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); - } - - [Fact] - public void IdentityData_NonGuidIdentityId_Throws() - { - // Arrange - var sut = CreateSut("deadbeef"); - - // Act - var error = Assert.Throws(() => sut.IdentityId); - - // Assert - error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/identity_id must contain a Guid (Parameter 'claims')"); - A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); - } - - private ClaimsIdentityIdDetermination CreateSut(string identityId) - { - var claims = new Claim[] { - new(PortalClaimTypes.IdentityId, identityId) - }; - - A.CallTo(() => _user.Claims).Returns(claims); - A.CallTo(() => _httpContext.User).Returns(_user); - - return new ClaimsIdentityIdDetermination(_httpContextAccessor); - } -} diff --git a/tests/framework/Framework.Web.Tests/MandatoryIdentityClaimHandlerTests.cs b/tests/framework/Framework.Web.Tests/MandatoryIdentityClaimHandlerTests.cs index 1f6630f902..3b9e270ff8 100644 --- a/tests/framework/Framework.Web.Tests/MandatoryIdentityClaimHandlerTests.cs +++ b/tests/framework/Framework.Web.Tests/MandatoryIdentityClaimHandlerTests.cs @@ -21,8 +21,9 @@ using Microsoft.Extensions.Logging; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; +using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using System.Security.Claims; @@ -31,10 +32,21 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web.Tests; public class MandatoryIdentityClaimHandlerTests { private readonly IFixture _fixture; - private readonly IIdentityService _identityService; + private readonly IClaimsIdentityDataBuilder _claimsIdentityDataBuilder; + private readonly IIdentityRepository _identityRepository; + private readonly IServiceAccountRepository _serviceAccountRepository; + private readonly IPortalRepositories _portalRepositories; private readonly IMockLogger _mockLogger; private readonly ILogger _logger; + private readonly Guid _companyUserId; + private readonly Guid _companyUserCompanyId; + private readonly Guid _serviceAccountId; + private readonly Guid _serviceAccountCompanyId; + private readonly string _clientId; + private readonly string _subject_company_user; + private readonly string _subject_service_account; + public MandatoryIdentityClaimHandlerTests() { _fixture = new Fixture().Customize(new AutoFakeItEasyCustomization { ConfigureMembers = true }); @@ -42,119 +54,99 @@ public MandatoryIdentityClaimHandlerTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - _identityService = A.Fake(); - _mockLogger = A.Fake>(); - _logger = new MockLogger(_mockLogger); - } + _claimsIdentityDataBuilder = new ClaimsIdentityDataBuilder(); + _identityRepository = A.Fake(); + _serviceAccountRepository = A.Fake(); + _portalRepositories = A.Fake(); - [Theory] - [InlineData(IdentityTypeId.COMPANY_USER, PolicyTypeId.CompanyUser)] - [InlineData(IdentityTypeId.COMPANY_SERVICE_ACCOUNT, PolicyTypeId.ServiceAccount)] - public async Task HandleRequirementAsync_WithValidIdentityType_ReturnsExpected(IdentityTypeId identityTypeId, PolicyTypeId policyTypeId) - { - // Arrange - var identity = _fixture.Build().With(x => x.IdentityType, identityTypeId).Create(); - var principal = _fixture.Create(); - A.CallTo(() => _identityService.GetIdentityData()).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(Guid.NewGuid()); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(policyTypeId), 1), principal, null); + _companyUserId = Guid.Parse("eceefebe-8f34-4d11-85ef-767786a95a92"); + _companyUserCompanyId = Guid.Parse("0d0de79b-c05d-4153-9c97-7331900880d2"); + _serviceAccountId = Guid.Parse("53472768-6cb5-41b0-9421-5c956e44e8c8"); + _serviceAccountCompanyId = Guid.Parse("a61092d7-1516-4ccf-b922-0308bbb087e3"); + _clientId = "valid_client"; + _subject_company_user = "valid_sub_company_user"; + _subject_service_account = "valid_sub_service_account"; - // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); + A.CallTo(() => _portalRepositories.GetInstance()).Returns(_identityRepository); + A.CallTo(() => _portalRepositories.GetInstance()).Returns(_serviceAccountRepository); - // Assert - ctx.HasSucceeded.Should().BeTrue(); - } + A.CallTo(() => _serviceAccountRepository.GetServiceAccountDataByClientId(A._)).Returns(default((Guid, Guid))); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByUserEntityId(A._)).Returns(default((Guid, IdentityTypeId, Guid))); + A.CallTo(() => _identityRepository.GetActiveCompanyIdByIdentityId(A._)).Returns(Guid.Empty); - [Theory] - [InlineData(IdentityTypeId.COMPANY_USER, PolicyTypeId.ServiceAccount)] - [InlineData(IdentityTypeId.COMPANY_SERVICE_ACCOUNT, PolicyTypeId.CompanyUser)] - public async Task HandleRequirementAsync_WithInvalidIdentityType_ReturnsExpected(IdentityTypeId identityTypeId, PolicyTypeId policyTypeId) - { - // Arrange - var identity = _fixture.Build().With(x => x.IdentityType, identityTypeId).Create(); - var principal = _fixture.Create(); - A.CallTo(() => _identityService.GetIdentityData()).Returns(identity); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(policyTypeId), 1), principal, null); + A.CallTo(() => _serviceAccountRepository.GetServiceAccountDataByClientId(_clientId)).Returns((_serviceAccountId, _serviceAccountCompanyId)); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByUserEntityId(_subject_company_user)).Returns((_companyUserId, IdentityTypeId.COMPANY_USER, _companyUserCompanyId)); + A.CallTo(() => _identityRepository.GetActiveIdentityDataByUserEntityId(_subject_service_account)).Returns((_serviceAccountId, IdentityTypeId.COMPANY_SERVICE_ACCOUNT, _serviceAccountCompanyId)); + A.CallTo(() => _identityRepository.GetActiveCompanyIdByIdentityId(_companyUserId)).Returns(_companyUserCompanyId); - // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); - - // Assert - ctx.HasSucceeded.Should().BeFalse(); + _mockLogger = A.Fake>(); + _logger = new MockLogger(_mockLogger); } [Theory] - [InlineData(PolicyTypeId.ValidCompany)] - [InlineData(PolicyTypeId.ValidIdentity)] - public async Task HandleRequirementAsync_WithValid_ReturnsExpected(PolicyTypeId policyTypeId) + [InlineData("preferred_username", "eceefebe-8f34-4d11-85ef-767786a95a92", PolicyTypeId.ValidIdentity, IClaimsIdentityDataBuilderStatus.Initialized, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "00000000-0000-0000-0000-000000000000")] + [InlineData("preferred_username", "eceefebe-8f34-4d11-85ef-767786a95a92", PolicyTypeId.CompanyUser, IClaimsIdentityDataBuilderStatus.Initialized, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "00000000-0000-0000-0000-000000000000")] + [InlineData("preferred_username", "eceefebe-8f34-4d11-85ef-767786a95a92", PolicyTypeId.ServiceAccount, IClaimsIdentityDataBuilderStatus.Initialized, false, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "00000000-0000-0000-0000-000000000000")] + [InlineData("preferred_username", "eceefebe-8f34-4d11-85ef-767786a95a92", PolicyTypeId.ValidCompany, IClaimsIdentityDataBuilderStatus.Complete, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "0d0de79b-c05d-4153-9c97-7331900880d2")] + [InlineData("clientId", "valid_client", PolicyTypeId.ValidIdentity, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("clientId", "valid_client", PolicyTypeId.CompanyUser, IClaimsIdentityDataBuilderStatus.Complete, false, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("clientId", "valid_client", PolicyTypeId.ServiceAccount, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("clientId", "valid_client", PolicyTypeId.ValidCompany, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("sub", "valid_sub_company_user", PolicyTypeId.ValidIdentity, IClaimsIdentityDataBuilderStatus.Complete, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "0d0de79b-c05d-4153-9c97-7331900880d2")] + [InlineData("sub", "valid_sub_company_user", PolicyTypeId.CompanyUser, IClaimsIdentityDataBuilderStatus.Complete, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "0d0de79b-c05d-4153-9c97-7331900880d2")] + [InlineData("sub", "valid_sub_company_user", PolicyTypeId.ServiceAccount, IClaimsIdentityDataBuilderStatus.Complete, false, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "0d0de79b-c05d-4153-9c97-7331900880d2")] + [InlineData("sub", "valid_sub_company_user", PolicyTypeId.ValidCompany, IClaimsIdentityDataBuilderStatus.Complete, true, "eceefebe-8f34-4d11-85ef-767786a95a92", IdentityTypeId.COMPANY_USER, "0d0de79b-c05d-4153-9c97-7331900880d2")] + [InlineData("sub", "valid_sub_service_account", PolicyTypeId.ValidIdentity, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("sub", "valid_sub_service_account", PolicyTypeId.CompanyUser, IClaimsIdentityDataBuilderStatus.Complete, false, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("sub", "valid_sub_service_account", PolicyTypeId.ServiceAccount, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData("sub", "valid_sub_service_account", PolicyTypeId.ValidCompany, IClaimsIdentityDataBuilderStatus.Complete, true, "53472768-6cb5-41b0-9421-5c956e44e8c8", IdentityTypeId.COMPANY_SERVICE_ACCOUNT, "a61092d7-1516-4ccf-b922-0308bbb087e3")] + [InlineData(null, null, PolicyTypeId.ValidIdentity, IClaimsIdentityDataBuilderStatus.Empty, false, "00000000-0000-0000-0000-000000000000", default(IdentityTypeId), "00000000-0000-0000-0000-000000000000")] + [InlineData(null, null, PolicyTypeId.CompanyUser, IClaimsIdentityDataBuilderStatus.Empty, false, "00000000-0000-0000-0000-000000000000", default(IdentityTypeId), "00000000-0000-0000-0000-000000000000")] + [InlineData(null, null, PolicyTypeId.ServiceAccount, IClaimsIdentityDataBuilderStatus.Empty, false, "00000000-0000-0000-0000-000000000000", default(IdentityTypeId), "00000000-0000-0000-0000-000000000000")] + [InlineData(null, null, PolicyTypeId.ValidCompany, IClaimsIdentityDataBuilderStatus.Empty, false, "00000000-0000-0000-0000-000000000000", default(IdentityTypeId), "00000000-0000-0000-0000-000000000000")] + public async Task HandleValidRequirement_ReturnsExpected(string? claim, string? value, PolicyTypeId policyType, IClaimsIdentityDataBuilderStatus status, bool success, Guid identityId, IdentityTypeId identityTypeId, Guid companyId) { // Arrange - var identity = _fixture.Build().With(x => x.CompanyId, Guid.NewGuid).Create(); - var principal = _fixture.Create(); - A.CallTo(() => _identityService.GetIdentityData()).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(Guid.NewGuid()); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(policyTypeId), 1), principal, null); + var principal = new ClaimsPrincipal( + claim == null || value == null + ? Enumerable.Empty() + : new[] { new ClaimsIdentity(new[] { new Claim(claim, value) }) }); - // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); - - // Assert - ctx.HasSucceeded.Should().BeTrue(); - } - - [Fact] - public async Task HandleRequirementAsync_WithInvalidCompany_ReturnsExpected() - { - // Arrange - var identity = _fixture.Build().With(x => x.CompanyId, Guid.Empty).Create(); - var principal = _fixture.Create(); - A.CallTo(() => _identityService.GetIdentityData()).Returns(identity); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(PolicyTypeId.ValidCompany), 1), principal, null); - - // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); - - // Assert - ctx.HasSucceeded.Should().BeFalse(); - } - - [Fact] - public async Task HandleRequirementAsync_WithInvalidIdentity_ReturnsExpected() - { - // Arrange - var principal = _fixture.Create(); - A.CallTo(() => _identityService.IdentityId).Returns(Guid.Empty); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(PolicyTypeId.ValidIdentity), 1), principal, null); - - // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); - - // Assert - ctx.HasSucceeded.Should().BeFalse(); - } - - [Fact] - public async Task HandleRequirementAsync_WithFailingIdentityService_LogsException() - { - // Arrange - var principal = _fixture.Create(); - var identityId = Guid.NewGuid(); - var exception = new ConflictException($"Identity {identityId} could not be found"); - A.CallTo(() => _identityService.GetIdentityData()).Throws(exception); - var sut = new MandatoryIdentityClaimHandler(_identityService, _logger); - var ctx = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(PolicyTypeId.ValidCompany), 1), principal, null); + var context = new AuthorizationHandlerContext(Enumerable.Repeat(new MandatoryIdentityClaimRequirement(policyType), 1), principal, null); + var sut = new MandatoryIdentityClaimHandler(_claimsIdentityDataBuilder, _portalRepositories, _logger); // Act - await sut.HandleAsync(ctx).ConfigureAwait(false); + await sut.HandleAsync(context).ConfigureAwait(false); // Assert - ctx.HasFailed.Should().BeTrue(); - A.CallTo(() => _mockLogger.Log(LogLevel.Information, exception, "unable to retrieve IdentityData: {Exception}")).MustNotHaveHappened(); + context.HasSucceeded.Should().Be(success); + _claimsIdentityDataBuilder.Status.Should().Be(status); + + if (identityId == Guid.Empty) + { + Assert.Throws(() => _claimsIdentityDataBuilder.IdentityId); + } + else + { + _claimsIdentityDataBuilder.IdentityId.Should().Be(identityId); + } + + if (identityTypeId == default) + { + Assert.Throws(() => _claimsIdentityDataBuilder.IdentityTypeId); + } + else + { + _claimsIdentityDataBuilder.IdentityTypeId.Should().Be(identityTypeId); + } + + if (companyId == Guid.Empty) + { + Assert.Throws(() => _claimsIdentityDataBuilder.CompanyId); + } + else + { + _claimsIdentityDataBuilder.CompanyId.Should().Be(companyId); + } } } diff --git a/tests/keycloak/Keycloak.Authentication.Tests/KeycloakClaimsTransformationTests.cs b/tests/keycloak/Keycloak.Authentication.Tests/KeycloakClaimsTransformationTests.cs index d70699af24..4adbdc8faa 100644 --- a/tests/keycloak/Keycloak.Authentication.Tests/KeycloakClaimsTransformationTests.cs +++ b/tests/keycloak/Keycloak.Authentication.Tests/KeycloakClaimsTransformationTests.cs @@ -18,22 +18,15 @@ ********************************************************************************/ using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; -using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using System.Security.Claims; namespace Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication.Tests; public class KeycloakClaimsTransformationTests { - private readonly KeycloakClaimsTransformation _sut; - private readonly IIdentityRepository _identityRepository; private readonly IFixture _fixture; - private readonly IMockLogger _mockLogger; public KeycloakClaimsTransformationTests() { @@ -41,88 +34,73 @@ public KeycloakClaimsTransformationTests() _fixture.Behaviors.OfType().ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - - var portalRepositories = A.Fake(); - _identityRepository = A.Fake(); - A.CallTo(() => portalRepositories.GetInstance()).Returns(_identityRepository); - - _mockLogger = A.Fake>(); - ILogger logger = new MockLogger(_mockLogger); - _sut = new KeycloakClaimsTransformation(Options.Create(new JwtBearerOptions()), portalRepositories, logger); - } - - [Fact] - public async Task TransformAsync_WithValid_ReturnsExpected() - { - // Arrange - var identityId = Guid.NewGuid(); - var identity = new ClaimsIdentity(Enumerable.Repeat(new Claim(PortalClaimTypes.PreferredUserName, identityId.ToString()), 1)); - var principal = new ClaimsPrincipal(identity); - - // Act - var result = await _sut.TransformAsync(principal).ConfigureAwait(false); - - // Assert - result.Identities.Should().Contain(x => x.Claims.Any(x => x.Type == PortalClaimTypes.IdentityId)); } [Fact] - public async Task TransformAsync_WithoutIdentityIdWithValidUserEntityId_ReturnsExpected() + public async Task TransformAsync_RurnsExpected() { // Arrange - var identityId = Guid.NewGuid(); - var userId = Guid.NewGuid().ToString(); - A.CallTo(() => _identityRepository.GetIdentityIdByUserEntityId(userId)) - .Returns(identityId); - var identity = new ClaimsIdentity(Enumerable.Repeat(new Claim(PortalClaimTypes.Sub, userId), 1)); + var resource_access = + """ + { + "client1": { + "roles": [ + "client1_role1", + "client1_role2" + ] + }, + "client2": { + "roles": [ + "client2_role1", + "client2_role2" + ] + }, + "client3": { + "roles": [ + "client3_role1", + "client3_role2" + ] + } + } + """; + + var identity = new ClaimsIdentity(new[] { new Claim(PortalClaimTypes.ResourceAccess, resource_access, "JSON") }); var principal = new ClaimsPrincipal(identity); - // Act - var result = await _sut.TransformAsync(principal).ConfigureAwait(false); - - // Assert - A.CallTo(() => _mockLogger.Log(LogLevel.Information, A._, $"Preferred user name (null) couldn't be parsed to uuid for userEntityId {userId}")).MustHaveHappenedOnceExactly(); - result.Identities.Should().Contain(x => x.Claims.Any(x => x.Type == PortalClaimTypes.IdentityId)); - } - - [Fact] - public async Task TransformAsync_WithoutInvalidIdentityIdWithValidUserEntityId_ReturnsExpected() - { - // Arrange - var identityId = Guid.NewGuid(); - var userId = Guid.NewGuid().ToString(); - A.CallTo(() => _identityRepository.GetIdentityIdByUserEntityId(userId)) - .Returns(identityId); - var identity = new ClaimsIdentity(new[] + var options = Options.Create(new JwtBearerOptions() { - new Claim(PortalClaimTypes.PreferredUserName, $"user.{identityId}"), - new Claim(PortalClaimTypes.Sub, userId) + TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() + { + ValidAudience = "client2" + } }); - var principal = new ClaimsPrincipal(identity); - - // Act - var result = await _sut.TransformAsync(principal).ConfigureAwait(false); - // Assert - A.CallTo(() => _mockLogger.Log(LogLevel.Information, A._, $"Preferred user name user.{identityId} couldn't be parsed to uuid for userEntityId {userId}")).MustHaveHappenedOnceExactly(); - result.Identities.Should().Contain(x => x.Claims.Any(x => x.Type == PortalClaimTypes.IdentityId)); - } - - [Fact] - public async Task TransformAsync_WithoutIdentityIdAndUserEntityId_ReturnsExpected() - { - // Arrange - var userId = Guid.NewGuid().ToString(); - A.CallTo(() => _identityRepository.GetIdentityIdByUserEntityId(userId)) - .Returns(Guid.Empty); - var identity = new ClaimsIdentity(Enumerable.Repeat(new Claim(PortalClaimTypes.Sub, userId), 1)); - var principal = new ClaimsPrincipal(identity); + var sut = new KeycloakClaimsTransformation(options); // Act - var result = await _sut.TransformAsync(principal).ConfigureAwait(false); + var result = await sut.TransformAsync(principal).ConfigureAwait(false); // Assert - A.CallTo(() => _mockLogger.Log(LogLevel.Information, A._, $"Preferred user name (null) couldn't be parsed to uuid for userEntityId {userId}")).MustHaveHappenedOnceExactly(); - result.Identities.Should().NotContain(x => x.Claims.Any(x => x.Type == PortalClaimTypes.IdentityId)); + result.Identities.Should().Contain(x => + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client2_role1") && + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client2_role2")); + + result.Identities.Should().NotContain(x => + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client1_role1") || + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client1_role2") || + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client3_role1") || + x.Claims.Any(x => + x.Type == ClaimTypes.Role && + x.Value == "client3_role2")); } } diff --git a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppBusinessLogicTests.cs b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppBusinessLogicTests.cs index 17ba2c4c4d..4782111fa5 100644 --- a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppBusinessLogicTests.cs +++ b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppBusinessLogicTests.cs @@ -42,8 +42,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.BusinessLogic.Tests; public class AppBusinessLogicTests { - private const string IamUserId = "3e8343f7-4fe5-4296-8312-f33aa6dbde5d"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; + private static readonly Guid CompanyUserId = Guid.NewGuid(); + private static readonly Guid CompanyId = Guid.NewGuid(); private readonly IFixture _fixture; private readonly IPortalRepositories _portalRepositories; @@ -65,11 +66,14 @@ public AppBusinessLogicTests() _portalRepositories = A.Fake(); _offerRepository = A.Fake(); _offerSubscriptionRepository = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); _offerSetupService = A.Fake(); _logger = A.Fake>(); + A.CallTo(() => _identity.IdentityId).Returns(CompanyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(CompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerSubscriptionRepository); @@ -89,7 +93,7 @@ public async Task AddFavouriteAppForUser_ExecutesSuccessfully() await sut.AddFavouriteAppForUserAsync(appId); // Assert - A.CallTo(() => _offerRepository.CreateAppFavourite(A.That.Matches(x => x == appId), A.That.Matches(x => x == _identity.UserId))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerRepository.CreateAppFavourite(appId, CompanyUserId)).MustHaveHappenedOnceExactly(); A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); } @@ -304,7 +308,7 @@ public async Task GetCompanyProvidedAppSubscriptionStatusesForUserAsync_ReturnsE x => x.OfferId == data[3].OfferId && x.OfferName == data[3].ServiceName && x.CompanySubscriptionStatuses.Count() == data[3].CompanySubscriptionStatuses.Count() && x.Image == data[3].Image, x => x.OfferId == data[4].OfferId && x.OfferName == data[4].ServiceName && x.CompanySubscriptionStatuses.Count() == data[4].CompanySubscriptionStatuses.Count() && x.Image == data[4].Image ); - A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identity.CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) + A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) .MustHaveHappenedOnceExactly(); } @@ -337,7 +341,7 @@ public async Task GetCompanyProvidedAppSubscriptionStatusesForUserAsync_EmptyIma x => x.OfferId == data[0].OfferId && x.OfferName == data[0].ServiceName && x.CompanySubscriptionStatuses.Count() == data[0].CompanySubscriptionStatuses.Count() && x.Image == null, x => x.OfferId == data[1].OfferId && x.OfferName == data[1].ServiceName && x.CompanySubscriptionStatuses.Count() == data[1].CompanySubscriptionStatuses.Count() && x.Image == data[1].Image ); - A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identity.CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) + A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) .MustHaveHappenedOnceExactly(); } @@ -367,7 +371,7 @@ public async Task GetCompanyProvidedAppSubscriptionStatusesForUserAsync_QueryNul // Assert result.Meta.NumberOfElements.Should().Be(0); result.Content.Should().BeEmpty(); - A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(_identity.CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) + A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyProvidedOfferSubscriptionStatusesUntrackedAsync(CompanyId, OfferTypeId.APP, default, A>.That.IsSameSequenceAs(new[] { OfferSubscriptionStatusId.PENDING, OfferSubscriptionStatusId.ACTIVE, OfferSubscriptionStatusId.INACTIVE }), offerId)) .MustHaveHappenedOnceExactly(); } @@ -462,7 +466,7 @@ public async Task GetCompanyProvidedAppsDataForUserAsync_ReturnsExpectedCount(Ap // Assert A.CallTo(() => _offerRepository.GetProvidedOffersData(A> - .That.IsSameSequenceAs(offerStatusIds), OfferTypeId.APP, _identity.CompanyId, sorting, name)).MustHaveHappenedOnceExactly(); + .That.IsSameSequenceAs(offerStatusIds), OfferTypeId.APP, CompanyId, sorting, name)).MustHaveHappenedOnceExactly(); result.Content.Should().HaveCount(3) .And.ContainInOrder(serviceDetailData.Skip(6).Take(3)); } @@ -475,9 +479,8 @@ public async Task GetCompanyProvidedAppsDataForUserAsync_ReturnsExpectedCount(Ap public async Task GetCompanySubscribedAppSubscriptionStatusesForUserAsync_ReturnsExpected() { // Arrange - var identity = _fixture.Create(); var data = _fixture.CreateMany(5).ToImmutableArray(); - var pagination = new Pagination.Response(new Pagination.Metadata(data.Count(), 1, 0, data.Count()), data); + var pagination = new Pagination.Response(new Pagination.Metadata(data.Length, 1, 0, data.Length), data); A.CallTo(() => _offerService.GetCompanySubscribedOfferSubscriptionStatusesForUserAsync(A._, A._, A._, A._)) .Returns(pagination); @@ -595,7 +598,7 @@ public async Task GetAppDetailsByIdAsync_ReturnsExpected() var result = await sut.GetAppDetailsByIdAsync(appId, language).ConfigureAwait(false); // Assert - A.CallTo(() => _offerRepository.GetOfferDetailsByIdAsync(appId, _identity.CompanyId, language, Constants.DefaultLanguage, OfferTypeId.APP)) + A.CallTo(() => _offerRepository.GetOfferDetailsByIdAsync(appId, CompanyId, language, Constants.DefaultLanguage, OfferTypeId.APP)) .MustHaveHappenedOnceExactly(); result.Id.Should().Be(data.Id); @@ -653,7 +656,7 @@ public async Task GetAppDetailsByIdAsync_WithNullProperties_ReturnsExpected() var result = await sut.GetAppDetailsByIdAsync(appId, null).ConfigureAwait(false); // Assert - A.CallTo(() => _offerRepository.GetOfferDetailsByIdAsync(appId, _identity.CompanyId, null, Constants.DefaultLanguage, OfferTypeId.APP)) + A.CallTo(() => _offerRepository.GetOfferDetailsByIdAsync(appId, CompanyId, null, Constants.DefaultLanguage, OfferTypeId.APP)) .MustHaveHappenedOnceExactly(); result.Title.Should().Be(Constants.ErrorString); @@ -671,9 +674,7 @@ public async Task GetAppDetailsByIdAsync_WithNullProperties_ReturnsExpected() public async Task GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsync_ReturnsExpected() { // Arrange - var identity = _fixture.Create(); var data = _fixture.CreateMany(5).ToAsyncEnumerable(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyActiveSubscribedOfferSubscriptionStatusesUntrackedAsync(A._, A._, A._)) .Returns(data); @@ -684,7 +685,7 @@ public async Task GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsy // Assert result.Should().HaveCount(5); - A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyActiveSubscribedOfferSubscriptionStatusesUntrackedAsync(identity.CompanyId, OfferTypeId.APP, DocumentTypeId.APP_LEADIMAGE)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanyActiveSubscribedOfferSubscriptionStatusesUntrackedAsync(CompanyId, OfferTypeId.APP, DocumentTypeId.APP_LEADIMAGE)).MustHaveHappenedOnceExactly(); } #endregion @@ -695,9 +696,7 @@ public async Task GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsy public async Task GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync_ReturnsExpected() { // Arrange - var identity = _fixture.Create(); var data = _fixture.CreateMany(5).ToAsyncEnumerable(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanySubscribedOfferSubscriptionUntrackedAsync(A._, A._)) .Returns(data); @@ -708,7 +707,7 @@ public async Task GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync_Re // Assert result.Should().HaveCount(5); - A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanySubscribedOfferSubscriptionUntrackedAsync(identity.CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerSubscriptionRepository.GetOwnCompanySubscribedOfferSubscriptionUntrackedAsync(CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); } #endregion diff --git a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs index 8a414ab61a..93a342e726 100644 --- a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs +++ b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -49,9 +48,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.BusinessLogic.Tests; public class AppChangeBusinessLogicTest { private const string ClientId = "catenax-portal"; - private const string IamUserId = "7469aa7e-517e-4204-9cf0-f5ccf69130e9"; private static readonly Guid CompanyUserId = Guid.NewGuid(); - private readonly IdentityData _identity = new(IamUserId, CompanyUserId, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private static readonly Guid CompanyId = Guid.NewGuid(); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly IProvisioningManager _provisioningManager; @@ -88,6 +87,10 @@ public AppChangeBusinessLogicTest() _identityService = A.Fake(); _offerDocumentService = A.Fake(); _dateTimeProvider = A.Fake(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(CompanyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(CompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _now = _fixture.Create(); A.CallTo(() => _dateTimeProvider.OffsetNow).Returns(_now); @@ -131,7 +134,6 @@ public AppChangeBusinessLogicTest() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerSubscriptionsRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRolesRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_documentRepository); - A.CallTo(() => _identityService.IdentityData).Returns(_identity); _sut = new AppChangeBusinessLogic(_portalRepositories, _notificationService, _provisioningManager, _offerService, _identityService, Options.Create(settings), _offerDocumentService, _dateTimeProvider); } @@ -557,8 +559,6 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsUnsupportedM { // Arrange var appId = _fixture.Create(); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); var appLeadImageContentTypes = new[] { MediaTypeId.JPEG, MediaTypeId.PNG }; var file = FormFileHelper.GetFormFile("Test File", "TestImage.pdf", "application/pdf"); @@ -575,12 +575,10 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsConflictExce { // Arrange var appId = _fixture.Create(); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); var file = FormFileHelper.GetFormFile("Test Image", "TestImage.jpeg", "image/jpeg"); - A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => (false, true, null!)); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(A._, A._, A._)) + .Returns((false, true, Enumerable.Empty())); // Act var Act = () => _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); @@ -588,6 +586,7 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsConflictExce // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); result.Message.Should().Be("offerStatus is in incorrect State"); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); } [Fact] @@ -595,19 +594,18 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsForbiddenExc { // Arrange var appId = _fixture.Create(); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); var file = FormFileHelper.GetFormFile("Test Image", "TestImage.jpeg", "image/jpeg"); - A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => (true, false, null!)); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(A._, A._, A._)) + .Returns((true, false, Enumerable.Empty())); // Act async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - result.Message.Should().Be($"Company {identity.CompanyId} is not the provider company of App {appId}"); + result.Message.Should().Be($"Company {CompanyId} is not the provider company of App {appId}"); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); } [Fact] @@ -615,12 +613,10 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsNotFoundExce { // Arrange var appId = _fixture.Create(); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); var file = FormFileHelper.GetFormFile("Test Image", "TestImage.jpeg", "image/jpeg"); - A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>()); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(A._, A._, A._)) + .Returns(default((bool, bool, IEnumerable))); // Act async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); @@ -628,6 +624,7 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ThrowsNotFoundExce // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); result.Message.Should().Be($"App {appId} does not exist."); + A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); } #endregion diff --git a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs index 9ac52fa9b6..a2d790c5aa 100644 --- a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs +++ b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -44,8 +43,6 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.BusinessLogic.Tests; public class AppReleaseBusinessLogicTest { - private const string IamUserId = "3e8343f7-4fe5-4296-8312-f33aa6dbde5d"; - private readonly IFixture _fixture; private readonly IPortalRepositories _portalRepositories; private readonly IOfferRepository _offerRepository; @@ -53,7 +50,8 @@ public class AppReleaseBusinessLogicTest private readonly IDocumentRepository _documentRepository; private readonly IOptions _options; private readonly CompanyUser _companyUser; - private readonly IdentityData _identity; + private readonly Guid _companyId = Guid.NewGuid(); + private readonly IIdentityData _identity; private readonly IOfferService _offerService; private readonly Guid _notExistingAppId = Guid.NewGuid(); private readonly Guid _activeAppId = Guid.NewGuid(); @@ -87,17 +85,16 @@ public AppReleaseBusinessLogicTest() _offerSetupService = A.Fake(); _options = A.Fake>(); - var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, Guid.NewGuid(), UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER) - { - UserEntityId = IamUserId - }; + var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, Guid.NewGuid(), UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER); _companyUser = _fixture.Build() .With(u => u.Identity, identity) .Create(); - _identity = new(IamUserId, _companyUser.Id, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); - + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(_companyUser.Id); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(_companyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _settings = new AppsSettings @@ -146,7 +143,7 @@ public async Task CreateServiceOffering_WithValidDataAndEmptyDescriptions_Return var appId = _fixture.Create(); var appUserRoles = _fixture.CreateMany(3).Select(role => new AppUserRole(role, _fixture.CreateMany(2).ToImmutableArray())).ToImmutableArray(); - A.CallTo(() => _offerRepository.IsProviderCompanyUserAsync(A.That.IsEqualTo(appId), A.That.IsEqualTo(_identity.CompanyId), A.That.IsEqualTo(OfferTypeId.APP))) + A.CallTo(() => _offerRepository.IsProviderCompanyUserAsync(appId, _identity.CompanyId, OfferTypeId.APP)) .Returns((true, true)); IEnumerable? userRoles = null; @@ -862,7 +859,7 @@ public async Task SetInstanceType_WithNotExistingApp_NotFoundException() var appId = Guid.NewGuid(); var data = new AppInstanceSetupData(true, "https://test.de"); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>()); + .Returns(default((OfferStatusId, bool, AppInstanceSetupTransferData?, IEnumerable<(Guid, Guid, string)>))); //Act async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); @@ -879,7 +876,7 @@ public async Task SetInstanceType_WithInvalidUser_ThrowsForbiddenException() var appId = Guid.NewGuid(); var data = new AppInstanceSetupData(true, "https://test.de"); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.ACTIVE, false, null, new List<(Guid, Guid, string)>())); + .Returns((OfferStatusId.ACTIVE, false, null, Enumerable.Empty<(Guid, Guid, string)>())); //Act async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); @@ -896,7 +893,7 @@ public async Task SetInstanceType_WithWrongOfferState_ThrowsConflictException() var appId = Guid.NewGuid(); var data = new AppInstanceSetupData(true, "https://test.de"); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.ACTIVE, true, null, new List<(Guid, Guid, string)>())); + .Returns((OfferStatusId.ACTIVE, true, null, Enumerable.Empty<(Guid, Guid, string)>())); //Act async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); @@ -915,7 +912,7 @@ public async Task SetInstanceType_FromSingleToMultiWithoutAppInstance_ThrowsConf var data = new AppInstanceSetupData(false, null); var instanceSetupTransferData = new AppInstanceSetupTransferData(instanceSetupId, true, null); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, new List<(Guid, Guid, string)>())); + .Returns((OfferStatusId.CREATED, true, instanceSetupTransferData, Enumerable.Empty<(Guid, Guid, string)>())); //Act async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); @@ -935,7 +932,7 @@ public async Task SetInstanceType_WithNewEntry_CreatesEntry() var data = new AppInstanceSetupData(true, "https://test.de"); AppInstanceSetup? instanceSetupData = null; A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, null, new List<(Guid, Guid, string)>())); + .Returns((OfferStatusId.CREATED, true, null, Enumerable.Empty<(Guid, Guid, string)>())); A.CallTo(() => _offerRepository.CreateAppInstanceSetup(appId, A>._)) .Invokes((Guid callingAppId, Action setOptionalParameters) => { @@ -969,7 +966,7 @@ public async Task SetInstanceType_WithUrlUpdate_CreatesEntry() var instanceSetupTransferData = new AppInstanceSetupTransferData(instanceSetupId, true, "https://test.de"); var instanceSetupData = new AppInstanceSetup(instanceSetupId, appId) { IsSingleInstance = true }; A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); + .Returns((OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); A.CallTo(() => _offerRepository.AttachAndModifyAppInstanceSetup(instanceSetupId, appId, A>._, A>._)) .Invokes((Guid _, Guid _, Action setOptionalParameters, Action? initializeParameter) => @@ -998,7 +995,7 @@ public async Task SetInstanceType_WithExistingEntryButNoAppInstance_ThrowsConfli var instanceSetupTransferData = new AppInstanceSetupTransferData(instanceSetupId, false, null); var instanceSetupData = new AppInstanceSetup(instanceSetupId, appId) { IsSingleInstance = false }; A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, new List<(Guid, Guid, string)>())); + .Returns((OfferStatusId.CREATED, true, instanceSetupTransferData, Enumerable.Empty<(Guid, Guid, string)>())); A.CallTo(() => _offerRepository.AttachAndModifyAppInstanceSetup(instanceSetupId, appId, A>._, A>._)) .Invokes((Guid _, Guid _, Action setOptionalParameters, Action? initializeParameter) => @@ -1031,7 +1028,7 @@ public async Task SetInstanceType_WithExistingEntry_UpdatesEntry() var data = new AppInstanceSetupData(true, "https://test.de"); var instanceSetupTransferData = new AppInstanceSetupTransferData(instanceSetupId, false, null); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); + .Returns((OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); A.CallTo(() => _offerRepository.AttachAndModifyAppInstanceSetup(instanceSetupId, appId, A>._, A>._)) .Invokes((Guid _, Guid _, Action setOptionalParameters, Action? initializeParameter) => @@ -1064,7 +1061,7 @@ public async Task SetInstanceType_FromSingleToMulti_UpdatesEntry() var data = new AppInstanceSetupData(false, null); var instanceSetupTransferData = new AppInstanceSetupTransferData(instanceSetupId, true, null); A.CallTo(() => _offerRepository.GetOfferWithSetupDataById(appId, _identity.CompanyId, OfferTypeId.APP)) - .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); + .Returns((OfferStatusId.CREATED, true, instanceSetupTransferData, appInstanceData)); A.CallTo(() => _offerRepository.AttachAndModifyAppInstanceSetup(instanceSetupId, appId, A>._, A>._)) .Invokes((Guid _, Guid _, Action setOptionalParameters, Action? initializeParameter) => @@ -1096,7 +1093,7 @@ public async Task GetInReviewAppDetailsByIdAsync_ReturnsExpected() var appId = _fixture.Create(); A.CallTo(() => _offerRepository.GetInReviewAppDataByIdAsync(appId, OfferTypeId.APP)) - .ReturnsLazily(() => data); + .Returns(data); // Act var result = await _sut.GetInReviewAppDetailsByIdAsync(appId).ConfigureAwait(false); @@ -1121,7 +1118,7 @@ public async Task GetInReviewAppDetailsByIdAsync_ThrowsNotFoundException() var appId = _fixture.Create(); A.CallTo(() => _offerRepository.GetInReviewAppDataByIdAsync(appId, OfferTypeId.APP)) - .ReturnsLazily(() => (InReviewOfferData?)default!); + .Returns(default(InReviewOfferData?)); //Act async Task Act() => await _sut.GetInReviewAppDetailsByIdAsync(appId).ConfigureAwait(false); diff --git a/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs b/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs index a8ed1dab5a..5d3ad8620e 100644 --- a/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs +++ b/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -36,8 +35,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.Controllers.Tests; public class AppChangeControllerTest { - private const string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly AppChangeController _controller; private readonly IAppChangeBusinessLogic _logic; @@ -46,8 +44,12 @@ public AppChangeControllerTest() { _fixture = new Fixture(); _logic = A.Fake(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _controller = new AppChangeController(_logic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _controller.AddControllerContextWithClaim(_identity); } [Fact] diff --git a/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs b/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs index 37f578a039..2d906961e5 100644 --- a/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs +++ b/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -37,8 +36,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.Controllers.Tests; public class AppReleaseProcessControllerTest { - private static readonly string IamUserId = "4C1A6851-D4E7-4E10-A011-3732CD045E8A"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly AppReleaseProcessController _controller; private readonly IAppReleaseBusinessLogic _logic; @@ -47,8 +45,12 @@ public AppReleaseProcessControllerTest() { _fixture = new Fixture(); _logic = A.Fake(); - this._controller = new AppReleaseProcessController(_logic); - _controller.AddControllerContextWithClaim(IamUserId, _identity); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); + _controller = new AppReleaseProcessController(_logic); + _controller.AddControllerContextWithClaim(_identity); } [Fact] @@ -60,7 +62,7 @@ public async Task UpdateAppDocument_ReturnsExpectedResult() var file = FormFileHelper.GetFormFile("this is just a test", "superFile.pdf", "application/pdf"); //Act - await this._controller.UpdateAppDocumentAsync(appId, documentTypeId, file, CancellationToken.None).ConfigureAwait(false); + await _controller.UpdateAppDocumentAsync(appId, documentTypeId, file, CancellationToken.None).ConfigureAwait(false); // Assert A.CallTo(() => _logic.CreateAppDocumentAsync(appId, documentTypeId, file, CancellationToken.None)) @@ -78,7 +80,7 @@ public async Task AddAppUserRole_AndUserRoleDescriptionWith201StatusCode() .Returns(appRoleData); //Act - var result = await this._controller.AddAppUserRole(appId, appUserRoles).ConfigureAwait(false); + var result = await _controller.AddAppUserRole(appId, appUserRoles).ConfigureAwait(false); foreach (var item in result) { //Assert @@ -97,7 +99,7 @@ public async Task GetOfferAgreementData_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetOfferAgreementDataAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetOfferAgreementDataAsync().ToListAsync().ConfigureAwait(false); // Assert result.Should().HaveCount(5); @@ -113,7 +115,7 @@ public async Task GetOfferAgreementConsentById_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetOfferAgreementConsentById(appId).ConfigureAwait(false); + var result = await _controller.GetOfferAgreementConsentById(appId).ConfigureAwait(false); // Assert result.Should().Be(data); @@ -132,7 +134,7 @@ public async Task SubmitOfferConsentToAgreementsAsync_ReturnsExpectedResult() .Returns(Enumerable.Repeat(consentStatusData, 1)); //Act - var result = await this._controller.SubmitOfferConsentToAgreementsAsync(appId, data).ConfigureAwait(false); + var result = await _controller.SubmitOfferConsentToAgreementsAsync(appId, data).ConfigureAwait(false); // Assert result.Should().HaveCount(1); @@ -150,7 +152,7 @@ public async Task GetAppDetailsForStatusAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetAppDetailsForStatusAsync(appId).ConfigureAwait(false); + var result = await _controller.GetAppDetailsForStatusAsync(appId).ConfigureAwait(false); // Assert result.Should().Be(data); @@ -166,7 +168,7 @@ public async Task DeleteAppRoleAsync_ReturnsExpectedResult() var roleId = Guid.NewGuid(); //Act - var result = await this._controller.DeleteAppRoleAsync(appId, roleId).ConfigureAwait(false); + var result = await _controller.DeleteAppRoleAsync(appId, roleId).ConfigureAwait(false); // Assert Assert.IsType(result); @@ -183,7 +185,7 @@ public async Task GetAppProviderSalesManagerAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetAppProviderSalesManagerAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetAppProviderSalesManagerAsync().ToListAsync().ConfigureAwait(false); // Assert result.Should().HaveCount(5); @@ -201,7 +203,7 @@ public async Task ExecuteAppCreation_ReturnsExpectedId() .Returns(appId); //Act - var result = await this._controller.ExecuteAppCreation(data).ConfigureAwait(false); + var result = await _controller.ExecuteAppCreation(data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AddAppAsync(data)).MustHaveHappenedOnceExactly(); @@ -241,7 +243,7 @@ public async Task UpdateAppRelease_ReturnsNoContent() ); // Act - var result = await this._controller.UpdateAppRelease(appId, data).ConfigureAwait(false); + var result = await _controller.UpdateAppRelease(appId, data).ConfigureAwait(false); // Assert Assert.IsType(result); @@ -257,7 +259,7 @@ public async Task GetAllInReviewStatusAppsAsync_ReturnsExpectedCount() .Returns(paginationResponse); //Act - var result = await this._controller.GetAllInReviewStatusAppsAsync().ConfigureAwait(false); + var result = await _controller.GetAllInReviewStatusAppsAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllInReviewStatusAppsAsync(0, 15, null, null)).MustHaveHappenedOnceExactly(); @@ -271,7 +273,7 @@ public async Task SubmitAppReleaseRequest_ReturnsExpectedCount() var appId = _fixture.Create(); //Act - var result = await this._controller.SubmitAppReleaseRequest(appId).ConfigureAwait(false); + var result = await _controller.SubmitAppReleaseRequest(appId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.SubmitAppReleaseRequestAsync(appId)).MustHaveHappenedOnceExactly(); @@ -285,7 +287,7 @@ public async Task ApproveAppRequest_ReturnsExpectedCount() var appId = _fixture.Create(); //Act - var result = await this._controller.ApproveAppRequest(appId).ConfigureAwait(false); + var result = await _controller.ApproveAppRequest(appId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.ApproveAppRequestAsync(appId)).MustHaveHappenedOnceExactly(); @@ -300,7 +302,7 @@ public async Task DeclineAppRequest_ReturnsNoContent() var data = new OfferDeclineRequest("Just a test"); //Act - var result = await this._controller.DeclineAppRequest(appId, data).ConfigureAwait(false); + var result = await _controller.DeclineAppRequest(appId, data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.DeclineAppRequestAsync(appId, data)).MustHaveHappenedOnceExactly(); @@ -318,7 +320,7 @@ public async Task GetinReviewAppDetailsByIdAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetInReviewAppDetailsByIdAsync(appId); + var result = await _controller.GetInReviewAppDetailsByIdAsync(appId); //Assert result.Should().NotBeNull(); @@ -333,7 +335,7 @@ public async Task DeleteAppDocumentsAsync_ReturnsExpectedResult() var documentId = Guid.NewGuid(); //Act - var result = await this._controller.DeleteAppDocumentsAsync(documentId).ConfigureAwait(false); + var result = await _controller.DeleteAppDocumentsAsync(documentId).ConfigureAwait(false); // Assert Assert.IsType(result); @@ -348,7 +350,7 @@ public async Task DeleteAppAsync_ReturnsExpectedResult() var appId = _fixture.Create(); //Act - var result = await this._controller.DeleteAppAsync(appId).ConfigureAwait(false); + var result = await _controller.DeleteAppAsync(appId).ConfigureAwait(false); // Assert Assert.IsType(result); @@ -380,7 +382,7 @@ public async Task GetTechnicalUserProfiles_ReturnsExpectedCount() .Returns(data); //Act - var result = await this._controller.GetTechnicalUserProfiles(offerId).ConfigureAwait(false); + var result = await _controller.GetTechnicalUserProfiles(offerId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetTechnicalUserProfilesForOffer(offerId)).MustHaveHappenedOnceExactly(); @@ -395,7 +397,7 @@ public async Task UpdateTechnicalUserProfiles_ReturnsExpectedCount() var data = _fixture.CreateMany(5); //Act - var result = await this._controller.CreateAndUpdateTechnicalUserProfiles(offerId, data).ConfigureAwait(false); + var result = await _controller.CreateAndUpdateTechnicalUserProfiles(offerId, data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.UpdateTechnicalUserProfiles(offerId, A>.That.Matches(x => x.Count() == 5))).MustHaveHappenedOnceExactly(); diff --git a/tests/marketplace/Apps.Service.Tests/Controllers/AppsControllerTests.cs b/tests/marketplace/Apps.Service.Tests/Controllers/AppsControllerTests.cs index 98bda37e0c..975bc60c43 100644 --- a/tests/marketplace/Apps.Service.Tests/Controllers/AppsControllerTests.cs +++ b/tests/marketplace/Apps.Service.Tests/Controllers/AppsControllerTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -43,7 +42,7 @@ public class AppsControllerTests private readonly IFixture _fixture; private readonly IAppsBusinessLogic _logic; private readonly AppsController _controller; - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; public AppsControllerTests() { @@ -51,9 +50,12 @@ public AppsControllerTests() _fixture.Behaviors.OfType().ToList() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); - this._controller = new AppsController(_logic); + _controller = new AppsController(_logic); _controller.AddControllerContextWithClaimAndBearer(_accessToken, _identity); } @@ -66,7 +68,7 @@ public async Task GetAllActiveAppsAsync_ReturnsExpectedCount() .Returns(data.AsAsyncEnumerable()); //Act - var result = await this._controller.GetAllActiveAppsAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetAllActiveAppsAsync().ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllActiveAppsAsync(null)).MustHaveHappenedOnceExactly(); @@ -82,7 +84,7 @@ public async Task GetAllBusinessAppsForCurrentUserAsync_ReturnsExpectedCount() .Returns(data.AsAsyncEnumerable()); //Act - var result = await this._controller.GetAllBusinessAppsForCurrentUserAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetAllBusinessAppsForCurrentUserAsync().ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllUserUserBusinessAppsAsync()).MustHaveHappenedOnceExactly(); @@ -99,7 +101,7 @@ public async Task GetAppDetailsByIdAsync_ReturnsExpectedCount() .Returns(data); //Act - var result = await this._controller.GetAppDetailsByIdAsync(appId).ConfigureAwait(false); + var result = await _controller.GetAppDetailsByIdAsync(appId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAppDetailsByIdAsync(appId, null)).MustHaveHappenedOnceExactly(); @@ -115,7 +117,7 @@ public async Task GetAllFavouriteAppsForCurrentUser_ReturnsExpectedCount() .Returns(ids.AsAsyncEnumerable()); //Act - var result = await this._controller.GetAllFavouriteAppsForCurrentUserAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetAllFavouriteAppsForCurrentUserAsync().ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllFavouriteAppsForUserAsync()).MustHaveHappenedOnceExactly(); @@ -129,7 +131,7 @@ public async Task AddFavouriteAppForCurrentUserAsync_ReturnsBusinessLogic() var id = _fixture.Create(); //Act - var result = await this._controller.AddFavouriteAppForCurrentUserAsync(id).ConfigureAwait(false); + var result = await _controller.AddFavouriteAppForCurrentUserAsync(id).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AddFavouriteAppForUserAsync(id)).MustHaveHappenedOnceExactly(); @@ -143,7 +145,7 @@ public async Task RemoveFavouriteAppForCurrentUserAsync_CallsBusinessLogic() var id = _fixture.Create(); //Act - var result = await this._controller.RemoveFavouriteAppForCurrentUserAsync(id).ConfigureAwait(false); + var result = await _controller.RemoveFavouriteAppForCurrentUserAsync(id).ConfigureAwait(false); //Assert A.CallTo(() => _logic.RemoveFavouriteAppForUserAsync(id)).MustHaveHappenedOnceExactly(); @@ -162,7 +164,7 @@ public async Task GetCompanySubscribedAppSubscriptionStatusesForCurrentUserAsync .Returns(pagination); //Act - var result = await this._controller.GetCompanySubscribedAppSubscriptionStatusesForUserAsync().ConfigureAwait(false); + var result = await _controller.GetCompanySubscribedAppSubscriptionStatusesForUserAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanySubscribedAppSubscriptionStatusesForUserAsync(0, 15)).MustHaveHappenedOnceExactly(); @@ -184,7 +186,7 @@ public async Task GetCompanyProvidedAppSubscriptionStatusesForCurrentUserAsync_R .Returns(pagination); //Act - var result = await this._controller.GetCompanyProvidedAppSubscriptionStatusesForCurrentUserAsync(offerId: offerId).ConfigureAwait(false); + var result = await _controller.GetCompanyProvidedAppSubscriptionStatusesForCurrentUserAsync(offerId: offerId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanyProvidedAppSubscriptionStatusesForUserAsync(0, 15, null, null, offerId)).MustHaveHappenedOnceExactly(); @@ -202,7 +204,7 @@ public async Task AddAppSubscriptionWithConsent_ReturnsExpectedId() //Act var serviceId = Guid.NewGuid(); - var result = await this._controller.AddCompanyAppSubscriptionAsync(serviceId, consentData).ConfigureAwait(false); + var result = await _controller.AddCompanyAppSubscriptionAsync(serviceId, consentData).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AddOwnCompanyAppSubscriptionAsync(serviceId, consentData)).MustHaveHappenedOnceExactly(); @@ -216,7 +218,7 @@ public async Task UnsubscribeCompanyAppSubscription_ReturnsNoContent() var appId = _fixture.Create(); //Act - var result = await this._controller.UnsubscribeCompanyAppSubscriptionAsync(appId).ConfigureAwait(false); + var result = await _controller.UnsubscribeCompanyAppSubscriptionAsync(appId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.UnsubscribeOwnCompanyAppSubscriptionAsync(appId)).MustHaveHappenedOnceExactly(); @@ -233,7 +235,7 @@ public async Task GetAppDataAsync_ReturnsExpectedCount() .Returns(paginationResponse); //Act - var result = await this._controller.GetAppDataAsync().ConfigureAwait(false); + var result = await _controller.GetAppDataAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanyProvidedAppsDataForUserAsync(0, 15, null, null, null)).MustHaveHappenedOnceExactly(); @@ -250,7 +252,7 @@ public async Task GetServiceAgreement_ReturnsExpected() .Returns(agreementData); //Act - var result = await this._controller.GetAppAgreement(appId).ToListAsync().ConfigureAwait(false); + var result = await _controller.GetAppAgreement(appId).ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAppAgreement(appId)).MustHaveHappenedOnceExactly(); @@ -274,7 +276,7 @@ public async Task AutoSetupService_ReturnsExpected() .Returns(responseData); //Act - var result = await this._controller.AutoSetupApp(data).ConfigureAwait(false); + var result = await _controller.AutoSetupApp(data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AutoSetupAppAsync(data)).MustHaveHappenedOnceExactly(); @@ -290,7 +292,7 @@ public async Task StartAutoSetupProcess_ReturnsExpected() var data = new OfferAutoSetupData(offerSubscriptionId, "https://test.de"); //Act - var result = await this._controller.StartAutoSetupAppProcess(data).ConfigureAwait(false); + var result = await _controller.StartAutoSetupAppProcess(data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.StartAutoSetupAsync(data)).MustHaveHappenedOnceExactly(); @@ -304,7 +306,7 @@ public async Task ActivateAppSubscription_ReturnsExpected() var offerSubscriptionId = Guid.NewGuid(); //Act - var result = await this._controller.ActivateOfferSubscription(offerSubscriptionId).ConfigureAwait(false); + var result = await _controller.ActivateOfferSubscription(offerSubscriptionId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.TriggerActivateOfferSubscription(offerSubscriptionId)).MustHaveHappenedOnceExactly(); @@ -318,7 +320,7 @@ public async Task ActivateSingleInstance_ReturnsExpected() var offerSubscriptionId = Guid.NewGuid(); //Act - var result = await this._controller.ActivateSingleInstance(offerSubscriptionId).ConfigureAwait(false); + var result = await _controller.ActivateSingleInstance(offerSubscriptionId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.ActivateSingleInstance(offerSubscriptionId)).MustHaveHappenedOnceExactly(); @@ -338,7 +340,7 @@ public async Task GetAppImageDocumentContentAsync_ReturnsExpected() .Returns((content, "image/png", fileName)); //Act - var result = await this._controller.GetAppDocumentContentAsync(appId, documentId, CancellationToken.None).ConfigureAwait(false); + var result = await _controller.GetAppDocumentContentAsync(appId, documentId, CancellationToken.None).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAppDocumentContentAsync(A._, A._, A._)).MustHaveHappenedOnceExactly(); @@ -357,7 +359,7 @@ public async Task GetAppDocumentTypePdfContentAsync_ReturnsExpected() .Returns((content, "application/pdf", fileName)); //Act - var result = await this._controller.GetAppDocumentContentAsync(appId, documentId, CancellationToken.None).ConfigureAwait(false); + var result = await _controller.GetAppDocumentContentAsync(appId, documentId, CancellationToken.None).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAppDocumentContentAsync(A._, A._, A._)).MustHaveHappenedOnceExactly(); @@ -374,7 +376,7 @@ public async Task GetSubscriptionDetailForProvider_ReturnsExpected() .Returns(data); // Act - var result = await this._controller.GetSubscriptionDetailForProvider(appId, subscriptionId).ConfigureAwait(false); + var result = await _controller.GetSubscriptionDetailForProvider(appId, subscriptionId).ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetSubscriptionDetailForProvider(appId, subscriptionId)).MustHaveHappenedOnceExactly(); @@ -392,7 +394,7 @@ public async Task GetSubscriptionDetailForSubscriber_ReturnsExpected() .Returns(data); // Act - var result = await this._controller.GetSubscriptionDetailForSubscriber(appId, subscriptionId).ConfigureAwait(false); + var result = await _controller.GetSubscriptionDetailForSubscriber(appId, subscriptionId).ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetSubscriptionDetailForSubscriber(appId, subscriptionId)).MustHaveHappenedOnceExactly(); @@ -410,7 +412,7 @@ public async Task GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsy .Returns(data); //Act - var result = await this._controller.GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsync().ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetOwnCompanyActiveSubscribedAppSubscriptionStatusesForUserAsync()).MustHaveHappenedOnceExactly(); @@ -430,7 +432,7 @@ public async Task GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync_Re .Returns(data); //Act - var result = await this._controller.GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync().ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetOwnCompanySubscribedAppOfferSubscriptionDataForUserAsync()).MustHaveHappenedOnceExactly(); diff --git a/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs b/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs index 25b9a71b32..43de420e3e 100644 --- a/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs +++ b/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -32,9 +31,10 @@ namespace Offer.Library.Web.Tests; public class OfferDocumentServiceTests { + private static readonly Guid CompanyUserId = Guid.NewGuid(); private static readonly Guid CompanyUserCompanyId = new("395f955b-f11b-4a74-ab51-92a526c1973a"); private readonly Guid _validAppId = Guid.NewGuid(); - private readonly IdentityData _identity = new("395f955b-f11b-4a55-ab51-92a526c1974b", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, CompanyUserCompanyId); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly IPortalRepositories _portalRepositories; @@ -50,7 +50,11 @@ public OfferDocumentServiceTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(CompanyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(CompanyUserCompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _portalRepositories = A.Fake(); @@ -235,13 +239,14 @@ public async Task UploadDocumentAsync_isStatusCreated_ThrowsConflictException(Of { // Arrange var id = _fixture.Create(); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); + var companyId = Guid.NewGuid(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.CompanyId).Returns(companyId); var uploadDocumentTypeIdSettings = offerTypeId == OfferTypeId.APP ? new UploadDocumentConfig[] { new(DocumentTypeId.APP_CONTRACT, new[] { MediaTypeId.PDF }) } : new UploadDocumentConfig[] { new(DocumentTypeId.ADDITIONAL_DETAILS, new[] { MediaTypeId.PDF }) }; var file = FormFileHelper.GetFormFile("this is just a test", "superFile.pdf", "application/pdf"); - A.CallTo(() => _offerRepository.GetProviderCompanyUserIdForOfferUntrackedAsync(id, identity.CompanyId, offerStatusId, offerTypeId)) + A.CallTo(() => _offerRepository.GetProviderCompanyUserIdForOfferUntrackedAsync(id, companyId, offerStatusId, offerTypeId)) .Returns((true, false, true)); // Act diff --git a/tests/marketplace/Offers.Library.Tests/Service/OfferServiceTests.cs b/tests/marketplace/Offers.Library.Tests/Service/OfferServiceTests.cs index 7291777333..50e5a580f3 100644 --- a/tests/marketplace/Offers.Library.Tests/Service/OfferServiceTests.cs +++ b/tests/marketplace/Offers.Library.Tests/Service/OfferServiceTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -37,9 +36,10 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Offers.Library.Tests.Service; public class OfferServiceTests { - private const string IamUserId = "3e8343f7-4fe5-4296-8312-f33aa6dbde5d"; private static readonly Guid CompanyUserCompanyId = new("395f955b-f11b-4a74-ab51-92a526c1973a"); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, CompanyUserCompanyId); + private readonly IIdentityData _identity; + private readonly Guid _companyUserId = Guid.NewGuid(); + private readonly Guid _companyId = Guid.NewGuid(); private readonly Guid _existingServiceId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); private readonly Guid _existingAgreementId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47664"); private readonly Guid _validConsentId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47664"); @@ -79,10 +79,7 @@ public OfferServiceTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, CompanyUserCompanyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER) - { - UserEntityId = IamUserId - }; + var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, CompanyUserCompanyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER); _companyUser = _fixture.Build() .With(u => u.Identity, identity) @@ -103,10 +100,13 @@ public OfferServiceTests() _documentRepository = A.Fake(); _offerSetupService = A.Fake(); _connectorsRepository = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); _logger = A.Fake>(); + A.CallTo(() => _identity.IdentityId).Returns(_companyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(_companyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); _sut = new OfferService(_portalRepositories, _notificationService, _roleBaseMailService, _identityService, _offerSetupService, _logger); @@ -136,7 +136,7 @@ public async Task CreateServiceOffering_WithValidDataAndEmptyDescriptions_Return }); // Act - var result = await _sut.CreateServiceOfferingAsync(new ServiceOfferingData("Newest Service", "42", "mail@test.de", _identity.UserId, Enumerable.Empty(), new[] { ServiceTypeId.DATASPACE_SERVICE }, "http://google.com"), OfferTypeId.SERVICE); + var result = await _sut.CreateServiceOfferingAsync(new ServiceOfferingData("Newest Service", "42", "mail@test.de", _companyUserId, Enumerable.Empty(), new[] { ServiceTypeId.DATASPACE_SERVICE }, "http://google.com"), OfferTypeId.SERVICE); // Assert result.Should().Be(serviceId); @@ -163,7 +163,7 @@ public async Task CreateServiceOffering_WithValidDataAndDescription_ReturnsCorre }); // Act - var serviceOfferingData = new ServiceOfferingData("Newest Service", "42", "mail@test.de", _identity.UserId, new LocalizedDescription[] + var serviceOfferingData = new ServiceOfferingData("Newest Service", "42", "mail@test.de", _companyUserId, new LocalizedDescription[] { new ("en", "That's a description with a valid language code", "Short description") }, @@ -207,7 +207,7 @@ public async Task CreateServiceOffering_WithoutTitle_ThrowsException() public async Task CreateServiceOffering_WithInvalidLanguage_ThrowsException() { // Act - var serviceOfferingData = new ServiceOfferingData("Newest Service", "42", "mail@test.de", _identity.UserId, new LocalizedDescription[] + var serviceOfferingData = new ServiceOfferingData("Newest Service", "42", "mail@test.de", _companyUserId, new LocalizedDescription[] { new ("gg", "That's a description with incorrect language short code", "Short description") }, new[] { ServiceTypeId.DATASPACE_SERVICE }, "http://google.com"); @@ -302,15 +302,14 @@ public async Task CreateOfferAgreementConsentAsync_WithNotExistingAgreement_Thro [Fact] public async Task CreateOfferAgreementConsentAsync_WithWrongUser_ThrowsException() { - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); // Act async Task Action() => await _sut.CreateOfferSubscriptionAgreementConsentAsync(_existingServiceId, _existingAgreementId, ConsentStatusId.ACTIVE, OfferTypeId.SERVICE); // Assert var ex = await Assert.ThrowsAsync(Action); - ex.ParamName.Should().Be("UserEntityId"); + ex.ParamName.Should().Be("IdentityId"); } [Fact] @@ -399,15 +398,14 @@ public async Task CreateOrUpdateServiceAgreementConsentAsync_WithWrongUser_Throw { new(_existingAgreementId, ConsentStatusId.ACTIVE) }; - A.CallTo(() => _identityService.IdentityData) - .Returns(new IdentityData(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid())); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); // Act async Task Action() => await _sut.CreateOrUpdateOfferSubscriptionAgreementConsentAsync(_existingServiceId, data, OfferTypeId.SERVICE); // Assert var ex = await Assert.ThrowsAsync(Action); - ex.ParamName.Should().Be("UserEntityId"); + ex.ParamName.Should().Be("IdentityId"); } [Fact] @@ -489,7 +487,7 @@ public async Task AddAppAsync_WithInvalidSalesManager_ThrowsException() // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - error.Message.Should().Be($"SalesManger is not a member of the company {_identity.CompanyId}"); + error.Message.Should().Be($"SalesManger is not a member of the company {_companyId}"); } [Fact] @@ -751,7 +749,7 @@ public async Task SubmitOffer_WithValidOfferData_UpdatesAppAndSendsNotification( await _sut.SubmitOfferAsync(offerId, offerType, new[] { NotificationTypeId.APP_SUBSCRIPTION_REQUEST }, _fixture.CreateMany(), new[] { DocumentTypeId.CONFORMITY_APPROVAL_BUSINESS_APPS, DocumentTypeId.APP_LEADIMAGE, DocumentTypeId.APP_IMAGE }).ConfigureAwait(false); // Assert - A.CallTo(() => _notificationService.CreateNotifications(A>._, _identity.UserId, A>._, false)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _notificationService.CreateNotifications(A>._, _companyUserId, A>._, false)).MustHaveHappenedOnceExactly(); A.CallTo(() => _documentRepository.AttachAndModifyDocuments(A?, Action)>>._)).MustHaveHappenedOnceExactly(); initial.Should().NotBeNull().And.HaveCount(1).And.Satisfy(x => x.Id == data.DocumentDatas.ElementAt(0).DocumentId && x.DocumentStatusId == DocumentStatusId.PENDING); modified.Should().NotBeNull().And.HaveCount(1).And.Satisfy(x => x.Id == data.DocumentDatas.ElementAt(0).DocumentId && x.DocumentStatusId == DocumentStatusId.LOCKED); @@ -1060,7 +1058,7 @@ public async Task SubmitService_WithValidOfferData_UpdatesAppAndSendsNotificatio await _sut.SubmitServiceAsync(offerId, offerType, new[] { NotificationTypeId.APP_SUBSCRIPTION_REQUEST }, _fixture.CreateMany()).ConfigureAwait(false); // Assert - A.CallTo(() => _notificationService.CreateNotifications(A>._, _identity.UserId, A>._, A._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _notificationService.CreateNotifications(A>._, _companyUserId, A>._, A._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _documentRepository.AttachAndModifyDocuments(A?, Action)>>._)).MustHaveHappenedOnceExactly(); initial.Should().NotBeNull().And.HaveCount(1).And.Satisfy(x => x.Id == data.DocumentDatas.ElementAt(0).DocumentId && x.DocumentStatusId == DocumentStatusId.PENDING); modified.Should().NotBeNull().And.HaveCount(1).And.Satisfy(x => x.Id == data.DocumentDatas.ElementAt(0).DocumentId && x.DocumentStatusId == DocumentStatusId.LOCKED); @@ -1250,7 +1248,7 @@ public async Task DeactivateOfferStatusIdAsync_WithoutExistingAppId_ThrowsForbid { // Arrange var notExistingId = _fixture.Create(); - A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(notExistingId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(notExistingId, offerTypeId, _companyId)) .Returns(((bool, bool))default); // Act @@ -1268,7 +1266,7 @@ public async Task DeactivateOfferStatusIdAsync_WithNotAssignedUser_ThrowsForbidd { // Arrange var offerId = _fixture.Create(); - A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _companyId)) .Returns((true, false)); // Act @@ -1287,7 +1285,7 @@ public async Task DeactivateOfferStatusIdAsync_WithNotOfferStatusId_ThrowsConfli { // Arrange var offerId = _fixture.Create(); - A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _companyId)) .Returns((false, true)); // Act @@ -1307,7 +1305,7 @@ public async Task DeactivateOfferStatusIdAsync_WithValidData_CallsExpected(Offer // Arrange var offer = _fixture.Create(); var offerId = _fixture.Create(); - A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _offerRepository.GetOfferActiveStatusDataByIdAsync(offerId, offerTypeId, _companyId)) .Returns(new ValueTuple(true, true)); A.CallTo(() => _offerRepository.AttachAndModifyOffer(offerId, A>._, A?>._)) @@ -1343,7 +1341,7 @@ public async Task GetProviderOfferAgreementConsentById_ReturnExpectedResult() var result = await _sut.GetProviderOfferAgreementConsentById(serviceId, OfferTypeId.SERVICE).ConfigureAwait(false); // Assert - A.CallTo(() => _agreementRepository.GetOfferAgreementConsentById(serviceId, _identity.CompanyId, OfferTypeId.SERVICE)) + A.CallTo(() => _agreementRepository.GetOfferAgreementConsentById(serviceId, _companyId, OfferTypeId.SERVICE)) .MustHaveHappenedOnceExactly(); result.Should().Be(data); } @@ -1362,7 +1360,7 @@ public async Task GetProviderOfferAgreementConsentById_WithInvalidUserProviderCo // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); - ex.Message.Should().Be($"Company {_identity.CompanyId} is not assigned with Offer {serviceId}"); + ex.Message.Should().Be($"Company {_companyId} is not assigned with Offer {serviceId}"); } [Fact] @@ -1395,7 +1393,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithNoService_Thro var offerId = Guid.NewGuid(); var agreementId = Guid.NewGuid(); var consentData = new OfferAgreementConsent(new[] { new AgreementConsentStatus(agreementId, ConsentStatusId.ACTIVE) }); - A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _identity.CompanyId, OfferStatusId.CREATED, offerTypeId)) + A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _companyId, OfferStatusId.CREATED, offerTypeId)) .Returns(((OfferAgreementConsentUpdate, bool))default); // Act @@ -1415,7 +1413,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithUserNotInProvi var offerId = Guid.NewGuid(); var agreementId = Guid.NewGuid(); var consentData = new OfferAgreementConsent(new[] { new AgreementConsentStatus(agreementId, ConsentStatusId.ACTIVE) }); - A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _identity.CompanyId, OfferStatusId.CREATED, offerTypeId)) + A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _companyId, OfferStatusId.CREATED, offerTypeId)) .Returns((new OfferAgreementConsentUpdate(Enumerable.Empty(), Enumerable.Empty()), false)); // Act @@ -1423,7 +1421,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithUserNotInProvi // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"Company {_identity.CompanyId} is not assigned with Offer {offerId}"); + ex.Message.Should().Be($"Company {_companyId} is not assigned with Offer {offerId}"); } [Theory] @@ -1446,7 +1444,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithInvalidData_Th { agreementId }); - A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _identity.CompanyId, OfferStatusId.CREATED, offerTypeId)) + A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _companyId, OfferStatusId.CREATED, offerTypeId)) .Returns((offerAgreementConsent, true)); // Act @@ -1482,7 +1480,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithValidData_Retu agreementId, additionalAgreementId }); - A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _identity.CompanyId, OfferStatusId.CREATED, offerTypeId)) + A.CallTo(() => _agreementRepository.GetOfferAgreementConsent(offerId, _companyId, OfferStatusId.CREATED, offerTypeId)) .Returns((offerAgreementConsent, true)); A.CallTo(() => _consentRepository.AddAttachAndModifyOfferConsents(A>._, A>._, A._, A._, A._, A._)) .Returns(new Consent[] { @@ -1501,7 +1499,7 @@ public async Task CreateOrUpdateProviderOfferAgreementConsent_WithValidData_Retu var result = await _sut.CreateOrUpdateProviderOfferAgreementConsent(offerId, consentData, offerTypeId).ConfigureAwait(false); // Assert - A.CallTo(() => _consentRepository.AddAttachAndModifyOfferConsents(A>._, A>._, offerId, _identity.CompanyId, _identity.UserId, A._)) + A.CallTo(() => _consentRepository.AddAttachAndModifyOfferConsents(A>._, A>._, offerId, _companyId, _companyUserId, A._)) .MustHaveHappenedOnceExactly(); result.Should() .HaveCount(2) @@ -1682,14 +1680,14 @@ public async Task DeleteDocumentsAsync_ReturnsExpectedResult(OfferTypeId offerTy //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.CREATED, offerId, true) }, true, DocumentStatusId.PENDING, true)); //Act await _sut.DeleteDocumentsAsync(_validDocumentId, documentTypeIdSettings, offerTypeId).ConfigureAwait(false); // Assert - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .MustHaveHappenedOnceExactly(); A.CallTo(() => _offerRepository.RemoveOfferAssignedDocument(offerId, _validDocumentId)).MustHaveHappenedOnceExactly(); A.CallTo(() => _documentRepository.RemoveDocument(_validDocumentId)).MustHaveHappenedOnceExactly(); @@ -1702,7 +1700,7 @@ public async Task DeleteDocumentsAsync_ReturnsExpectedResult(OfferTypeId offerTy public async Task DeleteDocumentsAsync_WithNoDocument_ThrowsNotFoundException(OfferTypeId offerTypeId, IEnumerable documentTypeIdSettings) { //Arrange - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns(((IEnumerable<(OfferStatusId, Guid, bool)>, bool, DocumentStatusId, bool))default); //Act @@ -1719,7 +1717,7 @@ public async Task DeleteDocumentsAsync_WithNoDocument_ThrowsNotFoundException(Of public async Task DeleteDocumentsAsync_WithNoAssignedOfferDocument_ThrowsConflictException(OfferTypeId offerTypeId, IEnumerable documentTypeIdSettings) { //Arrange - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { ((OfferStatusId, Guid, bool))default }, true, DocumentStatusId.PENDING, true)); //Act @@ -1736,7 +1734,7 @@ public async Task DeleteDocumentsAsync_WithNoAssignedOfferDocument_ThrowsConflic public async Task DeleteDocumentsAsync_WithMultipleDocumentsAssigned_ThrowsConflictException(OfferTypeId offerTypeId, IEnumerable documentTypeIdSettings) { //Arrange - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns(( new[] { @@ -1763,7 +1761,7 @@ public async Task DeleteDocumentsAsync_WithDocumentAssignedToService_ThrowsConfl //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.CREATED, offerId, false) }, true, DocumentStatusId.PENDING, true)); //Act @@ -1782,7 +1780,7 @@ public async Task DeleteDocumentsAsync_WithInvalidProviderCompanyUser_ThrowsForb //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.CREATED, offerId, true) }, true, DocumentStatusId.PENDING, false)); //Act @@ -1790,7 +1788,7 @@ public async Task DeleteDocumentsAsync_WithInvalidProviderCompanyUser_ThrowsForb // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"Company {_identity.CompanyId} is not the same company of document {_validDocumentId}"); + ex.Message.Should().Be($"Company {_companyId} is not the same company of document {_validDocumentId}"); } [Theory] @@ -1801,7 +1799,7 @@ public async Task DeleteDocumentsAsync_WithInvalidOfferStatus_ThrowsConflictExce //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.ACTIVE, offerId, true) }, true, DocumentStatusId.PENDING, true)); //Act @@ -1820,7 +1818,7 @@ public async Task DeleteDocumentsAsync_WithInvalidDocumentType_ThrowsArgumentExc //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.CREATED, offerId, true) }, false, DocumentStatusId.PENDING, true)); //Act @@ -1839,7 +1837,7 @@ public async Task DeleteDocumentsAsync_WithInvalidDocumentStatus_ThrowsConflictE //Arrange var offerId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _identity.CompanyId, documentTypeIdSettings, offerTypeId)) + A.CallTo(() => _documentRepository.GetOfferDocumentsAsync(_validDocumentId, _companyId, documentTypeIdSettings, offerTypeId)) .Returns((new[] { (OfferStatusId.CREATED, offerId, true) }, true, DocumentStatusId.LOCKED, true)); //Act async Task Act() => await _sut.DeleteDocumentsAsync(_validDocumentId, documentTypeIdSettings, offerTypeId).ConfigureAwait(false); @@ -1861,7 +1859,7 @@ public async Task GetTechnicalUserProfileData_ReturnsExpectedResult(OfferTypeId // Arrange var offerId = _fixture.Create(); var data = _fixture.CreateMany(5); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)) .Returns((true, data)); // Act @@ -1869,7 +1867,7 @@ public async Task GetTechnicalUserProfileData_ReturnsExpectedResult(OfferTypeId // Assert result.Should().HaveCount(5); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)).MustHaveHappenedOnceExactly(); } [Theory] @@ -1880,7 +1878,7 @@ public async Task GetTechnicalUserProfileData_WithoutOffer_ThrowsNotFoundExcepti // Arrange var offerId = _fixture.Create(); var data = _fixture.CreateMany(5); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)) .Returns(((bool, IEnumerable))default); // Act @@ -1889,7 +1887,7 @@ public async Task GetTechnicalUserProfileData_WithoutOffer_ThrowsNotFoundExcepti // Assert var ex = await Assert.ThrowsAsync(Act); ex.Message.Should().Be($"Offer {offerId} does not exist"); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)).MustHaveHappenedOnceExactly(); } [Theory] @@ -1899,7 +1897,7 @@ public async Task GetTechnicalUserProfileData_WithUserNotInProvidingCompany_Thro { // Arrange var offerId = _fixture.Create(); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)) .Returns((false, Enumerable.Empty())); // Act @@ -1907,8 +1905,8 @@ public async Task GetTechnicalUserProfileData_WithUserNotInProvidingCompany_Thro // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"Company {_identity.CompanyId} is not the providing company"); - A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _identity.CompanyId, offerTypeId)).MustHaveHappenedOnceExactly(); + ex.Message.Should().Be($"Company {_companyId} is not the providing company"); + A.CallTo(() => _technicalUserProfileRepository.GetTechnicalUserProfileInformation(offerId, _companyId, offerTypeId)).MustHaveHappenedOnceExactly(); } #endregion @@ -1947,7 +1945,7 @@ public async Task UpdateTechnicalUserProfiles_ReturnsExpectedResult(OfferTypeId (technicalUserProfile2, new[] {userRole1Id, userRole2Id}), // to delete (technicalUserProfile3, Enumerable.Empty()) }; - A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _companyId)) .Returns(new OfferProfileData(true, new[] { ServiceTypeId.DATASPACE_SERVICE }, profileData)); A.CallTo(() => _userRolesRepository.GetRolesForClient("cl1")) .Returns(new Guid[] { userRole1Id, userRole2Id }.ToAsyncEnumerable()); @@ -2004,7 +2002,7 @@ public async Task UpdateTechnicalUserProfiles_WithNotExistingRoles_ThrowsExcepti missingRoleId }), }; - A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _companyId)) .Returns(new OfferProfileData(true, new[] { ServiceTypeId.DATASPACE_SERVICE }, Enumerable.Empty<(Guid TechnicalUserProfileId, IEnumerable UserRoleIds)>())); A.CallTo(() => _userRolesRepository.GetRolesForClient("cl1")) .Returns(new Guid[] { userRole1Id, userRole2Id }.ToAsyncEnumerable()); @@ -2034,7 +2032,7 @@ public async Task UpdateTechnicalUserProfiles_ForConsultancyService_ThrowsExcept userRole2Id, }), }; - A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _companyId)) .Returns(new OfferProfileData(true, new[] { ServiceTypeId.CONSULTANCY_SERVICE }, Enumerable.Empty<(Guid TechnicalUserProfileId, IEnumerable UserRoleIds)>())); A.CallTo(() => _userRolesRepository.GetRolesForClient("cl1")) .Returns(new Guid[] { userRole1Id, userRole2Id }.ToAsyncEnumerable()); @@ -2064,7 +2062,7 @@ public async Task UpdateTechnicalUserProfiles_WithUserNotInProvidingCompany_Thro userRole2Id, }), }; - A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _companyId)) .Returns(new OfferProfileData(false, new[] { ServiceTypeId.DATASPACE_SERVICE }, Enumerable.Empty<(Guid TechnicalUserProfileId, IEnumerable UserRoleIds)>())); A.CallTo(() => _userRolesRepository.GetRolesForClient("cl1")) .Returns(new Guid[] { userRole1Id, userRole2Id }.ToAsyncEnumerable()); @@ -2074,7 +2072,7 @@ public async Task UpdateTechnicalUserProfiles_WithUserNotInProvidingCompany_Thro // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"Company {_identity.CompanyId} is not the providing company"); + ex.Message.Should().Be($"Company {_companyId} is not the providing company"); } [Theory] @@ -2094,7 +2092,7 @@ public async Task UpdateTechnicalUserProfiles_WithoutOffer_ThrowsException(Offer userRole2Id, }), }; - A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _identity.CompanyId)) + A.CallTo(() => _technicalUserProfileRepository.GetOfferProfileData(offerId, offerTypeId, _companyId)) .Returns((OfferProfileData?)null); A.CallTo(() => _userRolesRepository.GetRolesForClient("cl1")) .Returns(new Guid[] { userRole1Id, userRole2Id }.ToAsyncEnumerable()); @@ -2175,7 +2173,7 @@ public async Task GetSubscriptionDetailForProvider_WithNotExistingOffer_ThrowsNo ex.Message.Should().Contain($"subscription {subscriptionId} for offer {serviceId} of type {OfferTypeId.SERVICE} does not exist"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _identity.CompanyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _companyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2199,10 +2197,10 @@ public async Task GetSubscriptionDetailForProvider_WithUserNotInProvidingCompany // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Contain($"Company {_identity.CompanyId} is not part of the Provider company"); + ex.Message.Should().Contain($"Company {_companyId} is not part of the Provider company"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _identity.CompanyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _companyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2229,7 +2227,7 @@ public async Task GetSubscriptionDetailForProvider_WithValidData_ReturnsExpected result.Should().Be(data); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _identity.CompanyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForProviderAsync(serviceId, subscriptionId, _companyId, OfferTypeId.SERVICE, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2282,7 +2280,7 @@ public async Task GetAppSubscriptionDetailForProvider_WithNotExistingOffer_Throw ex.Message.Should().Contain($"subscription {subscriptionId} for offer {appId} of type {OfferTypeId.APP} does not exist"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2306,10 +2304,10 @@ public async Task GetAppSubscriptionDetailForProvider_WithUserNotInProvidingComp // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Contain($"Company {_identity.CompanyId} is not part of the Provider company"); + ex.Message.Should().Contain($"Company {_companyId} is not part of the Provider company"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2343,7 +2341,7 @@ public async Task GetAppSubscriptionDetailForProvider_WithValidData_ReturnsExpec result.OfferSubscriptionStatus.Should().Be(data.OfferSubscriptionStatus); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetAppSubscriptionDetailsForProviderAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2396,7 +2394,7 @@ public async Task GetSubscriptionDetailsForSubscriber_WithNotExistingOffer_Throw ex.Message.Should().Contain($"subscription {subscriptionId} for offer {appId} of type {OfferTypeId.APP} does not exist"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2420,10 +2418,10 @@ public async Task GetSubscriptionDetailsForSubscriber_WithUserNotInProvidingComp // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Contain($"Company {_identity.CompanyId} is not part of the Subscriber company"); + ex.Message.Should().Contain($"Company {_companyId} is not part of the Subscriber company"); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2451,7 +2449,7 @@ public async Task GetSubscriptionDetailsForSubscriber_WithValidData_ReturnsExpec result.Should().Be(data); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>.That.IsSameSequenceAs(companyAdminRoles))) .MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _identity.CompanyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) + A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionDetailsForSubscriberAsync(appId, subscriptionId, _companyId, OfferTypeId.APP, A>.That.IsSameSequenceAs(new[] { _validUserRoleId }))) .MustHaveHappenedOnceExactly(); } @@ -2481,7 +2479,7 @@ public async Task GetCompanySubscribedOfferSubscriptionStatusesForUserAsync_Retu x => x.OfferId == data[3].OfferId && x.OfferName == data[3].OfferName && x.Provider == data[3].Provider && x.OfferSubscriptionStatusId == data[3].OfferSubscriptionStatusId && x.OfferSubscriptionId == data[3].OfferSubscriptionId && x.DocumentId == data[3].DocumentId, x => x.OfferId == data[4].OfferId && x.OfferName == data[4].OfferName && x.Provider == data[4].Provider && x.OfferSubscriptionStatusId == data[4].OfferSubscriptionStatusId && x.OfferSubscriptionId == data[4].OfferSubscriptionId && x.DocumentId == data[4].DocumentId ); - A.CallTo(() => _offerSubscriptionsRepository.GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_identity.CompanyId, offerTypeId, documentTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_companyId, offerTypeId, documentTypeId)) .MustHaveHappenedOnceExactly(); } @@ -2500,7 +2498,7 @@ public async Task GetCompanySubscribedOfferSubscriptionStatusesForUserAsync_With // Assert result.Meta.NumberOfElements.Should().Be(0); result.Content.Should().BeEmpty(); - A.CallTo(() => _offerSubscriptionsRepository.GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_identity.CompanyId, offerTypeId, documentTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOwnCompanySubscribedOfferSubscriptionStatusesUntrackedAsync(_companyId, offerTypeId, documentTypeId)) .MustHaveHappenedOnceExactly(); } @@ -2522,7 +2520,7 @@ public async Task UnsubscribeOwnCompanySubscriptionAsync_WithNotExistingApp_Thro // Assert var ex = await Assert.ThrowsAsync(Act); ex.Message.Should().Be($"Subscription {notExistingSubscriptionId} does not exist."); - A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(notExistingSubscriptionId, _identity.CompanyId)) + A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(notExistingSubscriptionId, _companyId)) .MustHaveHappenedOnceExactly(); } @@ -2530,9 +2528,7 @@ public async Task UnsubscribeOwnCompanySubscriptionAsync_WithNotExistingApp_Thro public async Task UnsubscribeOwnCompanySubscriptionAsync_IsNoMemberOfCompanyProvidingApp_ThrowsArgumentException() { // Arrange - var identity = _fixture.Create(); var subscriptionId = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(A._, A._)) .Returns((OfferSubscriptionStatusId.ACTIVE, false, true, _fixture.CreateMany(), _fixture.CreateMany())); @@ -2542,7 +2538,7 @@ public async Task UnsubscribeOwnCompanySubscriptionAsync_IsNoMemberOfCompanyProv // Assert var ex = await Assert.ThrowsAsync(Act); ex.Message.Should().Be("the calling user does not belong to the subscribing company"); - A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(subscriptionId, identity.CompanyId)) + A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(subscriptionId, _companyId)) .MustHaveHappenedOnceExactly(); } @@ -2562,8 +2558,8 @@ public async Task UnsubscribeOwnCompanySubscriptionAsync_WithInactiveApp_ThrowsA // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"There is no active or pending subscription for company '{_identity.CompanyId}' and subscriptionId '{offerSubscriptionId}'"); - A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(offerSubscriptionId, _identity.CompanyId)) + ex.Message.Should().Be($"There is no active or pending subscription for company '{_companyId}' and subscriptionId '{offerSubscriptionId}'"); + A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(offerSubscriptionId, _companyId)) .MustHaveHappenedOnceExactly(); } @@ -2610,7 +2606,7 @@ public async Task UnsubscribeOwnCompanySubscriptionAsync_CallsExpected() // Assert offerSubscription.OfferSubscriptionStatusId.Should().Be(OfferSubscriptionStatusId.INACTIVE); A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); - A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(offerSubscription.Id, _identity.CompanyId)) + A.CallTo(() => _offerSubscriptionsRepository.GetCompanyAssignedOfferSubscriptionDataForCompanyUserAsync(offerSubscription.Id, _companyId)) .MustHaveHappenedOnceExactly(); A.CallTo(() => _offerSubscriptionsRepository.AttachAndModifyOfferSubscription(offerSubscription.Id, A>._)) .MustHaveHappenedOnceExactly(); @@ -2658,15 +2654,15 @@ private void SetupRepositories() var offerSubscription = _fixture.Create(); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingServiceId), _identity.UserId, A.That.Matches(x => x == OfferTypeId.SERVICE))) - .Returns((_identity.CompanyId, offerSubscription)); + A.That.Matches(x => x == _existingServiceId), _companyUserId, A.That.Matches(x => x == OfferTypeId.SERVICE))) + .Returns((_companyId, offerSubscription)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingServiceId), _identity.UserId, A.That.Not.Matches(x => x == OfferTypeId.SERVICE))) - .Returns((_identity.CompanyId, (OfferSubscription?)null)); - A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync(A.That.Not.Matches(x => x == _existingServiceId), _identity.UserId, A._)) - .Returns((_identity.CompanyId, (OfferSubscription?)null)); + A.That.Matches(x => x == _existingServiceId), _companyUserId, A.That.Not.Matches(x => x == OfferTypeId.SERVICE))) + .Returns((_companyId, (OfferSubscription?)null)); + A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync(A.That.Not.Matches(x => x == _existingServiceId), _companyUserId, A._)) + .Returns((_companyId, (OfferSubscription?)null)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingServiceId), A.That.Not.Matches(x => x == _identity.UserId), + A.That.Matches(x => x == _existingServiceId), A.That.Not.Matches(x => x == _companyUserId), A._)) .Returns(((Guid companyId, OfferSubscription? offerSubscription))default); @@ -2683,9 +2679,9 @@ private void SetupRepositories() A.CallTo(() => _consentRepository.GetConsentDetailData(A._, A.That.Not.Matches(x => x == OfferTypeId.SERVICE))) .Returns((ConsentDetailData?)null); - A.CallTo(() => _companyRepository.GetCompanyNameUntrackedAsync(_identity.CompanyId)) + A.CallTo(() => _companyRepository.GetCompanyNameUntrackedAsync(_companyId)) .Returns((true, "the company")); - A.CallTo(() => _companyRepository.GetCompanyNameUntrackedAsync(A.That.Not.Matches(x => x == _identity.CompanyId))) + A.CallTo(() => _companyRepository.GetCompanyNameUntrackedAsync(A.That.Not.Matches(x => x == _companyId))) .Returns(new ValueTuple()); A.CallTo(() => _consentAssignedOfferSubscriptionRepository.GetConsentAssignedOfferSubscriptionsForSubscriptionAsync(A._, A>.That.Not.Matches(x => x.Any(y => y == _existingAgreementForSubscriptionId)))) diff --git a/tests/marketplace/Offers.Library.Tests/Service/OfferSetupServiceTests.cs b/tests/marketplace/Offers.Library.Tests/Service/OfferSetupServiceTests.cs index 20f7edd633..6b9ab38312 100644 --- a/tests/marketplace/Offers.Library.Tests/Service/OfferSetupServiceTests.cs +++ b/tests/marketplace/Offers.Library.Tests/Service/OfferSetupServiceTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -43,10 +42,11 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Offers.Library.Tests.Service; public class OfferSetupServiceTests { private const string Bpn = "CAXSDUMMYCATENAZZ"; - private const string IamUserId = "9aae7a3b-b188-4a42-b46b-fb2ea5f47668"; private static readonly Guid CompanyUserCompanyId = new("395f955b-f11b-4a74-ab51-92a526c1973a"); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, CompanyUserCompanyId); + private readonly IIdentityData _identity; + private readonly Guid _companyUserId = Guid.NewGuid(); + private readonly Guid _companyId = Guid.NewGuid(); private readonly Guid _existingServiceId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); private readonly Guid _validSubscriptionId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); private readonly Guid _pendingSubscriptionId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47663"); @@ -98,7 +98,11 @@ public OfferSetupServiceTests() _mailingService = A.Fake(); _technicalUserProfileService = A.Fake(); _offerSubscriptionProcessService = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(_companyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(_companyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_appSubscriptionDetailRepository); @@ -321,7 +325,8 @@ public async Task AutoSetup_WithValidDataAndUserWithoutMail_NoMailIsSend() }; var data = new OfferAutoSetupData(_pendingSubscriptionId, "https://new-url.com/"); - A.CallTo(() => _identityService.IdentityData).Returns(new IdentityData(IamUserId, _companyUserWithoutMailId, IdentityTypeId.COMPANY_USER, _companyUserWithoutMailCompanyId)); + A.CallTo(() => _identity.IdentityId).Returns(_companyUserWithoutMailId); + A.CallTo(() => _identity.CompanyId).Returns(_companyUserWithoutMailCompanyId); // Act var result = await _sut.AutoSetupOfferAsync(data, companyAdminRoles, OfferTypeId.SERVICE, "https://base-address.com", serviceManagerRoles).ConfigureAwait(false); @@ -366,7 +371,7 @@ public async Task AutoSetup_WithNotExistingOfferSubscriptionId_ThrowsException() // Arrange SetupAutoSetup(OfferTypeId.APP); var data = new OfferAutoSetupData(Guid.NewGuid(), "https://new-url.com/"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(data.RequestId, _identity.CompanyId, OfferTypeId.SERVICE)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(data.RequestId, _companyId, OfferTypeId.SERVICE)) .Returns((OfferSubscriptionTransferData?)null); // Act @@ -401,7 +406,8 @@ public async Task AutoSetup_WithUserNotFromProvidingCompany_ThrowsException() // Arrange SetupAutoSetup(OfferTypeId.APP); var data = new OfferAutoSetupData(_pendingSubscriptionId, "https://new-url.com/"); - A.CallTo(() => _identityService.IdentityData).Returns(new IdentityData(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid())); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); // Act async Task Action() => await _sut.AutoSetupOfferAsync(data, Enumerable.Empty(), OfferTypeId.SERVICE, "https://base-address.com", Enumerable.Empty()); @@ -666,7 +672,7 @@ public async Task StartAutoSetupAsync_WithNotExistingOfferSubscription_ThrowsNot // Arrange var offerSubscriptionId = Guid.NewGuid(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyId, offerTypeId)) .Returns((OfferSubscriptionTransferData?)null); // Act @@ -688,7 +694,7 @@ public async Task StartAutoSetupAsync_WithWrongStatue_ThrowsConflictException(Of .Create(); var offerSubscriptionId = Guid.NewGuid(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.UserId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyUserId, offerTypeId)) .Returns(transferData); // Act @@ -712,7 +718,7 @@ public async Task StartAutoSetupAsync_WithNotProvidingCompany_ThrowsForbiddenExc .Create(); var offerSubscriptionId = Guid.NewGuid(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyId, offerTypeId)) .Returns(transferData); // Act @@ -737,7 +743,7 @@ public async Task StartAutoSetupAsync_WithMultipleInstancesForSingleInstance_Thr .Create(); var offerSubscriptionId = Guid.NewGuid(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyId, offerTypeId)) .Returns(transferData); // Act @@ -763,7 +769,7 @@ public async Task StartAutoSetupAsync_WithValidSingleInstance_ThrowsConflictExce var offerSubscriptionId = Guid.NewGuid(); var process = _fixture.Create(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyId, offerTypeId)) .Returns(transferData); A.CallTo(() => _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscriptionId, @@ -800,7 +806,7 @@ public async Task StartAutoSetupAsync_WithValidMultiInstance_ReturnsExpected(Off var offerSubscriptionId = Guid.NewGuid(); var process = _fixture.Create(); var data = new OfferAutoSetupData(offerSubscriptionId, "https://www.test.de"); - A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _identity.CompanyId, offerTypeId)) + A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany(offerSubscriptionId, _companyId, offerTypeId)) .Returns(transferData); A.CallTo(() => _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscriptionId, @@ -931,7 +937,7 @@ public async Task CreateSingleInstanceSubscriptionDetail_WithValidData_ReturnsEx .With(x => x.Status, OfferSubscriptionStatusId.PENDING) .With(x => x.InstanceData, new ValueTuple(true, "https://www.test.de")) .With(x => x.AppInstanceIds, new[] { Guid.NewGuid() }) - .With(x => x.ProviderCompanyId, _identity.CompanyId) + .With(x => x.ProviderCompanyId, _companyId) .Create(); var detail = new AppSubscriptionDetail(Guid.NewGuid(), offerSubscriptionId); A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionActivationDataByIdAsync(offerSubscriptionId)) @@ -1134,10 +1140,10 @@ public async Task CreateTechnicalUser_WithTechnicalUserNeeded_ReturnsExpected(st public async Task ActivateSubscription_WithValidData_ReturnsExpected() { // Arrange - var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _identity.UserId, default); + var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _companyUserId, default); var processStep = new ProcessStep(Guid.NewGuid(), ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, ProcessStepStatusId.TODO, Guid.NewGuid(), DateTimeOffset.Now); - A.CallTo(() => _offerSubscriptionsRepository.CheckOfferSubscriptionForProvider(offerSubscription.Id, _identity.CompanyId)) + A.CallTo(() => _offerSubscriptionsRepository.CheckOfferSubscriptionForProvider(offerSubscription.Id, _companyId)) .Returns(true); A.CallTo(() => _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscription.Id, ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, null, true)) .Returns(new ManualProcessStepData(ProcessStepTypeId.TRIGGER_ACTIVATE_SUBSCRIPTION, _fixture.Create(), new[] { processStep }, _portalRepositories)); @@ -1178,7 +1184,7 @@ public async Task ActivateSingleInstanceSubscription_WithNotExistingOfferSubscri public async Task ActivateSingleInstanceSubscription_WithValidData_ReturnsExpected(string? requesterEmail) { // Arrange - var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _identity.UserId, default); + var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _companyUserId, default); var subscriptionProcessData = new List { new(offerSubscription.Id, "https://www.test.de") @@ -1188,7 +1194,7 @@ public async Task ActivateSingleInstanceSubscription_WithValidData_ReturnsExpect A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>._, A._, A._, A._, A._)) .Returns(new[] { Guid.NewGuid() }.AsFakeIAsyncEnumerable(out var createNotificationsEnumerator)); A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionActivationDataByIdAsync(offerSubscription.Id)) - .Returns(new SubscriptionActivationData(_validOfferId, OfferSubscriptionStatusId.PENDING, OfferTypeId.APP, "Test App", "Stark Industries", _identity.CompanyId, requesterEmail, "Tony", "Stark", Guid.NewGuid(), new(true, null), new[] { Guid.NewGuid() }, true, Guid.NewGuid(), _identity.CompanyId, null, Enumerable.Empty())); + .Returns(new SubscriptionActivationData(_validOfferId, OfferSubscriptionStatusId.PENDING, OfferTypeId.APP, "Test App", "Stark Industries", _companyId, requesterEmail, "Tony", "Stark", Guid.NewGuid(), new(true, null), new[] { Guid.NewGuid() }, true, Guid.NewGuid(), _companyId, null, Enumerable.Empty())); A.CallTo(() => _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscription.Id, ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, null, true)) .Returns(new ManualProcessStepData(ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, _fixture.Create(), new[] { processStep }, _portalRepositories)); @@ -1221,7 +1227,7 @@ public async Task ActivateSingleInstanceSubscription_WithValidData_ReturnsExpect A.CallTo(() => _provisioningManager.EnableClient(A._)).MustNotHaveHappened(); - A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>.That.Matches(x => x.Count() == 1 && x.Single().Item2 == notificationTypeId), _identity.CompanyId, A._, offerSubscription.Id.ToString(), null)) + A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>.That.Matches(x => x.Count() == 1 && x.Single().Item2 == notificationTypeId), _companyId, A._, offerSubscription.Id.ToString(), null)) .MustHaveHappenedOnceExactly(); A.CallTo(() => createNotificationsEnumerator.MoveNextAsync()).MustHaveHappened(2, Times.Exactly); @@ -1243,7 +1249,7 @@ public async Task ActivateSingleInstanceSubscription_WithValidData_ReturnsExpect public async Task ActivateMultipleInstancesSubscription_WithValidData_ReturnsExpected(string? requesterEmail) { // Arrange - var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _identity.UserId, default); + var offerSubscription = new OfferSubscription(Guid.NewGuid(), _validOfferId, CompanyUserCompanyId, OfferSubscriptionStatusId.PENDING, _companyUserId, default); var subscriptionProcessData = new List { new(offerSubscription.Id, "https://www.test.de") @@ -1256,7 +1262,7 @@ public async Task ActivateMultipleInstancesSubscription_WithValidData_ReturnsExp A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>._, A._, A._, A._, A._)) .Returns(new[] { Guid.NewGuid() }.AsFakeIAsyncEnumerable(out var createNotificationsEnumerator)); A.CallTo(() => _offerSubscriptionsRepository.GetSubscriptionActivationDataByIdAsync(offerSubscription.Id)) - .Returns(new SubscriptionActivationData(_validOfferId, OfferSubscriptionStatusId.PENDING, OfferTypeId.APP, "Test App", "Stark Industries", _identity.CompanyId, requesterEmail, "Tony", "Stark", Guid.NewGuid(), new(false, null), new[] { Guid.NewGuid() }, true, Guid.NewGuid(), _identity.CompanyId, clientClientId, serviceAccountClientIds)); + .Returns(new SubscriptionActivationData(_validOfferId, OfferSubscriptionStatusId.PENDING, OfferTypeId.APP, "Test App", "Stark Industries", _companyId, requesterEmail, "Tony", "Stark", Guid.NewGuid(), new(false, null), new[] { Guid.NewGuid() }, true, Guid.NewGuid(), _companyId, clientClientId, serviceAccountClientIds)); A.CallTo(() => _offerSubscriptionProcessService.VerifySubscriptionAndProcessSteps(offerSubscription.Id, ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, null, true)) .Returns(new ManualProcessStepData(ProcessStepTypeId.ACTIVATE_SUBSCRIPTION, _fixture.Create(), new[] { processStep }, _portalRepositories)); @@ -1291,7 +1297,7 @@ public async Task ActivateMultipleInstancesSubscription_WithValidData_ReturnsExp A.CallTo(() => _provisioningManager.EnableClient(A.That.Matches(x => serviceAccountClientIds.Contains(x)))).MustHaveHappened(serviceAccountClientIds.Length, Times.Exactly) ); - A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>.That.Matches(x => x.Count() == 1 && x.Single().Item2 == notificationTypeId), _identity.CompanyId, A._, offerSubscription.Id.ToString(), null)) + A.CallTo(() => _notificationService.CreateNotificationsWithExistenceCheck(A>._, null, A>.That.Matches(x => x.Count() == 1 && x.Single().Item2 == notificationTypeId), _companyId, A._, offerSubscription.Id.ToString(), null)) .MustHaveHappenedOnceExactly(); A.CallTo(() => createNotificationsEnumerator.MoveNextAsync()).MustHaveHappened(2, Times.Exactly); @@ -1405,10 +1411,10 @@ private IAsyncEnumerator SetupAutoSetup(OfferTypeId offerTypeId, OfferSubs A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany( _validSubscriptionId, - _identity.CompanyId, + _companyId, A._)) .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.ACTIVE, true, "Company", - _identity.CompanyId, _identity.UserId, _existingServiceId, offerTypeId, "Test Service", + _companyId, _companyUserId, _existingServiceId, offerTypeId, "Test Service", Bpn, "user@email.com", "Tony", "Gilbert", (isSingleInstance, "https://test.de"), new[] { Guid.NewGuid() }, _salesManagerId)); @@ -1417,37 +1423,37 @@ private IAsyncEnumerator SetupAutoSetup(OfferTypeId offerTypeId, OfferSubs _companyUserWithoutMailCompanyId, A._)) .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.PENDING, true, - "Company", _identity.CompanyId, _identity.UserId, _existingServiceId, offerTypeId, "Test Service", + "Company", _companyId, _companyUserId, _existingServiceId, offerTypeId, "Test Service", Bpn, null, null, null, (isSingleInstance, "https://test.de"), new[] { Guid.NewGuid() }, _salesManagerId)); A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany( _pendingSubscriptionId, - _identity.CompanyId, + _companyId, A._)) - .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.PENDING, true, "Company", _identity.CompanyId, - _identity.UserId, + .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.PENDING, true, "Company", _companyId, + _companyUserId, _existingServiceId, offerTypeId, "Test Service", Bpn, "user@email.com", "Tony", "Gilbert", (isSingleInstance, "https://test.de"), new[] { Guid.NewGuid() }, _salesManagerId)); A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany( _offerIdWithMultipleInstances, - _identity.CompanyId, + _companyId, A._)) .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.PENDING, true, "Company", - _identity.CompanyId, _identity.UserId, _existingServiceId, offerTypeId, "Test Service", + _companyId, _companyUserId, _existingServiceId, offerTypeId, "Test Service", Bpn, "user@email.com", "Tony", "Gilbert", (isSingleInstance, null), Enumerable.Empty(), null)); A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany( A.That.Not.Matches(x => x == _pendingSubscriptionId || x == _validSubscriptionId || x == _offerIdWithMultipleInstances), - _identity.CompanyId, + _companyId, A._)) .Returns((OfferSubscriptionTransferData?)null); A.CallTo(() => _offerSubscriptionsRepository.GetOfferDetailsAndCheckProviderCompany( _pendingSubscriptionId, - A.That.Not.Matches(x => x == _identity.CompanyId || x == _companyUserWithoutMailCompanyId), + A.That.Not.Matches(x => x == _companyId || x == _companyUserWithoutMailCompanyId), A._)) .Returns(new OfferSubscriptionTransferData(OfferSubscriptionStatusId.PENDING, false, string.Empty, Guid.NewGuid(), Guid.NewGuid(), _existingServiceId, OfferTypeId.APP, "Test Service", diff --git a/tests/marketplace/Offers.Library.Tests/Service/OfferSubscriptionServiceTests.cs b/tests/marketplace/Offers.Library.Tests/Service/OfferSubscriptionServiceTests.cs index 6d3d6d888f..f4fc499a10 100644 --- a/tests/marketplace/Offers.Library.Tests/Service/OfferSubscriptionServiceTests.cs +++ b/tests/marketplace/Offers.Library.Tests/Service/OfferSubscriptionServiceTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -40,7 +39,7 @@ public class OfferSubscriptionServiceTests private readonly Guid _notAssignedCompanyId; private readonly Guid _noBpnSetCompanyId; - private readonly IdentityData _identity; + private readonly IIdentityData _identity; private readonly Guid _companyUserId; private readonly Guid _companyId; private readonly Guid _existingActiveSubscriptionCompanyId; @@ -79,7 +78,6 @@ public OfferSubscriptionServiceTests() _companyUserId = _fixture.Create(); _companyId = _fixture.Create(); - _identity = new IdentityData(_fixture.Create(), _companyUserId, IdentityTypeId.COMPANY_USER, _companyId); _existingOfferIdWithoutProviderEmail = _fixture.Create(); _existingActiveSubscriptionCompanyId = _fixture.Create(); _existingInactiveSubscriptionCompanyId = _fixture.Create(); @@ -93,7 +91,11 @@ public OfferSubscriptionServiceTests() _userRoleId = _fixture.Create(); _offerAgreementIds = _fixture.CreateMany().ToImmutableArray(); _validConsentData = _offerAgreementIds.Select(x => new OfferAgreementConsentData(x, ConsentStatusId.ACTIVE)); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _portalRepositories = A.Fake(); @@ -317,7 +319,7 @@ public async Task AddOfferSubscription_NotAssignedCompany_ThrowsException(OfferT new UserRoleConfig("portal", new [] { "App Manager", "Sales Manager" })} : new[]{ new UserRoleConfig("portal", new [] { "Service Manager", "Sales Manager" })}; var serviceManagerRoles = new[] { new UserRoleConfig("portal", new[] { "Service Manager" }) }; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = _notAssignedCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(_notAssignedCompanyId); // Act async Task Action() => await _sut.AddOfferSubscriptionAsync(_existingOfferId, Enumerable.Empty(), offerTypeId, BasePortalUrl, subscriptionManagerRoles, serviceManagerRoles).ConfigureAwait(false); @@ -444,7 +446,7 @@ public async Task AddOfferSubscription_WithoutBuisnessPartnerNumber_ThrowsConfli new UserRoleConfig("portal", new [] { "App Manager", "Sales Manager" })} : new[]{ new UserRoleConfig("portal", new [] { "Service Manager", "Sales Manager" })}; var serviceManagerRoles = new[] { new UserRoleConfig("portal", new[] { "Service Manager" }) }; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = _noBpnSetCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(_noBpnSetCompanyId); async Task Action() => await _sut.AddOfferSubscriptionAsync(_existingOfferId, Enumerable.Empty(), offerTypeId, BasePortalUrl, subscriptionManagerRoles, serviceManagerRoles).ConfigureAwait(false); // Assert @@ -485,7 +487,7 @@ public async Task AddOfferSubscription_WithExistingActiveSubscription_ThrowsConf var subscriptionManagerRoles = new[]{ new UserRoleConfig("portal", new [] { "App Manager", "Sales Manager" })}; var serviceManagerRoles = new[] { new UserRoleConfig("portal", new[] { "Service Manager" }) }; - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = _existingActiveSubscriptionCompanyId }); + A.CallTo(() => _identity.CompanyId).Returns(_existingActiveSubscriptionCompanyId); A.CallTo(() => _offerSubscriptionsRepository.CheckPendingOrActiveSubscriptionExists(_existingOfferId, _existingActiveSubscriptionCompanyId, A._)) .Returns(true); @@ -527,15 +529,15 @@ private void SetupRepositories() .With(x => x.Id, _existingOfferId) .Create(); - A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_identity.CompanyId, _identity.UserId)) + A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_identity.CompanyId, _identity.IdentityId)) .Returns(new CompanyInformationData(_companyId, "The Company", "DE", "BPM00000001", "test@mail.com")); - A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_notAssignedCompanyId, _identity.UserId)) + A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_notAssignedCompanyId, _identity.IdentityId)) .Returns((CompanyInformationData?)null); - A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_noBpnSetCompanyId, _identity.UserId)) + A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_noBpnSetCompanyId, _identity.IdentityId)) .Returns(new CompanyInformationData(_companyId, "The Company", "DE", null, "test@mail.com")); - A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_existingActiveSubscriptionCompanyId, _identity.UserId)) + A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_existingActiveSubscriptionCompanyId, _identity.IdentityId)) .Returns(new CompanyInformationData(_existingActiveSubscriptionCompanyId, "The Company", "DE", "BPM00000001", "test@mail.com")); - A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_existingInactiveSubscriptionCompanyId, _identity.UserId)) + A.CallTo(() => _companyRepository.GetOwnCompanyInformationAsync(_existingInactiveSubscriptionCompanyId, _identity.IdentityId)) .Returns(new CompanyInformationData(_existingInactiveSubscriptionCompanyId, "The Company", "DE", "BPM00000001", "test@mail.com")); A.CallTo(() => _userRepository.GetServiceProviderCompanyUserWithRoleIdAsync(A.That.Matches(x => x == _existingOfferId), A>.That.IsSameSequenceAs(new[] { _userRoleId }))) .Returns(new[] { _companyUserId, _salesManagerId }.ToAsyncEnumerable()); @@ -580,14 +582,14 @@ private void SetupRepositories() A._)) .Returns((SubscriptionDetailData?)null); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingOfferId), A.That.Matches(x => x == _identity.UserId), A._)) + A.That.Matches(x => x == _existingOfferId), A.That.Matches(x => x == _identity.IdentityId), A._)) .Returns((_companyId, offerSubscription)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Not.Matches(x => x == _existingOfferId), A.That.Matches(x => x == _identity.UserId), + A.That.Not.Matches(x => x == _existingOfferId), A.That.Matches(x => x == _identity.IdentityId), A._)) .Returns((_companyId, null)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingOfferId), A.That.Not.Matches(x => x == _identity.UserId), + A.That.Matches(x => x == _existingOfferId), A.That.Not.Matches(x => x == _identity.IdentityId), A._)) .Returns(((Guid companyId, OfferSubscription? offerSubscription))default); diff --git a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceBusinessLogicTests.cs b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceBusinessLogicTests.cs index 129c4acb9f..7668b03220 100644 --- a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceBusinessLogicTests.cs +++ b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -44,10 +43,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Services.Service.Tests.BusinessLog public class ServiceBusinessLogicTests { - private const string IamUserId = "502dabcf-01c7-47d9-a88e-0be4279097b5"; private static readonly Guid CompanyUserCompanyId = new("395f955b-f11b-4a74-ab51-92a526c1973a"); - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, CompanyUserCompanyId); + private readonly IIdentityData _identity; private readonly Guid _existingServiceId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); private readonly Guid _existingServiceWithFailingAutoSetupId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); private readonly Guid _validSubscriptionId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47662"); @@ -75,10 +73,8 @@ public ServiceBusinessLogicTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); - var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, CompanyUserCompanyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER) - { - UserEntityId = IamUserId - }; + var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, CompanyUserCompanyId, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER); + _companyUser = _fixture.Build() .With(u => u.Identity, identity) .Create(); @@ -94,8 +90,12 @@ public ServiceBusinessLogicTests() _offerSubscriptionService = A.Fake(); _offerService = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); _logger = A.Fake>(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); _fixture.Inject(_identityService); @@ -687,14 +687,14 @@ private void SetupRepositories() A._)) .Returns((SubscriptionDetailData?)null); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingServiceId), _identity.UserId, A._)) + A.That.Matches(x => x == _existingServiceId), _identity.IdentityId, A._)) .Returns((_identity.CompanyId, offerSubscription)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Not.Matches(x => x == _existingServiceId), _identity.UserId, + A.That.Not.Matches(x => x == _existingServiceId), _identity.IdentityId, A._)) .Returns((_identity.CompanyId, (OfferSubscription?)null)); A.CallTo(() => _offerSubscriptionsRepository.GetCompanyIdWithAssignedOfferForCompanyUserAndSubscriptionAsync( - A.That.Matches(x => x == _existingServiceId), A.That.Not.Matches(x => x == _identity.UserId), + A.That.Matches(x => x == _existingServiceId), A.That.Not.Matches(x => x == _identity.IdentityId), A._)) .Returns(((Guid companyId, OfferSubscription? offerSubscription))default); diff --git a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs index cde6b64ae7..3d1e34af4f 100644 --- a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs +++ b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -45,11 +44,10 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Services.Service.Tests.BusinessLog public class ServiceReleaseBusinessLogicTest { - private const string IamUserId = "1cb10522-bd03-4214-bd85-de8122acf212"; private static readonly Guid CompanyUserId = Guid.NewGuid(); private static readonly Guid CompanyUserCompanyId = Guid.NewGuid(); - private readonly IdentityData _identity = new(IamUserId, CompanyUserId, IdentityTypeId.COMPANY_USER, CompanyUserCompanyId); + private readonly IIdentityData _identity; private readonly Guid _notExistingServiceId = Guid.NewGuid(); private readonly Guid _existingServiceId = new("9aae7a3b-b188-4a42-b46b-fb2ea5f47661"); private readonly Guid _activeServiceId = Guid.NewGuid(); @@ -80,6 +78,10 @@ public ServiceReleaseBusinessLogicTest() _technicalUserProfileRepository = A.Fake(); _identityService = A.Fake(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(CompanyUserId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(CompanyUserCompanyId); A.CallTo(() => _identityService.IdentityData).Returns(_identity); SetupRepositories(); diff --git a/tests/marketplace/Services.Service.Tests/Controllers/ServiceChangeControllerTest.cs b/tests/marketplace/Services.Service.Tests/Controllers/ServiceChangeControllerTest.cs index c1e4b2232d..7420c90aec 100644 --- a/tests/marketplace/Services.Service.Tests/Controllers/ServiceChangeControllerTest.cs +++ b/tests/marketplace/Services.Service.Tests/Controllers/ServiceChangeControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -32,7 +31,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Services.Service.Tests.Controllers public class ServiceChangeControllerTest { - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly ServiceChangeController _controller; private readonly IServiceChangeBusinessLogic _logic; @@ -40,9 +39,13 @@ public class ServiceChangeControllerTest public ServiceChangeControllerTest() { _fixture = new Fixture(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _logic = A.Fake(); - this._controller = new ServiceChangeController(_logic); - _controller.AddControllerContextWithClaim(_identity.UserEntityId, _identity); + _controller = new ServiceChangeController(_logic); + _controller.AddControllerContextWithClaim(_identity); } [Fact] @@ -52,7 +55,7 @@ public async Task DeactivateApp_ReturnsNoContent() var serviceId = _fixture.Create(); //Act - var result = await this._controller.DeactivateService(serviceId).ConfigureAwait(false); + var result = await _controller.DeactivateService(serviceId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.DeactivateOfferByServiceIdAsync(serviceId)).MustHaveHappenedOnceExactly(); diff --git a/tests/marketplace/Services.Service.Tests/Controllers/ServiceControllerTest.cs b/tests/marketplace/Services.Service.Tests/Controllers/ServiceControllerTest.cs index 31fe276622..6acd1b3c17 100644 --- a/tests/marketplace/Services.Service.Tests/Controllers/ServiceControllerTest.cs +++ b/tests/marketplace/Services.Service.Tests/Controllers/ServiceControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -40,7 +39,7 @@ public class ServiceControllerTest { private const string AccessToken = "THISISTHEACCESSTOKEN"; private static readonly Guid ServiceId = new("4C1A6851-D4E7-4E10-A011-3732CD045453"); - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly IServiceBusinessLogic _logic; private readonly ServicesController _controller; @@ -49,7 +48,11 @@ public ServiceControllerTest() { _fixture = new Fixture(); _logic = A.Fake(); - this._controller = new ServicesController(_logic); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); + _controller = new ServicesController(_logic); _controller.AddControllerContextWithClaimAndBearer(AccessToken, _identity); } @@ -62,7 +65,7 @@ public async Task GetAllActiveServicesAsync_ReturnsExpectedId() .Returns(paginationResponse); //Act - var result = await this._controller.GetAllActiveServicesAsync().ConfigureAwait(false); + var result = await _controller.GetAllActiveServicesAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllActiveServicesAsync(0, 15, null, null)).MustHaveHappenedOnceExactly(); @@ -81,7 +84,7 @@ public async Task AddServiceSubscriptionWithConsent_ReturnsExpectedId() //Act var serviceId = Guid.NewGuid(); - var result = await this._controller.AddServiceSubscription(serviceId, consentData).ConfigureAwait(false); + var result = await _controller.AddServiceSubscription(serviceId, consentData).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AddServiceSubscription(serviceId, consentData)).MustHaveHappenedOnceExactly(); @@ -99,7 +102,7 @@ public async Task GetServiceDetails_ReturnsExpectedId() .Returns(serviceDetailData); //Act - var result = await this._controller.GetServiceDetails(serviceId).ConfigureAwait(false); + var result = await _controller.GetServiceDetails(serviceId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetServiceDetailsAsync(serviceId, "en")).MustHaveHappenedOnceExactly(); @@ -117,7 +120,7 @@ public async Task GetSubscriptionDetail_ReturnsExpectedId() .Returns(detailData); //Act - var result = await this._controller.GetSubscriptionDetail(subscriptionId).ConfigureAwait(false); + var result = await _controller.GetSubscriptionDetail(subscriptionId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetSubscriptionDetailAsync(subscriptionId)).MustHaveHappenedOnceExactly(); @@ -134,7 +137,7 @@ public async Task GetServiceAgreement_ReturnsExpected() .Returns(agreementData); //Act - var result = await this._controller.GetServiceAgreement(ServiceId).ToListAsync().ConfigureAwait(false); + var result = await _controller.GetServiceAgreement(ServiceId).ToListAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetServiceAgreement(ServiceId)).MustHaveHappenedOnceExactly(); @@ -151,7 +154,7 @@ public async Task GetServiceAgreementConsentDetail_ReturnsExpected() .Returns(consentDetailData); //Act - var result = await this._controller.GetServiceAgreementConsentDetail(consentId).ConfigureAwait(false); + var result = await _controller.GetServiceAgreementConsentDetail(consentId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetServiceConsentDetailDataAsync(consentId)).MustHaveHappenedOnceExactly(); @@ -163,9 +166,11 @@ public async Task AutoSetupService_ReturnsExpected() { //Arrange var offerSubscriptionId = Guid.NewGuid(); - var userRoleData = new List(); - userRoleData.Add("Sales Manager"); - userRoleData.Add("IT Manager"); + var userRoleData = new[] + { + "Sales Manager", + "IT Manager" + }; var data = new OfferAutoSetupData(offerSubscriptionId, "https://test.de"); var responseData = new OfferAutoSetupResponseData( new TechnicalUserInfoData(Guid.NewGuid(), userRoleData, "abcPW", "sa1"), @@ -175,7 +180,7 @@ public async Task AutoSetupService_ReturnsExpected() .Returns(responseData); //Act - var result = await this._controller.AutoSetupService(data).ConfigureAwait(false); + var result = await _controller.AutoSetupService(data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.AutoSetupServiceAsync(data)).MustHaveHappenedOnceExactly(); @@ -196,7 +201,7 @@ public async Task GetCompanyProvidedServiceSubscriptionStatusesForCurrentUserAsy .Returns(pagination); //Act - var result = await this._controller.GetCompanyProvidedServiceSubscriptionStatusesForCurrentUserAsync(offerId: offerId).ConfigureAwait(false); + var result = await _controller.GetCompanyProvidedServiceSubscriptionStatusesForCurrentUserAsync(offerId: offerId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanyProvidedServiceSubscriptionStatusesForUserAsync(0, 15, null, null, offerId)).MustHaveHappenedOnceExactly(); @@ -216,7 +221,7 @@ public async Task GetServiceDocumentContentAsync_ReturnsExpected() .Returns((content, "image/png", fileName)); //Act - var result = await this._controller.GetServiceDocumentContentAsync(serviceId, documentId, CancellationToken.None).ConfigureAwait(false); + var result = await _controller.GetServiceDocumentContentAsync(serviceId, documentId, CancellationToken.None).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetServiceDocumentContentAsync(A._, A._, A._)).MustHaveHappenedOnceExactly(); @@ -235,7 +240,7 @@ public async Task GetCompanyProvidedServiceStatusDataAsync_ReturnsExpectedCount( .Returns(paginationResponse); //Act - var result = await this._controller.GetCompanyProvidedServiceStatusDataAsync().ConfigureAwait(false); + var result = await _controller.GetCompanyProvidedServiceStatusDataAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanyProvidedServiceStatusDataAsync(0, 15, null, null, null)).MustHaveHappenedOnceExactly(); @@ -250,7 +255,7 @@ public async Task StartAutoSetupProcess_ReturnsExpected() var data = new OfferAutoSetupData(offerSubscriptionId, "https://test.de"); //Act - var result = await this._controller.StartAutoSetupServiceProcess(data).ConfigureAwait(false); + var result = await _controller.StartAutoSetupServiceProcess(data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.StartAutoSetupAsync(data)).MustHaveHappenedOnceExactly(); @@ -268,7 +273,7 @@ public async Task GetSubscriptionDetailForProvider_ReturnsExpected() .Returns(data); // Act - var result = await this._controller.GetSubscriptionDetailForProvider(serviceId, subscriptionId).ConfigureAwait(false); + var result = await _controller.GetSubscriptionDetailForProvider(serviceId, subscriptionId).ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetSubscriptionDetailForProvider(serviceId, subscriptionId)).MustHaveHappenedOnceExactly(); @@ -286,7 +291,7 @@ public async Task GetSubscriptionDetailForSubscriber_ReturnsExpected() .Returns(data); // Act - var result = await this._controller.GetSubscriptionDetailForSubscriber(serviceId, subscriptionId).ConfigureAwait(false); + var result = await _controller.GetSubscriptionDetailForSubscriber(serviceId, subscriptionId).ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetSubscriptionDetailForSubscriber(serviceId, subscriptionId)).MustHaveHappenedOnceExactly(); @@ -305,7 +310,7 @@ public async Task GetCompanySubscribedServiceSubscriptionStatusesForCurrentUserA .Returns(pagination); //Act - var result = await this._controller.GetCompanySubscribedServiceSubscriptionStatusesForUserAsync().ConfigureAwait(false); + var result = await _controller.GetCompanySubscribedServiceSubscriptionStatusesForUserAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetCompanySubscribedServiceSubscriptionStatusesForUserAsync(0, 15)).MustHaveHappenedOnceExactly(); @@ -321,7 +326,7 @@ public async Task UnsubscribeCompanyServiceSubscription_ReturnsNoContent() var serviceId = _fixture.Create(); //Act - var result = await this._controller.UnsubscribeCompanyServiceSubscriptionAsync(serviceId).ConfigureAwait(false); + var result = await _controller.UnsubscribeCompanyServiceSubscriptionAsync(serviceId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.UnsubscribeOwnCompanyServiceSubscriptionAsync(serviceId)).MustHaveHappenedOnceExactly(); diff --git a/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs b/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs index c3125ca193..a06ed07bf9 100644 --- a/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs +++ b/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -39,7 +38,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Services.Service.Tests.Controllers public class ServiceReleaseControllerTest { private const string AccessToken = "THISISTHEACCESSTOKEN"; - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private static readonly Guid ServiceId = new("4C1A6851-D4E7-4E10-A011-3732CD045453"); private readonly IFixture _fixture; private readonly IServiceReleaseBusinessLogic _logic; @@ -48,7 +47,11 @@ public ServiceReleaseControllerTest() { _fixture = new Fixture(); _logic = A.Fake(); - this._controller = new ServiceReleaseController(_logic); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); + _controller = new ServiceReleaseController(_logic); _controller.AddControllerContextWithClaimAndBearer(AccessToken, _identity); } @@ -61,7 +64,7 @@ public async Task GetServiceAgreementData_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetServiceAgreementDataAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetServiceAgreementDataAsync().ToListAsync().ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetServiceAgreementDataAsync()).MustHaveHappenedOnceExactly(); @@ -78,7 +81,7 @@ public async Task GetServiceDetailsByIdAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetServiceDetailsByIdAsync(serviceId).ConfigureAwait(false); + var result = await _controller.GetServiceDetailsByIdAsync(serviceId).ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetServiceDetailsByIdAsync(serviceId)).MustHaveHappenedOnceExactly(); @@ -94,7 +97,7 @@ public async Task GetServiceTypeData_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetServiceTypeDataAsync().ToListAsync().ConfigureAwait(false); + var result = await _controller.GetServiceTypeDataAsync().ToListAsync().ConfigureAwait(false); // Assert A.CallTo(() => _logic.GetServiceTypeDataAsync()).MustHaveHappenedOnceExactly(); @@ -112,7 +115,7 @@ public async Task GetServiceAgreementConsentByIdAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetServiceAgreementConsentByIdAsync(serviceId).ConfigureAwait(false); + var result = await _controller.GetServiceAgreementConsentByIdAsync(serviceId).ConfigureAwait(false); // Assert result.Should().Be(data); @@ -130,7 +133,7 @@ public async Task GetServiceDetailsForStatusAsync_ReturnsExpectedResult() .Returns(data); //Act - var result = await this._controller.GetServiceDetailsForStatusAsync(serviceId).ConfigureAwait(false); + var result = await _controller.GetServiceDetailsForStatusAsync(serviceId).ConfigureAwait(false); // Assert result.Should().Be(data); @@ -150,7 +153,7 @@ public async Task SubmitOfferConsentToAgreementsAsync_ReturnsExpectedId() .Returns(Enumerable.Repeat(consentStatusData, 1)); //Act - var result = await this._controller.SubmitOfferConsentToAgreementsAsync(serviceId, offerAgreementConsentData).ConfigureAwait(false); + var result = await _controller.SubmitOfferConsentToAgreementsAsync(serviceId, offerAgreementConsentData).ConfigureAwait(false); //Assert A.CallTo(() => _logic.SubmitOfferConsentAsync(serviceId, offerAgreementConsentData)).MustHaveHappenedOnceExactly(); @@ -166,7 +169,7 @@ public async Task GetAllInReviewStatusServiceAsync_ReturnsExpectedCount() .Returns(paginationResponse); //Act - var result = await this._controller.GetAllInReviewStatusServiceAsync().ConfigureAwait(false); + var result = await _controller.GetAllInReviewStatusServiceAsync().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetAllInReviewStatusServiceAsync(0, 15, null, null, null, null)).MustHaveHappenedOnceExactly(); @@ -180,7 +183,7 @@ public async Task DeleteServiceDocumentsAsync_ReturnsExpectedCount() var documentId = Guid.NewGuid(); //Act - var result = await this._controller.DeleteServiceDocumentsAsync(documentId).ConfigureAwait(false); + var result = await _controller.DeleteServiceDocumentsAsync(documentId).ConfigureAwait(false); // Assert Assert.IsType(result); @@ -198,7 +201,7 @@ public async Task CreateServiceOffering_ReturnsExpectedId() .Returns(id); //Act - var result = await this._controller.CreateServiceOffering(serviceOfferingData).ConfigureAwait(false); + var result = await _controller.CreateServiceOffering(serviceOfferingData).ConfigureAwait(false); //Assert A.CallTo(() => _logic.CreateServiceOfferingAsync(serviceOfferingData)).MustHaveHappenedOnceExactly(); @@ -216,7 +219,7 @@ public async Task UpdateService_ReturnsExpected() .Returns(Task.CompletedTask); //Act - var result = await this._controller.UpdateService(serviceId, data).ConfigureAwait(false); + var result = await _controller.UpdateService(serviceId, data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.UpdateServiceAsync(serviceId, data)).MustHaveHappenedOnceExactly(); @@ -227,7 +230,7 @@ public async Task UpdateService_ReturnsExpected() public async Task SubmitService_ReturnsExpectedCount() { //Act - await this._controller.SubmitService(ServiceId).ConfigureAwait(false); + await _controller.SubmitService(ServiceId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.SubmitServiceAsync(ServiceId)).MustHaveHappenedOnceExactly(); @@ -240,7 +243,7 @@ public async Task ApproveServiceRequest_ReturnsNoContent() var serviceId = _fixture.Create(); //Act - var result = await this._controller.ApproveServiceRequest(serviceId).ConfigureAwait(false); + var result = await _controller.ApproveServiceRequest(serviceId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.ApproveServiceRequestAsync(serviceId)).MustHaveHappenedOnceExactly(); @@ -255,7 +258,7 @@ public async Task DeclineServiceRequest_ReturnsNoContent() var data = new OfferDeclineRequest("Just a test"); //Act - var result = await this._controller.DeclineServiceRequest(serviceId, data).ConfigureAwait(false); + var result = await _controller.DeclineServiceRequest(serviceId, data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.DeclineServiceRequestAsync(serviceId, data)).MustHaveHappenedOnceExactly(); @@ -270,7 +273,7 @@ public async Task UpdateServiceDocumentAsync_CallExpected() var file = FormFileHelper.GetFormFile("this is just a test", "superFile.pdf", "application/pdf"); // Act - await this._controller.UpdateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None).ConfigureAwait(false); + await _controller.UpdateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None).ConfigureAwait(false); // Assert A.CallTo(() => _logic.CreateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None)).MustHaveHappenedOnceExactly(); @@ -287,7 +290,7 @@ public async Task GetTechnicalUserProfiles_ReturnsExpectedCount() .Returns(data); //Act - var result = await this._controller.GetTechnicalUserProfiles(offerId).ConfigureAwait(false); + var result = await _controller.GetTechnicalUserProfiles(offerId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetTechnicalUserProfilesForOffer(offerId)).MustHaveHappenedOnceExactly(); @@ -302,7 +305,7 @@ public async Task UpdateTechnicalUserProfiles_ReturnsExpectedCount() var data = _fixture.CreateMany(5); //Act - var result = await this._controller.CreateAndUpdateTechnicalUserProfiles(offerId, data).ConfigureAwait(false); + var result = await _controller.CreateAndUpdateTechnicalUserProfiles(offerId, data).ConfigureAwait(false); //Assert A.CallTo(() => _logic.UpdateTechnicalUserProfiles(offerId, A>.That.Matches(x => x.Count() == 5))).MustHaveHappenedOnceExactly(); diff --git a/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs b/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs index 264fa80e74..fda6c0b215 100644 --- a/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs +++ b/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -40,8 +39,8 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Notifications.Service.Tests.Busine public class NotificationBusinessLogicTests { - private const string IamUserId = "3e8343f7-4fe5-4296-8312-f33aa6dbde5d"; - private readonly IdentityData _identity = new(IamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly Guid _identityId = Guid.NewGuid(); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly NotificationDetailData _notificationDetail; @@ -66,9 +65,12 @@ public NotificationBusinessLogicTests() _notificationRepository = A.Fake(); _userRepository = A.Fake(); + _identity = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(_identityId); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); _readNotificationDetails = _fixture.Build() .CreateMany(1); @@ -186,8 +188,7 @@ public async Task GetNotifications_WithFilters_CallsExpected() })); var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + A.CallTo(() => _identity.IdentityId).Returns(userId); var filter = _fixture.Create(); // Act @@ -223,8 +224,8 @@ public async Task GetNotificationDetailDataAsync_WithIdAndUser_ReturnsCorrectRes public async Task GetNotificationDetailDataAsync_WithNotMatchingUser_ThrowsForbiddenException() { // Arrange - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 @@ -295,7 +296,7 @@ public async Task GetNotificationCountDetailsAsync() new (false, true, NotificationTopicId.ACTION, 3), new (false, false, NotificationTopicId.ACTION, 2), }); - A.CallTo(() => _notificationRepository.GetCountDetailsForUserAsync(_identity.UserId)).Returns(data.AsAsyncEnumerable()); + A.CallTo(() => _notificationRepository.GetCountDetailsForUserAsync(_identityId)).Returns(data.AsAsyncEnumerable()); var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 @@ -352,8 +353,7 @@ public async Task SetNotificationToRead_WithNotMatchingNotification_NotFoundExce { MaxPageSize = 15 })); - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(identity); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); // Act async Task Act() => await sut.SetNotificationStatusAsync(randomNotificationId, true).ConfigureAwait(false); @@ -367,8 +367,8 @@ public async Task SetNotificationToRead_WithNotMatchingNotification_NotFoundExce public async Task SetNotificationToRead_WithNotExistingCompanyUser_ThrowsForbiddenException() { // Arrange - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 @@ -406,8 +406,8 @@ public async Task DeleteNotification_WithValidData_ExecutesSuccessfully() public async Task DeleteNotification_WithNotExistingCompanyUser_ThrowsForbiddenException() { // Arrange - var identity = _fixture.Create(); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 @@ -447,7 +447,7 @@ private void SetupRepositories() { SetupNotifications(); - A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, _identity.UserId)) + A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, _identityId)) .Returns((true, _notificationDetail)); A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync( @@ -455,7 +455,7 @@ private void SetupRepositories() .Returns(((bool, NotificationDetailData))default); A.CallTo(() => - _notificationRepository.CheckNotificationExistsByIdAndValidateReceiverAsync(_notificationDetail.Id, _identity.UserId)) + _notificationRepository.CheckNotificationExistsByIdAndValidateReceiverAsync(_notificationDetail.Id, _identityId)) .ReturnsLazily(() => (true, true, true)); A.CallTo(() => _notificationRepository.CheckNotificationExistsByIdAndValidateReceiverAsync( @@ -463,16 +463,16 @@ private void SetupRepositories() .Returns((false, false, true)); A.CallTo(() => _notificationRepository.CheckNotificationExistsByIdAndValidateReceiverAsync(_notificationDetail.Id, - A.That.Not.Matches(x => x == _identity.UserId))) + A.That.Not.Matches(x => x == _identityId))) .Returns((false, true, true)); - A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, _identity.UserId)) + A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, _identityId)) .Returns((true, _unreadNotificationDetails.First())); - A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, A.That.Not.Matches(x => x == _identity.UserId))) + A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(_notificationDetail.Id, A.That.Not.Matches(x => x == _identityId))) .Returns((false, _unreadNotificationDetails.First())); - A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(A.That.Not.Matches(x => x == _notificationDetail.Id), _identity.UserId)) + A.CallTo(() => _notificationRepository.GetNotificationByIdAndValidateReceiverAsync(A.That.Not.Matches(x => x == _notificationDetail.Id), _identityId)) .Returns(default((bool IsUserReceiver, NotificationDetailData NotificationDetailData))); - A.CallTo(() => _notificationRepository.GetNotificationCountForUserAsync(_identity.UserId, false)) + A.CallTo(() => _notificationRepository.GetNotificationCountForUserAsync(_identityId, false)) .Returns(5); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRepository); @@ -485,11 +485,11 @@ private void SetupNotifications() var readPaging = (int skip, int take) => Task.FromResult(new Pagination.Source(_readNotificationDetails.Count(), _readNotificationDetails.Skip(skip).Take(take))); var notificationsPaging = (int skip, int take) => Task.FromResult(new Pagination.Source(_notificationDetails.Count(), _notificationDetails.Skip(skip).Take(take))); - A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identity.UserId, false, null, null, false, A._, null, A>._, null)) + A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identityId, false, null, null, false, A._, null, A>._, null)) .Returns(unreadPaging); - A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identity.UserId, true, null, null, false, A._, null, A>._, null)) + A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identityId, true, null, null, false, A._, null, A>._, null)) .Returns(readPaging); - A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identity.UserId, null, null, null, false, A._, null, A>._, null)) + A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(_identityId, null, null, null, false, A._, null, A>._, null)) .Returns(notificationsPaging); } diff --git a/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs b/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs index ee140a014b..82c6b47cb9 100644 --- a/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs +++ b/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -36,7 +35,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Notifications.Service.Tests.Contro public class NotificationControllerTest { - private readonly IdentityData _identity = new("4C1A6851-D4E7-4E10-A011-3732CD045E8A", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly INotificationBusinessLogic _logic; private readonly NotificationController _controller; @@ -45,7 +44,11 @@ public NotificationControllerTest() { _fixture = new Fixture(); _logic = A.Fake(); - this._controller = new NotificationController(_logic); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); + _controller = new NotificationController(_logic); _controller.AddControllerContextWithClaimAndBearer("THISISTHEACCESSTOKEN", _identity); } @@ -64,7 +67,7 @@ public async Task GetNotifications_ReturnsExpectedCount() .ReturnsLazily(() => paginationResponse); //Act - var result = await this._controller.GetNotifications(isRead: isRead, notificationTypeId: typeId, notificationTopicId: topicId, onlyDueDate: onlyDueDate, sorting: sorting, doneState: doneState, searchTypeIds: Enumerable.Empty()).ConfigureAwait(false); + var result = await _controller.GetNotifications(isRead: isRead, notificationTypeId: typeId, notificationTopicId: topicId, onlyDueDate: onlyDueDate, sorting: sorting, doneState: doneState, searchTypeIds: Enumerable.Empty()).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetNotificationsAsync(0, 15, A.That.Matches(x => x.IsRead == isRead && x.TypeId == typeId && x.TopicId == topicId && x.OnlyDueDate == onlyDueDate && x.Sorting == sorting && x.DoneState == doneState))).MustHaveHappenedOnceExactly(); @@ -82,7 +85,7 @@ public async Task GetNotification_ReturnsExpectedData() .ReturnsLazily(() => data); //Act - var result = await this._controller.GetNotification(notificationId).ConfigureAwait(false); + var result = await _controller.GetNotification(notificationId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetNotificationDetailDataAsync(notificationId)).MustHaveHappenedOnceExactly(); @@ -98,7 +101,7 @@ public async Task NotificationCountDetails_ReturnsExpectedData() .ReturnsLazily(() => data); //Act - var result = await this._controller.NotificationCountDetails().ConfigureAwait(false); + var result = await _controller.NotificationCountDetails().ConfigureAwait(false); //Assert A.CallTo(() => _logic.GetNotificationCountDetailsAsync()).MustHaveHappenedOnceExactly(); @@ -115,7 +118,7 @@ public async Task SetNotificationToRead_ReturnsNoContent() .ReturnsLazily(() => Task.CompletedTask); //Act - var result = await this._controller.SetNotificationToRead(notificationId).ConfigureAwait(false); + var result = await _controller.SetNotificationToRead(notificationId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.SetNotificationStatusAsync(notificationId, true)).MustHaveHappenedOnceExactly(); @@ -131,7 +134,7 @@ public async Task DeleteNotification_ReturnsNoContent() .ReturnsLazily(() => Task.CompletedTask); //Act - var result = await this._controller.DeleteNotification(notificationId).ConfigureAwait(false); + var result = await _controller.DeleteNotification(notificationId).ConfigureAwait(false); //Assert A.CallTo(() => _logic.DeleteNotificationAsync(notificationId)).MustHaveHappenedOnceExactly(); diff --git a/tests/portalbackend/PortalBackend.DBAccess.Tests/ServiceAccountRespotitoryTests.cs b/tests/portalbackend/PortalBackend.DBAccess.Tests/ServiceAccountRespotitoryTests.cs index 2212638aba..ca4749a4a5 100644 --- a/tests/portalbackend/PortalBackend.DBAccess.Tests/ServiceAccountRespotitoryTests.cs +++ b/tests/portalbackend/PortalBackend.DBAccess.Tests/ServiceAccountRespotitoryTests.cs @@ -60,7 +60,6 @@ public async Task CreateCompanyServiceAccount_ReturnsExpectedResult() _validCompanyId, "test", "Only a test service account", - "test-1", "sa1", CompanyServiceAccountTypeId.MANAGED, sa => @@ -73,7 +72,6 @@ public async Task CreateCompanyServiceAccount_ReturnsExpectedResult() var changedEntries = changeTracker.Entries().ToList(); result.OfferSubscriptionId.Should().Be(_validSubscriptionId); result.CompanyServiceAccountTypeId.Should().Be(CompanyServiceAccountTypeId.MANAGED); - result.ClientId.Should().Be("test-1"); result.ClientClientId.Should().Be("sa1"); changeTracker.HasChanges().Should().BeTrue(); changedEntries.Should().NotBeEmpty(); @@ -127,7 +125,7 @@ public async Task GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync_Ret // Assert result.Should().NotBe(default); - result!.ClientId.Should().Be("dab9dd17-0d31-46c7-b313-aca61225dcd1"); + result!.ClientClientId.Should().Be("sa-cl5-custodian-1"); } [Fact] diff --git a/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRepositoryTests.cs b/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRepositoryTests.cs index c2e2adf8e0..8633a0a4ac 100644 --- a/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRepositoryTests.cs +++ b/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRepositoryTests.cs @@ -247,11 +247,11 @@ public async Task GetCompanyBpnForIamUserAsync_WithExistingUser_ReturnsExpected( #region GetAppAssignedIamClientUserDataUntrackedAsync [Theory] - [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, true, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", true, "SDE with EDC", "User", "Active")] - [InlineData("deadbeef-dead-beef-dead-beefdeadbeef", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, false, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", true, null, "User", "Active")] - [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "78d664de-04a0-41c6-9a47-478d303403d2", "00000000-0000-0000-0000-000000000000", true, true, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", false, "SDE with EDC", "User", "Active")] - [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "deadbeef-dead-beef-dead-beefdeadbeef", ValidUserCompanyId, false, false, null, false, null, null, null)] - public async Task GetAppAssignedIamClientUserDataUntrackedAsync_ReturnsExpected(Guid offerId, Guid companyUserId, Guid userCompanyId, bool found, bool validOffer, string resultIamUserId, bool sameCompany, string? offerName, string? firstName, string? lastName) + [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, true, true, "SDE with EDC", "User", "Active")] + [InlineData("deadbeef-dead-beef-dead-beefdeadbeef", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, false, true, null, "User", "Active")] + [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "78d664de-04a0-41c6-9a47-478d303403d2", "00000000-0000-0000-0000-000000000000", true, true, false, "SDE with EDC", "User", "Active")] + [InlineData("a16e73b9-5277-4b69-9f8d-3b227495dfea", "deadbeef-dead-beef-dead-beefdeadbeef", ValidUserCompanyId, false, false, false, null, null, null)] + public async Task GetAppAssignedIamClientUserDataUntrackedAsync_ReturnsExpected(Guid offerId, Guid companyUserId, Guid userCompanyId, bool found, bool validOffer, bool sameCompany, string? offerName, string? firstName, string? lastName) { var sut = await CreateSut().ConfigureAwait(false); @@ -262,7 +262,6 @@ public async Task GetAppAssignedIamClientUserDataUntrackedAsync_ReturnsExpected( { iamUserData.Should().NotBeNull(); iamUserData!.IsValidOffer.Should().Be(validOffer); - iamUserData.IamUserId.Should().Be(resultIamUserId); iamUserData.IsSameCompany.Should().Be(sameCompany); iamUserData.OfferName.Should().Be(offerName); iamUserData.Firstname.Should().Be(firstName); @@ -279,11 +278,11 @@ public async Task GetAppAssignedIamClientUserDataUntrackedAsync_ReturnsExpected( #region GetCoreOfferAssignedIamClientUserDataUntrackedAsync [Theory] - [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, true, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", true, "User", "Active")] - [InlineData("deadbeef-dead-beef-dead-beefdeadbeef", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, false, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", true, "User", "Active")] - [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "78d664de-04a0-41c6-9a47-478d303403d2", "00000000-0000-0000-0000-000000000000", true, true, "f3e2bcd8-1b42-4a62-ab09-2d86e40d0f85", false, "User", "Active")] - [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "deadbeef-dead-beef-dead-beefdeadbeef", ValidUserCompanyId, false, false, null, false, null, null)] - public async Task GetCoreOfferAssignedIamClientUserDataUntrackedAsync_ReturnsExpected(Guid offerId, Guid companyUserId, Guid userCompanyId, bool found, bool validOffer, string resultIamUserId, bool sameCompany, string? firstName, string? lastName) + [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, true, true, "User", "Active")] + [InlineData("deadbeef-dead-beef-dead-beefdeadbeef", "78d664de-04a0-41c6-9a47-478d303403d2", ValidUserCompanyId, true, false, true, "User", "Active")] + [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "78d664de-04a0-41c6-9a47-478d303403d2", "00000000-0000-0000-0000-000000000000", true, true, false, "User", "Active")] + [InlineData("9b957704-3505-4445-822c-d7ef80f27fcd", "deadbeef-dead-beef-dead-beefdeadbeef", ValidUserCompanyId, false, false, false, null, null)] + public async Task GetCoreOfferAssignedIamClientUserDataUntrackedAsync_ReturnsExpected(Guid offerId, Guid companyUserId, Guid userCompanyId, bool found, bool validOffer, bool sameCompany, string? firstName, string? lastName) { var sut = await CreateSut().ConfigureAwait(false); @@ -294,7 +293,6 @@ public async Task GetCoreOfferAssignedIamClientUserDataUntrackedAsync_ReturnsExp { iamUserData.Should().NotBeNull(); iamUserData!.IsValidOffer.Should().Be(validOffer); - iamUserData.IamUserId.Should().Be(resultIamUserId); iamUserData.IsSameCompany.Should().Be(sameCompany); iamUserData.Firstname.Should().Be(firstName); iamUserData.Lastname.Should().Be(lastName); diff --git a/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRolesRepositoryTests.cs b/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRolesRepositoryTests.cs index c832870c32..c0c710ecec 100644 --- a/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRolesRepositoryTests.cs +++ b/tests/portalbackend/PortalBackend.DBAccess.Tests/UserRolesRepositoryTests.cs @@ -80,7 +80,7 @@ public async Task GetUserWithUserRolesForApplicationId_WithValidData_ReturnsExpe // Assert data.Should().HaveCount(2); - data.Should().AllSatisfy(((Guid, string, IEnumerable UserRoleIds) userData) => userData.UserRoleIds.Should().NotBeEmpty().And.AllSatisfy(userRoleId => userRoleIds.Should().Contain(userRoleId))); + data.Should().AllSatisfy(((Guid, IEnumerable UserRoleIds) userData) => userData.UserRoleIds.Should().NotBeEmpty().And.AllSatisfy(userRoleId => userRoleIds.Should().Contain(userRoleId))); } #endregion diff --git a/tests/processes/NetworkRegistration.Library.Tests/NetworkRegistrationHandlerTests.cs b/tests/processes/NetworkRegistration.Library.Tests/NetworkRegistrationHandlerTests.cs index bc85c3daea..395536c633 100644 --- a/tests/processes/NetworkRegistration.Library.Tests/NetworkRegistrationHandlerTests.cs +++ b/tests/processes/NetworkRegistration.Library.Tests/NetworkRegistrationHandlerTests.cs @@ -95,7 +95,7 @@ public async Task SynchronizeUser_WithUserDataNull_ThrowsConflictException(strin // Arrange var user1Id = Guid.NewGuid(); var user1 = new CompanyUserIdentityProviderProcessData(user1Id, firstName, lastName, email, - "123456789", "Test Company", "BPNL00000001TEST", + "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("ironman", "idp1", "id1234"), 1)); A.CallTo(() => _networkRepository.GetOspCompanyName(NetworkRegistrationId)) @@ -121,7 +121,7 @@ public async Task SynchronizeUser_WithAliasNull_ThrowsConflictException() { // Arrange var user1Id = Guid.NewGuid(); - var user1 = new CompanyUserIdentityProviderProcessData(user1Id, "tony", "stark", "tony@stark.com", "123456789", "Test Company", "BPNL00000001TEST", + var user1 = new CompanyUserIdentityProviderProcessData(user1Id, "tony", "stark", "tony@stark.com", "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("ironman", null, "id1234"), 1)); A.CallTo(() => _networkRepository.GetOspCompanyName(NetworkRegistrationId)) @@ -148,10 +148,10 @@ public async Task SynchronizeUser_WithDisplayNameNull_ThrowsConflictException() // Arrange var user1Id = Guid.NewGuid().ToString(); var user1 = new CompanyUserIdentityProviderProcessData(Guid.NewGuid(), "tony", "stark", "tony@stark.com", - "123456789", "Test Company", "BPNL00000001TEST", + "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("ironman", "idp1", "id1234"), 1)); var user2 = new CompanyUserIdentityProviderProcessData(Guid.NewGuid(), "steven", "strange", - "steven@strange.com", "987654321", "Test Company", "BPNL00000001TEST", + "steven@strange.com", "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("drstrange", "idp1", "id9876"), 1)); A.CallTo(() => _networkRepository.GetOspCompanyName(NetworkRegistrationId)) @@ -181,13 +181,13 @@ public async Task SynchronizeUser_WithValidData_ReturnsExpected() // Arrange var user1Id = Guid.NewGuid().ToString(); var user1 = new CompanyUserIdentityProviderProcessData(Guid.NewGuid(), "tony", "stark", "tony@stark.com", - "123456789", "Test Company", "BPNL00000001TEST", + "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("ironman", "idp1", "id1234"), 1)); var user2 = new CompanyUserIdentityProviderProcessData(Guid.NewGuid(), "steven", "strange", - "steven@strange.com", "987654321", "Test Company", "BPNL00000001TEST", + "steven@strange.com", "Test Company", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("drstrange", "idp1", "id9876"), 1)); var user3 = new CompanyUserIdentityProviderProcessData(Guid.NewGuid(), "foo", "bar", - "foo@bar.com", "deadbeef", "Acme Corp", "BPNL00000001TEST", + "foo@bar.com", "Acme Corp", "BPNL00000001TEST", Enumerable.Repeat(new ProviderLinkData("foobar", "idp2", "id4711"), 1)); A.CallTo(() => _networkRepository.GetOspCompanyName(NetworkRegistrationId)) diff --git a/tests/processes/Processes.Worker.Library.Tests/ProcessExecutionServiceTests.cs b/tests/processes/Processes.Worker.Library.Tests/ProcessExecutionServiceTests.cs index e1921b9755..92d5a9de32 100644 --- a/tests/processes/Processes.Worker.Library.Tests/ProcessExecutionServiceTests.cs +++ b/tests/processes/Processes.Worker.Library.Tests/ProcessExecutionServiceTests.cs @@ -22,11 +22,11 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Org.Eclipse.TractusX.Portal.Backend.Framework.DateTimeProvider; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ProcessIdentity; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Repositories; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Entities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.Tests.Shared; using System.Collections.Immutable; @@ -40,7 +40,7 @@ public class ProcessExecutionServiceTests private readonly IMockLogger _mockLogger; private readonly ProcessExecutionService _service; private readonly IFixture _fixture; - private readonly IIdentityService _identityService; + private readonly IProcessIdentityDataDetermination _processIdentityDataDetermination; public ProcessExecutionServiceTests() { @@ -53,9 +53,7 @@ public ProcessExecutionServiceTests() _portalRepositories = A.Fake(); _processStepRepository = A.Fake(); _processExecutor = A.Fake(); - _identityService = A.Fake(); - - A.CallTo(() => _identityService.GetIdentityData()).Returns(_fixture.Create()); + _processIdentityDataDetermination = A.Fake(); _mockLogger = A.Fake>(); ILogger logger = new MockLogger(_mockLogger); @@ -69,7 +67,7 @@ public ProcessExecutionServiceTests() var serviceProvider = A.Fake(); A.CallTo(() => serviceProvider.GetService(typeof(IPortalRepositories))).Returns(_portalRepositories); A.CallTo(() => serviceProvider.GetService(typeof(IProcessExecutor))).Returns(_processExecutor); - A.CallTo(() => serviceProvider.GetService(typeof(IIdentityService))).Returns(_identityService); + A.CallTo(() => serviceProvider.GetService(typeof(IProcessIdentityDataDetermination))).Returns(_processIdentityDataDetermination); var serviceScope = A.Fake(); A.CallTo(() => serviceScope.ServiceProvider).Returns(serviceProvider); var serviceScopeFactory = A.Fake(); @@ -90,6 +88,7 @@ public async Task ExecuteAsync_WithNoPendingItems_NoServiceCall() await _service.ExecuteAsync(CancellationToken.None); // Assert + A.CallTo(() => _processIdentityDataDetermination.GetIdentityData()).MustHaveHappenedOnceExactly(); A.CallTo(() => _processExecutor.ExecuteProcess(A._, A._, A._)) .MustNotHaveHappened(); } diff --git a/tests/provisioning/Provisioning.Library.Tests/Extensions/ClientManagerTests.cs b/tests/provisioning/Provisioning.Library.Tests/Extensions/ClientManagerTests.cs index 2bd033d0e7..8e15b50470 100644 --- a/tests/provisioning/Provisioning.Library.Tests/Extensions/ClientManagerTests.cs +++ b/tests/provisioning/Provisioning.Library.Tests/Extensions/ClientManagerTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional diff --git a/tests/provisioning/Provisioning.Library.Tests/Extensions/ServiceAccountCreationTests.cs b/tests/provisioning/Provisioning.Library.Tests/Extensions/ServiceAccountCreationTests.cs index da66e671e7..2416055fd3 100644 --- a/tests/provisioning/Provisioning.Library.Tests/Extensions/ServiceAccountCreationTests.cs +++ b/tests/provisioning/Provisioning.Library.Tests/Extensions/ServiceAccountCreationTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -116,14 +115,18 @@ public async Task CreateServiceAccountAsync_WithValidData_ReturnsExpected() // Assert result.userRoleData.Should().ContainSingle(x => x.UserRoleId == _validUserRoleId && x.UserRoleText == "UserRole"); result.serviceAccountData.InternalClientId.Should().Be("internal-sa1"); - result.serviceAccountData.UserEntityId.Should().Be(_iamUserId); + result.serviceAccountData.IamUserId.Should().Be(_iamUserId); result.serviceAccountData.AuthData.IamClientAuthMethod.Should().Be(IamClientAuthMethod.SECRET); A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(_iamUserId, bpns)).MustHaveHappenedOnceExactly(); A.CallTo(() => _provisioningManager.AddProtocolMapperAsync("internal-sa1")).MustHaveHappenedOnceExactly(); A.CallTo(() => _portalRepositories.SaveAsync()).MustNotHaveHappened(); - serviceAccounts.Should().ContainSingle().Which.Name.Should().Be("testName"); - serviceAccounts.Should().ContainSingle().Which.ClientId.Should().Be("internal-sa1"); - identities.Should().ContainSingle().And.Satisfy(x => x.CompanyId == _companyId && x.UserEntityId == _iamUserId); + serviceAccounts.Should().ContainSingle().Which.Should().Match( + x => x.Name == "testName" && + x.ClientClientId == "sa1"); + identities.Should().ContainSingle().Which.Should().Match( + x => x.CompanyId == _companyId && + x.UserStatusId == UserStatusId.ACTIVE && + x.IdentityTypeId == IdentityTypeId.COMPANY_SERVICE_ACCOUNT); } [Fact] @@ -145,15 +148,19 @@ public async Task CreateServiceAccountAsync_WithNameSetAndValidData_ReturnsExpec // Assert result.userRoleData.Should().ContainSingle(x => x.UserRoleId == _validUserRoleId && x.UserRoleText == "UserRole"); result.serviceAccountData.InternalClientId.Should().Be("internal-sa1"); - result.serviceAccountData.UserEntityId.Should().Be(_iamUserId); + result.serviceAccountData.IamUserId.Should().Be(_iamUserId); result.serviceAccountData.AuthData.IamClientAuthMethod.Should().Be(IamClientAuthMethod.SECRET); A.CallTo(() => _provisioningManager.SetupCentralServiceAccountClientAsync(A._, A.That.Matches(x => x.Name == "sa1-testName"), A._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(_iamUserId, bpns)).MustHaveHappenedOnceExactly(); A.CallTo(() => _provisioningManager.AddProtocolMapperAsync("internal-sa1")).MustHaveHappenedOnceExactly(); A.CallTo(() => _portalRepositories.SaveAsync()).MustNotHaveHappened(); - serviceAccounts.Should().ContainSingle().Which.Name.Should().Be("sa1-testName"); - serviceAccounts.Should().ContainSingle().Which.ClientId.Should().Be("internal-sa1"); - identities.Should().ContainSingle().And.Satisfy(x => x.CompanyId == _companyId && x.UserEntityId == _iamUserId); + serviceAccounts.Should().ContainSingle().Which.Should().Match( + x => x.Name == "sa1-testName" && + x.ClientClientId == "sa1"); + identities.Should().ContainSingle().Which.Should().Match( + x => x.CompanyId == _companyId && + x.UserStatusId == UserStatusId.ACTIVE && + x.IdentityTypeId == IdentityTypeId.COMPANY_SERVICE_ACCOUNT); } #region Setup @@ -174,8 +181,8 @@ private void Setup(ICollection? serviceAccounts = null, I identities?.Add(identity); }) .Returns(new Identity(_identityId, default, default, default, default)); - A.CallTo(() => _serviceAccountRepository.CreateCompanyServiceAccount(_identityId, A._, A._, A._, A._, A._, A>._)) - .Invokes((Guid identityId, string name, string description, string clientId, string clientClientId, CompanyServiceAccountTypeId companyServiceAccountTypeId, Action? setOptionalParameters) => + A.CallTo(() => _serviceAccountRepository.CreateCompanyServiceAccount(_identityId, A._, A._, A._, A._, A>._)) + .Invokes((Guid identityId, string name, string description, string clientClientId, CompanyServiceAccountTypeId companyServiceAccountTypeId, Action? setOptionalParameters) => { var sa = new CompanyServiceAccount( identityId, @@ -183,7 +190,6 @@ private void Setup(ICollection? serviceAccounts = null, I description, companyServiceAccountTypeId) { - ClientId = clientId, ClientClientId = clientClientId }; setOptionalParameters?.Invoke(sa); diff --git a/tests/provisioning/Provisioning.Library.Tests/UserManagerTests.cs b/tests/provisioning/Provisioning.Library.Tests/UserManagerTests.cs index ed36cbbf7d..f198f509f6 100644 --- a/tests/provisioning/Provisioning.Library.Tests/UserManagerTests.cs +++ b/tests/provisioning/Provisioning.Library.Tests/UserManagerTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -21,6 +20,7 @@ using Flurl.Http; using Flurl.Http.Testing; using Microsoft.Extensions.Options; +using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Factory; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Library; using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Library.Models.Clients; @@ -133,7 +133,7 @@ public async Task GetUserByUserName_WithOneUser_ReturnsId() { // Arrange using var httpTest = new HttpTest(); - var user = new User { Id = "test123" }; + var user = new User { Id = "test123", UserName = "test" }; httpTest.WithAuthorization() .WithGetUsersAsync(Enumerable.Repeat(user, 1)); @@ -144,6 +144,22 @@ public async Task GetUserByUserName_WithOneUser_ReturnsId() result.Should().Be("test123"); } + [Fact] + public async Task GetUserByUserName_WithDuplicateUsers_Throws() + { + // Arrange + using var httpTest = new HttpTest(); + var user = new User { Id = "test123", UserName = "test" }; + httpTest.WithAuthorization() + .WithGetUsersAsync(Enumerable.Repeat(user, 2)); + + // Act + var result = await Assert.ThrowsAsync(() => _sut.GetUserByUserName("test")).ConfigureAwait(false); + + // Assert + result.Message.Should().Be("there should never be multiple users in keycloak having the same username 'test'"); + } + [Fact] public async Task GetUserByUserName_With404Error_ReturnsNull() { diff --git a/tests/provisioning/Provisioning.Library.Tests/UserProvisioningServiceCreateUsersTests.cs b/tests/provisioning/Provisioning.Library.Tests/UserProvisioningServiceCreateUsersTests.cs index 9625232910..44e85d495c 100644 --- a/tests/provisioning/Provisioning.Library.Tests/UserProvisioningServiceCreateUsersTests.cs +++ b/tests/provisioning/Provisioning.Library.Tests/UserProvisioningServiceCreateUsersTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -220,11 +219,15 @@ public async Task TestCreateUsersCentralUserDuplicateKeycloakUserError() var userInfo = userCreationInfoIdp.ElementAt(_indexSpecialUser); var iamUserId = _fixture.Create(); + var companyUserId = Guid.NewGuid(); A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(A.That.IsEqualTo(userInfo.FirstName), A._, A._, A._, A>._)) - .Returns(new[] { (UserEntityId: (string?)iamUserId, CompanyUserId: Guid.Empty) }.ToAsyncEnumerable()); + .Returns(new[] { (CompanyUserId: companyUserId, IsFullMatch: false) }.ToAsyncEnumerable()); - A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(A.That.IsEqualTo(iamUserId))) + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); + + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId)) .Returns(new[] { new IdentityProviderLink(_companyNameIdpAliasData.IdpAlias, userInfo.UserId, userInfo.UserName) }.ToAsyncEnumerable()); var result = await sut.CreateOwnCompanyIdpUsersAsync( @@ -241,7 +244,39 @@ public async Task TestCreateUsersCentralUserDuplicateKeycloakUserError() var error = result.ElementAt(_indexSpecialUser).Error; error.Should().NotBeNull(); error.Should().BeOfType(typeof(ConflictException)); - error!.Message.Should().Be($"existing user {iamUserId} in keycloak for provider userid {userInfo.UserId}, {userInfo.UserName}"); + error!.Message.Should().Be($"existing user {companyUserId} in keycloak for provider userid {userInfo.UserId}, {userInfo.UserName}"); + } + + [Fact] + public async Task TestCreateUsersCentralUserPotentialMatchWithoutMatchingKeycloakUserSuccess() + { + var sut = new UserProvisioningService(_provisioningManager, _portalRepositories); + + var userCreationInfoIdp = CreateUserCreationInfoIdp().ToList(); + + var userInfo = userCreationInfoIdp.ElementAt(_indexSpecialUser); + var iamUserId = _fixture.Create(); + var companyUserId = Guid.NewGuid(); + + A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(A.That.IsEqualTo(userInfo.FirstName), A._, A._, A._, A>._)) + .Returns(new[] { (CompanyUserId: companyUserId, IsFullMatch: false) }.ToAsyncEnumerable()); + + A.CallTo(() => _provisioningManager.GetUserByUserName(companyUserId.ToString())) + .Returns(iamUserId); + + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(iamUserId)) + .Returns(_fixture.CreateMany(3).ToAsyncEnumerable()); + + var result = await sut.CreateOwnCompanyIdpUsersAsync( + _companyNameIdpAliasData, + userCreationInfoIdp.ToAsyncEnumerable(), + _cancellationTokenSource.Token + ).ToListAsync().ConfigureAwait(false); + + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(A._)).MustHaveHappenedOnceExactly(); + + result.Should().HaveCount(_numUsers) + .And.AllSatisfy(r => r.Error.Should().BeNull()); } [Fact] @@ -283,16 +318,18 @@ public async Task TestCreateUsersNotExistingCompanyUserWithoutKeycloakUserSucces var userCreationInfoIdp = CreateUserCreationInfoIdp().ToList(); var userInfo = userCreationInfoIdp.ElementAt(_indexSpecialUser); - var identityId = _fixture.Create(); + var identityId = Guid.NewGuid(); var centralUserId = _fixture.Create(); - A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(A.That.IsEqualTo(userInfo.FirstName), A._, A._, A._, A>._)) - .Returns(new[] { (UserEntityId: (string?)null, CompanyUserId: Guid.Empty) }.ToAsyncEnumerable()); + A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(userInfo.FirstName, A._, A._, A._, A>._)) + .Returns(Enumerable.Empty<(Guid, bool)>().ToAsyncEnumerable()); - A.CallTo(() => _userRepository.CreateIdentity(A._, A._, IdentityTypeId.COMPANY_USER, null)) - .ReturnsLazily((Guid companyId, UserStatusId userStatusId, IdentityTypeId identityId, Action _) => new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, companyId, userStatusId, identityId) + A.CallTo(() => _userRepository.CreateIdentity(A._, A._, A._, A>._)) + .ReturnsLazily((Guid companyId, UserStatusId userStatusId, IdentityTypeId identityTypeId, Action? setOptionalFields) => { - UserEntityId = centralUserId + var identity = new Identity(Guid.NewGuid(), DateTimeOffset.UtcNow, companyId, userStatusId, identityTypeId); + setOptionalFields?.Invoke(identity); + return identity; }); A.CallTo(() => _userRepository.CreateCompanyUser(A._, userInfo.FirstName, A._, A._)) .ReturnsLazily((Guid _, string? firstName, string? lastName, string email) => new CompanyUser(identityId) { Firstname = firstName, Lastname = lastName, Email = email }); @@ -329,11 +366,12 @@ public async Task TestCreateUsersExistingCompanyUserWithoutKeycloakUserSuccess() var userCreationInfoIdp = CreateUserCreationInfoIdp().ToList(); var userInfo = userCreationInfoIdp.ElementAt(_indexSpecialUser); - var companyUserId = _fixture.Create(); + var companyUserId = Guid.NewGuid(); + var existingUserId = _fixture.Create(); var centralUserId = _fixture.Create(); - A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(A.That.IsEqualTo(userInfo.FirstName), A._, A._, A._, A>._)) - .Returns(new[] { (UserEntityId: (string?)null, CompanyUserId: companyUserId) }.ToAsyncEnumerable()); + A.CallTo(() => _userRepository.GetMatchingCompanyIamUsersByNameEmail(userInfo.FirstName, A._, A._, A._, A>._)) + .Returns(new[] { (CompanyUserId: companyUserId, IsFullMatch: true) }.ToAsyncEnumerable()); A.CallTo(() => _provisioningManager.CreateCentralUserAsync(A.That.Matches(u => u.FirstName == userInfo.FirstName), A)>>._)) .Returns(centralUserId); @@ -344,10 +382,10 @@ public async Task TestCreateUsersExistingCompanyUserWithoutKeycloakUserSuccess() _cancellationTokenSource.Token ).ToListAsync().ConfigureAwait(false); - A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(A._)).MustNotHaveHappened(); + A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(existingUserId)).MustNotHaveHappened(); A.CallTo(() => _provisioningManager.CreateCentralUserAsync(A._, A)>>._)).MustHaveHappened(userCreationInfoIdp.Count, Times.Exactly); A.CallTo(() => _provisioningManager.CreateCentralUserAsync(A.That.Matches(u => u.FirstName == userInfo.FirstName), A)>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _userRepository.CreateIdentity(A._, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER, null)).MustHaveHappened(userCreationInfoIdp.Count - 1, Times.Exactly); + A.CallTo(() => _userRepository.CreateIdentity(A._, UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER, A>._)).MustHaveHappened(userCreationInfoIdp.Count - 1, Times.Exactly); A.CallTo(() => _userRepository.CreateCompanyUser(A._, A._, A._, A._)).MustHaveHappened(userCreationInfoIdp.Count - 1, Times.Exactly); A.CallTo(() => _userRepository.CreateCompanyUser(A._, userInfo.FirstName, A._, A._)).MustNotHaveHappened(); A.CallTo(() => _businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(A._, _companyNameIdpAliasData.BusinessPartnerNumber!)).MustHaveHappened(userCreationInfoIdp.Count - 1, Times.Exactly); diff --git a/tests/registration/ApplicationActivation.Library.Tests/ApplicationActivationTests.cs b/tests/registration/ApplicationActivation.Library.Tests/ApplicationActivationTests.cs index cde92422ca..5a115ada2d 100644 --- a/tests/registration/ApplicationActivation.Library.Tests/ApplicationActivationTests.cs +++ b/tests/registration/ApplicationActivation.Library.Tests/ApplicationActivationTests.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -52,9 +51,9 @@ public class ApplicationActivationTests private static readonly Guid CompanyUserId3 = new("857b93b1-8fcb-4141-81b0-ae81950d48af"); private static readonly Guid UserRoleId = new("607818be-4978-41f4-bf63-fa8d2de51154"); private static readonly Guid CompanyUserRoleId = new("607818be-4978-41f4-bf63-fa8d2de51154"); - private static readonly Guid CentralUserId1 = new("6bc51706-9a30-4eb9-9e60-77fdd6d9cd6f"); - private static readonly Guid CentralUserId2 = new("6bc51706-9a30-4eb9-9e60-77fdd6d9cd70"); - private static readonly Guid CentralUserId3 = new("6bc51706-9a30-4eb9-9e60-77fdd6d9cd71"); + private static readonly string CentralUserId1 = "6bc51706-9a30-4eb9-9e60-77fdd6d9cd6f"; + private static readonly string CentralUserId2 = "6bc51706-9a30-4eb9-9e60-77fdd6d9cd70"; + private static readonly string CentralUserId3 = "6bc51706-9a30-4eb9-9e60-77fdd6d9cd71"; private static readonly Guid ProcessId = new("db9d99cd-51a3-4933-a1cf-dc1b836b53bb"); private readonly IFixture _fixture; @@ -257,9 +256,9 @@ public async Task HandleApplicationActivation_WithMidnightRun_ApprovesRequestAnd A.CallTo(() => _businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(CompanyUserId3, BusinessPartnerNumber)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserRolesByClientId(A>.That.IsSameSequenceAs(new[] { "remove-id" }))).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserWithUserRolesForApplicationId(A._, A>.That.IsSameSequenceAs(new[] { CompanyUserRoleId }))).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("1", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("2", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("3", A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId1, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId2, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId3, A>>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _custodianService.SetMembership(BusinessPartnerNumber, A._)).MustHaveHappenedOnceExactly(); _notifications.Should().HaveCount(5); @@ -338,9 +337,9 @@ public async Task HandleApplicationActivation_WithCompanyAdminUser_ApprovesReque A.CallTo(() => _businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(CompanyUserId3, BusinessPartnerNumber)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserRolesByClientId(A>.That.IsSameSequenceAs(new[] { "remove-id" }))).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserWithUserRolesForApplicationId(A._, A>.That.IsSameSequenceAs(new[] { CompanyUserRoleId }))).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("1", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("2", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("3", A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId1, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId2, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId3, A>>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _custodianService.SetMembership(BusinessPartnerNumber, A._)).MustHaveHappenedOnceExactly(); @@ -473,9 +472,9 @@ public async Task HandleApplicationActivation_WithExternalApplication_ApprovesRe A.CallTo(() => _businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(CompanyUserId2, BusinessPartnerNumber)).MustNotHaveHappened(); A.CallTo(() => _rolesRepository.GetUserRolesByClientId(A>.That.IsSameSequenceAs(new[] { "remove-id" }))).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserWithUserRolesForApplicationId(A._, A>.That.IsSameSequenceAs(new[] { CompanyUserRoleId }))).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("1", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("2", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("3", A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId1, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId2, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId3, A>>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _custodianService.SetMembership(BusinessPartnerNumber, A._)).MustHaveHappenedOnceExactly(); processSteps.Should().ContainSingle().And.Satisfy( @@ -642,9 +641,9 @@ public async Task HandleApplicationActivation_WithUnassignedRoles_ThrowsUnexpect A.CallTo(() => _businessPartnerRepository.CreateCompanyUserAssignedBusinessPartner(CompanyUserId3, BusinessPartnerNumber)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserRolesByClientId(A>.That.IsSameSequenceAs(new[] { "remove-id" }))).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.GetUserWithUserRolesForApplicationId(A._, A>.That.IsSameSequenceAs(new[] { CompanyUserRoleId }))).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("1", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("2", A>>._)).MustHaveHappenedOnceExactly(); - A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync("3", A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId1, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId2, A>>._)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _provisioningManager.DeleteClientRolesFromCentralUserAsync(CentralUserId3, A>>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _rolesRepository.DeleteCompanyUserAssignedRoles(A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappened(3, Times.Exactly); A.CallTo(() => _custodianService.SetMembership(BusinessPartnerNumber, A._)).MustHaveHappenedOnceExactly(); @@ -935,9 +934,9 @@ private void SetupFakes( var companyInvitedUsers = new CompanyInvitedUserData[] { - new(CompanyUserId1, CentralUserId1.ToString(), Enumerable.Empty(), Enumerable.Empty()), - new(CompanyUserId2, CentralUserId2.ToString(), Enumerable.Repeat(BusinessPartnerNumber, 1), Enumerable.Repeat(UserRoleId, 1)), - new(CompanyUserId3, CentralUserId3.ToString(), Enumerable.Empty(), Enumerable.Empty()) + new(CompanyUserId1, Enumerable.Empty(), Enumerable.Empty()), + new(CompanyUserId2, Enumerable.Repeat(BusinessPartnerNumber, 1), Enumerable.Repeat(UserRoleId, 1)), + new(CompanyUserId3, Enumerable.Empty(), Enumerable.Empty()) }.ToAsyncEnumerable(); var businessPartnerNumbers = new[] { BusinessPartnerNumber }.AsEnumerable(); @@ -982,18 +981,25 @@ private void SetupFakes( A.CallTo(() => _applicationRepository.GetInvitedUsersDataByApplicationIdUntrackedAsync(Id)) .Returns(companyInvitedUsers); - A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId1.ToString(), A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) + A.CallTo(() => _provisioningManager.GetUserByUserName(CompanyUserId1.ToString())) + .Returns(CentralUserId1); + A.CallTo(() => _provisioningManager.GetUserByUserName(CompanyUserId2.ToString())) + .Returns(CentralUserId2); + A.CallTo(() => _provisioningManager.GetUserByUserName(CompanyUserId3.ToString())) + .Returns(CentralUserId3); + + A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId1, A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) .Returns(clientRoleNames.Select(x => (Client: x.ClientId, Roles: x.UserRoleNames)).ToAsyncEnumerable()); - A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId2.ToString(), A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) + A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId2, A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) .Returns(clientRoleNames.Select(x => (Client: x.ClientId, Roles: x.UserRoleNames)).ToAsyncEnumerable()); - A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId3.ToString(), A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) + A.CallTo(() => _provisioningManager.AssignClientRolesToCentralUserAsync(CentralUserId3, A>>.That.Matches(x => x[ClientId].First() == clientRoleNames.First(x => x.ClientId == ClientId).UserRoleNames.First()))) .Returns(clientRoleNames.Select(x => (Client: x.ClientId, Roles: x.UserRoleNames)).ToAsyncEnumerable()); - A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId1.ToString(), businessPartnerNumbers)) + A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId1, businessPartnerNumbers)) .Returns(Task.CompletedTask); - A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId2.ToString(), businessPartnerNumbers)) + A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId2, businessPartnerNumbers)) .Returns(Task.CompletedTask); - A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId3.ToString(), businessPartnerNumbers)) + A.CallTo(() => _provisioningManager.AddBpnAttributetoUserAsync(CentralUserId3, businessPartnerNumbers)) .Returns(Task.CompletedTask); A.CallTo(() => _rolesRepository.CreateIdentityAssignedRole(CompanyUserId1, CompanyUserRoleId)) @@ -1050,11 +1056,11 @@ async IAsyncEnumerable CreateNotificationsUserIds(IEnumerable userId private void SetupForDelete() { - var userData = new (Guid CompanyUserId, string UserEntityId, IEnumerable UserRoleIds)[] + var userData = new (Guid CompanyUserId, IEnumerable UserRoleIds)[] { - new (CompanyUserId1, "1", new [] {CompanyUserRoleId}), - new (CompanyUserId2, "2", new [] {CompanyUserRoleId}), - new (CompanyUserId3, "3", new [] {CompanyUserRoleId}), + new (CompanyUserId1, new [] {CompanyUserRoleId}), + new (CompanyUserId2, new [] {CompanyUserRoleId}), + new (CompanyUserId3, new [] {CompanyUserRoleId}), }; var userRoles = new (string ClientClientId, IEnumerable<(Guid UserRoleId, string UserRoleText)>)[] { ( "remove-id", new [] { ( CompanyUserRoleId, "Company Admin" ) } ) diff --git a/tests/registration/Registration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs b/tests/registration/Registration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs index b58952baa1..a4c4b97359 100644 --- a/tests/registration/Registration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs +++ b/tests/registration/Registration.Service.Tests/BusinessLogic/NetworkBusinessLogicTests.cs @@ -49,7 +49,7 @@ public class NetworkBusinessLogicTests private readonly IFixture _fixture; - private readonly IdentityData _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IUserProvisioningService _userProvisioningService; private readonly IApplicationChecklistCreationService _checklistService; @@ -83,8 +83,11 @@ public NetworkBusinessLogicTests() _consentRepository = A.Fake(); var identityService = A.Fake(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => identityService.IdentityData).Returns(_identity); - A.CallTo(() => identityService.IdentityId).Returns(_identity.UserId); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_companyRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_consentRepository); @@ -319,7 +322,7 @@ public async Task Submit_WithValidData_CallsExpected() consents.Should().HaveCount(2) .And.AllSatisfy(x => x.Should().Match(x => x.CompanyId == _identity.CompanyId && - x.CompanyUserId == _identity.UserId && + x.CompanyUserId == _identity.IdentityId && x.ConsentStatusId == ConsentStatusId.ACTIVE)) .And.Satisfy( x => x.AgreementId == agreementId, diff --git a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs index c78a6a696f..94e5ca3025 100644 --- a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs +++ b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 Microsoft and BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -37,7 +36,6 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using Org.Eclipse.TractusX.Portal.Backend.Processes.ApplicationChecklist.Library; -using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; using Org.Eclipse.TractusX.Portal.Backend.Registration.Common; @@ -55,7 +53,6 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Tests.Busines public class RegistrationBusinessLogicTest { private readonly IFixture _fixture; - private readonly IProvisioningManager _provisioningManager; private readonly IUserProvisioningService _userProvisioningService; private readonly IInvitationRepository _invitationRepository; private readonly IDocumentRepository _documentRepository; @@ -69,7 +66,7 @@ public class RegistrationBusinessLogicTest private readonly IConsentRepository _consentRepository; private readonly IProcessStepRepository _processStepRepository; private readonly IApplicationChecklistCreationService _checklistService; - private readonly IdentityData _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly Guid _existingApplicationId; private readonly string _displayName; private readonly string _alpha2code; @@ -89,7 +86,6 @@ public RegistrationBusinessLogicTest() _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); _portalRepositories = A.Fake(); - _provisioningManager = A.Fake(); _userProvisioningService = A.Fake(); _mailingService = A.Fake(); _invitationRepository = A.Fake(); @@ -107,8 +103,11 @@ public RegistrationBusinessLogicTest() _dateTimeProvider = A.Fake(); _identityService = A.Fake(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); A.CallTo(() => _identityService.IdentityData).Returns(_identity); - A.CallTo(() => _identityService.IdentityId).Returns(_identity.UserId); var options = Options.Create(new RegistrationSettings { @@ -131,7 +130,6 @@ public RegistrationBusinessLogicTest() SetupRepositories(); - _fixture.Inject(_provisioningManager); _fixture.Inject(_userProvisioningService); _fixture.Inject(_portalRepositories); } @@ -148,7 +146,6 @@ public async Task GetClientRolesCompositeAsync_GetsAllRoles() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -221,7 +218,6 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_R bpnAccess, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -264,7 +260,6 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_T null!, null!, null!, - null!, _identityService, _dateTimeProvider); @@ -285,14 +280,17 @@ public async Task GetAllApplicationsForUserWithStatus_WithValidUser_GetsAllRoles { //Arrange var userCompanyId = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = userCompanyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(userCompanyId); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -347,7 +345,6 @@ public async Task GetCompanyWithAddressAsync_WithValidApplication_GetsData() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -376,7 +373,6 @@ public async Task GetCompanyWithAddressAsync_WithInvalidApplication_ThrowsNotFou null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -404,7 +400,6 @@ public async Task GetCompanyWithAddressAsync_WithInvalidUser_ThrowsForbiddenExce null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -435,7 +430,11 @@ public async Task GetCompanyWithAddressAsync_WithInvalidUser_ThrowsForbiddenExce public async Task SetCompanyWithAddressAsync_WithMissingData_ThrowsArgumentException(string? name, string? city, string? streetName, string? countryCode, IEnumerable uniqueIdentifierIds, IEnumerable values, string argumentName) { //Arrange - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, @@ -444,7 +443,6 @@ public async Task SetCompanyWithAddressAsync_WithMissingData_ThrowsArgumentExcep null!, null!, null!, - null!, _identityService, _dateTimeProvider); @@ -471,7 +469,6 @@ public async Task SetCompanyWithAddressAsync_WithInvalidApplicationId_ThrowsNotF null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -496,7 +493,11 @@ public async Task SetCompanyWithAddressAsync_WithoutCompanyUserId_ThrowsForbidde //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = new CompanyDetailData(companyId, "name", "munich", "main street", "de", null, null, null, null, null, null, Enumerable.Empty()); var sut = new RegistrationBusinessLogic( @@ -505,7 +506,6 @@ public async Task SetCompanyWithAddressAsync_WithoutCompanyUserId_ThrowsForbidde null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -528,7 +528,11 @@ public async Task SetCompanyWithAddressAsync__WithInvalidBpn_ThrowsControllerArg //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, "invalid") .With(x => x.CompanyId, companyId) @@ -541,7 +545,6 @@ public async Task SetCompanyWithAddressAsync__WithInvalidBpn_ThrowsControllerArg null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -561,7 +564,11 @@ public async Task SetCompanyWithAddressAsync__WithExistingBpn_ThrowsControllerAr //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, "BPNL00000001TEST") .With(x => x.CompanyId, companyId) @@ -575,7 +582,6 @@ public async Task SetCompanyWithAddressAsync__WithExistingBpn_ThrowsControllerAr null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -595,7 +601,11 @@ public async Task SetCompanyWithAddressAsync_ModifyCompany() //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, (string?)null) .With(x => x.CompanyId, companyId) @@ -614,7 +624,6 @@ public async Task SetCompanyWithAddressAsync_ModifyCompany() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -654,8 +663,12 @@ public async Task SetCompanyWithAddressAsync_WithoutInitialCompanyAddress_Create var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); var addressId = Guid.NewGuid(); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, (string?)null) .With(x => x.CompanyId, companyId) @@ -684,7 +697,6 @@ public async Task SetCompanyWithAddressAsync_WithoutInitialCompanyAddress_Create null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -748,7 +760,10 @@ public async Task SetCompanyWithAddressAsync_WithInitialCompanyAddress_ModifyAdd //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, (string?)null) @@ -770,7 +785,6 @@ public async Task SetCompanyWithAddressAsync_WithInitialCompanyAddress_ModifyAdd null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -831,8 +845,12 @@ public async Task SetCompanyWithAddressAsync_WithUniqueIdentifiers_CreateModifyD var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); var now = DateTimeOffset.Now; + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(companyId); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var uniqueIdentifiers = _fixture.CreateMany(4); var firstIdData = _fixture.Build().With(x => x.UniqueIdentifierId, uniqueIdentifiers.First()).Create(); // shall not modify @@ -866,7 +884,6 @@ public async Task SetCompanyWithAddressAsync_WithUniqueIdentifiers_CreateModifyD null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -912,7 +929,11 @@ public async Task SetCompanyWithAddressAsync_WithInvalidCountryCode_Throws() .With(x => x.BusinessPartnerNumber, (string?)null) .With(x => x.CountryAlpha2Code, _alpha2code) .Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, @@ -920,7 +941,6 @@ public async Task SetCompanyWithAddressAsync_WithInvalidCountryCode_Throws() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -942,7 +962,11 @@ public async Task SetCompanyWithAddressAsync_WithInvalidUniqueIdentifiers_Throws { //Arrange var identifiers = _fixture.CreateMany(2); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var companyData = _fixture.Build() .With(x => x.BusinessPartnerNumber, (string?)null) @@ -956,7 +980,6 @@ public async Task SetCompanyWithAddressAsync_WithInvalidUniqueIdentifiers_Throws null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -982,14 +1005,17 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsCo { //Arrange var applicationId = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1008,14 +1034,17 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidApplication_Thr { //Arrange var applicationId = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1037,14 +1066,17 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsAr { //Arrange var applicationId = _fixture.Create(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1076,14 +1108,17 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithValidData_SavesChanges { setOptionalFields.Invoke(application); }); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var sut = new RegistrationBusinessLogic( _options, null!, null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1120,7 +1155,6 @@ public async Task GetCompanyRolesAsync_() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1150,7 +1184,6 @@ public async Task Get_WhenThereAreInvitedUser_ShouldReturnInvitedUserWithRoles() { //Assert A.CallTo(() => _invitationRepository.GetInvitedUserDetailsUntrackedAsync(_existingApplicationId)).MustHaveHappened(1, Times.OrMore); - A.CallTo(() => _provisioningManager.GetClientRoleMappingsForUserAsync(A._, A._)).MustHaveHappened(1, Times.OrMore); Assert.NotNull(item); Assert.IsType(item); } @@ -1210,7 +1243,6 @@ public async Task UploadDocumentAsync_WithValidData_CreatesDocument() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1274,7 +1306,6 @@ public async Task UploadDocumentAsync_WithNotExistingApplicationId_ThrowsExcepti null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1310,12 +1341,10 @@ public async Task UploadDocumentAsync_WithNotExistingIamUser_ThrowsException() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, _dateTimeProvider); - var identity = _fixture.Create(); // Act async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.CX_FRAME_CONTRACT, CancellationToken.None); @@ -1345,7 +1374,6 @@ public async Task UploadDocumentAsync_WithInvalidDocumentTypeId_ThrowsException( null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1383,7 +1411,6 @@ public async Task TestInviteNewUserAsyncSuccess() _options, _mailingService, null!, - _provisioningManager, _userProvisioningService, null!, _portalRepositories, @@ -1416,7 +1443,6 @@ public async Task TestInviteNewUserEmptyEmailThrows() _options, _mailingService, null!, - _provisioningManager, _userProvisioningService, null!, _portalRepositories, @@ -1446,7 +1472,6 @@ public async Task TestInviteNewUserUserAlreadyExistsThrows() _options, _mailingService, null!, - _provisioningManager, _userProvisioningService, null!, _portalRepositories, @@ -1481,7 +1506,6 @@ public async Task TestInviteNewUserAsyncCreationErrorThrows() _options, _mailingService, null!, - _provisioningManager, _userProvisioningService, null!, _portalRepositories, @@ -1509,12 +1533,11 @@ public async Task GetUploadedDocumentsAsync_ReturnsExpectedOutput() { // Arrange var applicationId = _fixture.Create(); - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); var uploadDocuments = _fixture.CreateMany(3); - A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) + A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.IdentityId)) .Returns((true, uploadDocuments)); var sut = new RegistrationBusinessLogic( @@ -1523,7 +1546,6 @@ public async Task GetUploadedDocumentsAsync_ReturnsExpectedOutput() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1542,11 +1564,10 @@ public async Task GetUploadedDocumentsAsync_InvalidApplication_ThrowsNotFound() { // Arrange var applicationId = _fixture.Create(); - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _identityService.IdentityId).Returns(identity.UserId); - A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) + A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.IdentityId)) .Returns(((bool, IEnumerable))default); var sut = new RegistrationBusinessLogic( @@ -1555,7 +1576,6 @@ public async Task GetUploadedDocumentsAsync_InvalidApplication_ThrowsNotFound() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1575,10 +1595,10 @@ public async Task GetUploadedDocumentsAsync_InvalidUser_ThrowsForbidden() { // Arrange var applicationId = _fixture.Create(); - var identity = _fixture.Create(); + var identity = _fixture.Create(); A.CallTo(() => _identityService.IdentityData).Returns(identity); - A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) + A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.IdentityId)) .Returns((false, Enumerable.Empty())); var sut = new RegistrationBusinessLogic( @@ -1587,7 +1607,6 @@ public async Task GetUploadedDocumentsAsync_InvalidUser_ThrowsForbidden() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -1613,7 +1632,7 @@ public async Task SubmitRoleConsentsAsync_WithNotExistingApplication_ThrowsNotFo var notExistingId = _fixture.Create(); A.CallTo(() => _companyRolesRepository.GetCompanyRoleAgreementConsentDataAsync(notExistingId)) .ReturnsLazily(() => (CompanyRoleAgreementConsentData?)null); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRoleConsentAsync(notExistingId, _fixture.Create()) @@ -1633,7 +1652,7 @@ public async Task SubmitRoleConsentsAsync_WithWrongCompanyUser_ThrowsForbiddenEx var data = new CompanyRoleAgreementConsentData(Guid.NewGuid(), applicationStatusId, _fixture.CreateMany(2), _fixture.CreateMany(5)); A.CallTo(() => _companyRolesRepository.GetCompanyRoleAgreementConsentDataAsync(applicationId)) .ReturnsLazily(() => data); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create()) @@ -1663,7 +1682,7 @@ public async Task SubmitRoleConsentsAsync_WithInvalidRoles_ThrowsControllerArgum .ReturnsLazily(() => data); A.CallTo(() => _companyRolesRepository.GetAgreementAssignedCompanyRolesUntrackedAsync(roleIds)) .Returns(companyRoleAssignedAgreements.ToAsyncEnumerable()); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create()) @@ -1704,7 +1723,7 @@ public async Task SubmitRoleConsentsAsync_WithoutAllRolesConsentGiven_ThrowsCont A.CallTo(() => _companyRolesRepository.GetAgreementAssignedCompanyRolesUntrackedAsync(A>._)) .Returns(companyRoleAssignedAgreements.ToAsyncEnumerable()); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, consents) @@ -1786,7 +1805,7 @@ public async Task SubmitRoleConsentsAsync_WithValidData_CallsExpected() removedCompanyRoleIds = companyRoleIds; }); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act await sut.SubmitRoleConsentAsync(applicationId, consents).ConfigureAwait(false); @@ -1824,7 +1843,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingApplication_ThrowsNotFo }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns((CompanyApplicationUserEmailData?)null); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(notExistingId) @@ -1833,7 +1852,7 @@ async Task Act() => await sut.SubmitRegistrationAsync(notExistingId) // Assert var ex = await Assert.ThrowsAsync(Act); ex.Message.Should().Be($"application {notExistingId} does not exist"); - A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(notExistingId, _identity.UserId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(notExistingId, _identity.IdentityId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) .MustHaveHappenedOnceExactly(); } @@ -1915,13 +1934,13 @@ public async Task SubmitRegistrationAsync_WithDocumentId_Success() DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT } }; - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, _checklistService, _identityService, _dateTimeProvider); // Act await sut.SubmitRegistrationAsync(applicationId); // Assert - A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.UserId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.IdentityId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) .MustHaveHappenedOnceExactly(); A.CallTo(() => _documentRepository.AttachAndModifyDocuments(A?, Action)>>.That.Matches(x => x.Count() == 2))) @@ -1981,8 +2000,11 @@ public async Task SubmitRegistrationAsync_InvalidStatus_ThrowsForbiddenException { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2003,7 +2025,7 @@ public async Task SubmitRegistrationAsync_InvalidStatus_ThrowsForbiddenException var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", "Munich", "Germany", uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns(new CompanyApplicationUserEmailData(statusId, true, _fixture.Create(), documents, companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2024,8 +2046,11 @@ public async Task SubmitRegistrationAsync_AlreadyClosed_ThrowsForbiddenException { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2046,7 +2071,7 @@ public async Task SubmitRegistrationAsync_AlreadyClosed_ThrowsForbiddenException }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns(new CompanyApplicationUserEmailData(statusId, true, _fixture.Create(), documents, companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2064,8 +2089,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyUser_ThrowsForbi { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2082,7 +2110,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyUser_ThrowsForbi }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns(new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, false, null, null!, companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2100,8 +2128,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingStreetName_ThrowsConfli { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2118,7 +2149,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingStreetName_ThrowsConfli }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .Returns(new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2134,8 +2165,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingAddressId_ThrowsConflic { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2146,7 +2180,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingAddressId_ThrowsConflic var companyData = new CompanyData("Test Company", null, "Strabe Street", "Munich", "Germany", uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2162,8 +2196,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyName_ThrowsConfl { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2174,7 +2211,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyName_ThrowsConfl var companyData = new CompanyData(string.Empty, Guid.NewGuid(), "Strabe Street", "Munich", "Germany", uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .Returns(new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2190,8 +2227,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingUniqueId_ThrowsConflict { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); var agreementConsents = new List<(Guid AgreementId, ConsentStatusId ConsentStatusId)> @@ -2202,7 +2242,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingUniqueId_ThrowsConflict var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", "Munich", "Germany", uniqueIdentifierData, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2218,8 +2258,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyRoleId_ThrowsCon { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var agreementConsents = new List<(Guid AgreementId, ConsentStatusId ConsentStatusId)> @@ -2230,7 +2273,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyRoleId_ThrowsCon var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", "Munich", "Germany", uniqueIds, companyRoleIdData); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2246,8 +2289,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingAgreementandConsent_Thr { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2255,7 +2301,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingAgreementandConsent_Thr var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", "Munich", "Germany", uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2271,8 +2317,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingCity_ThrowsConflictExce { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2283,7 +2332,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCity_ThrowsConflictExce var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", string.Empty, "Germany", uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2299,8 +2348,11 @@ public async Task SubmitRegistrationAsync_WithNotExistingCountry_ThrowsConflictE { // Arrange var userId = Guid.NewGuid(); - A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); - A.CallTo(() => _identityService.IdentityId).Returns(userId); + var identityData = A.Fake(); + A.CallTo(() => identityData.IdentityId).Returns(userId); + A.CallTo(() => identityData.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => identityData.CompanyId).Returns(Guid.NewGuid()); + A.CallTo(() => _identityService.IdentityData).Returns(identityData); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2312,7 +2364,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCountry_ThrowsConflictE var companyData = new CompanyData("Test Company", Guid.NewGuid(), "Strabe Street", "Munich", string.Empty, uniqueIds, companyRoleIds); A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, A>._)) .ReturnsLazily(() => new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, _fixture.Create(), Enumerable.Empty(), companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.SubmitRegistrationAsync(applicationId) @@ -2357,14 +2409,14 @@ public async Task SubmitRegistrationAsync_WithUserEmail_SendsMail() { setOptionalFields.Invoke(application); }); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, _portalRepositories, _checklistService, _identityService, _dateTimeProvider); // Act var result = await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert - A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.UserId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.IdentityId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) .MustHaveHappenedOnceExactly(); A.CallTo(() => _applicationRepository.AttachAndModifyCompanyApplication(applicationId, A>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _checklistService.CreateInitialChecklistAsync(applicationId)).MustHaveHappenedOnceExactly(); @@ -2407,14 +2459,14 @@ public async Task SubmitRegistrationAsync_WithoutUserEmail_DoesntSendMail() { setOptionalFields.Invoke(application); }); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, A.Fake>(), _portalRepositories, _checklistService, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, A.Fake>(), _portalRepositories, _checklistService, _identityService, _dateTimeProvider); // Act var result = await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert - A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.UserId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.IdentityId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) .MustHaveHappenedOnceExactly(); A.CallTo(() => _applicationRepository.AttachAndModifyCompanyApplication(applicationId, A>._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _checklistService.CreateInitialChecklistAsync(applicationId)).MustHaveHappenedOnceExactly(); @@ -2442,7 +2494,6 @@ public async Task GetCompanyIdentifiers_ReturnsExpectedOutput() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -2474,7 +2525,6 @@ public async Task GetCompanyIdentifiers_InvalidCountry_Throws() null!, null!, null!, - null!, _portalRepositories, null!, _identityService, @@ -2502,7 +2552,7 @@ public async Task GetRegistrationDataAsync_ReturnsExpected() A.CallTo(() => _applicationRepository.GetRegistrationDataUntrackedAsync(_existingApplicationId, _identity.CompanyId, A>._)) .Returns((true, true, data)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var result = await sut.GetRegistrationDataAsync(_existingApplicationId).ConfigureAwait(false); @@ -2547,7 +2597,7 @@ public async Task GetRegistrationDataAsync_WithInvalidApplicationId_Throws() A.CallTo(() => _applicationRepository.GetRegistrationDataUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((false, false, data)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = () => sut.GetRegistrationDataAsync(applicationId); @@ -2566,7 +2616,7 @@ public async Task GetRegistrationDataAsync_WithInvalidUser_Throws() A.CallTo(() => _applicationRepository.GetRegistrationDataUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((true, false, data)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = () => sut.GetRegistrationDataAsync(applicationId); @@ -2585,7 +2635,7 @@ public async Task GetRegistrationDataAsync_WithNullData_Throws() A.CallTo(() => _applicationRepository.GetRegistrationDataUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((true, true, null)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = () => sut.GetRegistrationDataAsync(applicationId); @@ -2605,7 +2655,7 @@ public async Task GetRegistrationDocumentAsync_ReturnsExpectedResult() var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple(content, "test.json", true, MediaTypeId.JSON)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); //Act var result = await sut.GetRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2624,7 +2674,7 @@ public async Task GetRegistrationDocumentAsync_WithInvalidDocumentTypeId_ThrowsN var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple(content, "test.json", false, MediaTypeId.JSON)); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); //Act var Act = () => sut.GetRegistrationDocumentAsync(documentId); @@ -2642,7 +2692,7 @@ public async Task GetRegistrationDocumentAsync_WithInvalidDocumentId_ThrowsNotFo var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentAsync(documentId, A>._)) .ReturnsLazily(() => new ValueTuple()); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); //Act var Act = () => sut.GetRegistrationDocumentAsync(documentId); @@ -2660,11 +2710,11 @@ public async Task GetDocumentAsync_WithValidData_ReturnsExpected() // Arrange var documentId = Guid.NewGuid(); var content = new byte[7]; - A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.UserId)) + A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.IdentityId)) .ReturnsLazily(() => new ValueTuple(documentId, true)); A.CallTo(() => _documentRepository.GetDocumentByIdAsync(documentId)) .ReturnsLazily(() => new Document(documentId, content, content, "test.pdf", MediaTypeId.PDF, DateTimeOffset.UtcNow, DocumentStatusId.LOCKED, DocumentTypeId.APP_CONTRACT)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var result = await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); @@ -2681,9 +2731,9 @@ public async Task GetDocumentAsync_WithoutDocument_ThrowsNotFoundException() // Arrange var documentId = Guid.NewGuid(); var content = new byte[7]; - A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.UserId)) + A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.IdentityId)) .ReturnsLazily(() => new ValueTuple(Guid.Empty, false)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); @@ -2698,9 +2748,9 @@ public async Task GetDocumentAsync_WithWrongUser_ThrowsForbiddenException() { // Arrange var documentId = Guid.NewGuid(); - A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.UserId)) + A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.IdentityId)) .ReturnsLazily(() => new ValueTuple(documentId, false)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act async Task Act() => await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); @@ -2727,20 +2777,20 @@ public async Task SetInvitationStatusAsync_ReturnsExpected() .Create(); A.CallTo(() => _dateTimeProvider.OffsetNow).Returns(now); - A.CallTo(() => _invitationRepository.GetInvitationStatusAsync(_identity.UserId)) + A.CallTo(() => _invitationRepository.GetInvitationStatusAsync(_identity.IdentityId)) .Returns(invitation); A.CallTo(() => _applicationRepository.AttachAndModifyCompanyApplication(A._, A>._)) .Invokes((Guid _, Action setOptionalFields) => { setOptionalFields.Invoke(application); }); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var result = await sut.SetInvitationStatusAsync().ConfigureAwait(false); // Assert - A.CallTo(() => _invitationRepository.GetInvitationStatusAsync(_identity.UserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _invitationRepository.GetInvitationStatusAsync(_identity.IdentityId)).MustHaveHappenedOnceExactly(); A.CallTo(() => _applicationRepository.AttachAndModifyCompanyApplication(A._, A>._)).MustHaveHappenedOnceExactly(); invitation.InvitationStatusId.Should().Be(InvitationStatusId.ACCEPTED); application.DateLastChanged.Should().Be(now); @@ -2752,7 +2802,7 @@ public async Task SetInvitationStatusAsync_Throws_ForbiddenException() // Arrange A.CallTo(() => _invitationRepository.GetInvitationStatusAsync(A._)) .Returns((Invitation)null!); - var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); //Act var Act = async () => await sut.SetInvitationStatusAsync().ConfigureAwait(false); @@ -2806,7 +2856,7 @@ public async Task DeleteRegistrationDocumentAsync_ReturnsExpected() A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, _identity.CompanyId, settings.ApplicationStatusIds)) .Returns((documentId, DocumentStatusId.PENDING, true, DocumentTypeId.CX_FRAME_CONTRACT, false, applicationIds)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var result = await sut.DeleteRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2845,7 +2895,7 @@ public async Task DeleteRegistrationDocumentAsync_DocumentTypeId_ConflictExcepti A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, _identity.CompanyId, settings.ApplicationStatusIds)) .Returns((documentId, DocumentStatusId.PENDING, true, DocumentTypeId.CONFORMITY_APPROVAL_BUSINESS_APPS, false, applicationId)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2862,7 +2912,7 @@ public async Task DeleteRegistrationDocumentAsync_Throws_NotFoundException() A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns(new ValueTuple>()); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(_fixture.Create()).ConfigureAwait(false); @@ -2893,7 +2943,7 @@ public async Task DeleteRegistrationDocumentAsync_Throws_ConflictException() A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((documentId, DocumentStatusId.PENDING, true, DocumentTypeId.CX_FRAME_CONTRACT, true, applicationId)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2924,7 +2974,7 @@ public async Task DeleteRegistrationDocumentAsync_Throws_ForbiddenException() A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((documentId, DocumentStatusId.PENDING, false, DocumentTypeId.CX_FRAME_CONTRACT, false, applicationId)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2955,7 +3005,7 @@ public async Task DeleteRegistrationDocumentAsync_DocumentStatusId_Throws_Confli A.CallTo(() => _documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(A._, _identity.CompanyId, A>._)) .Returns((documentId, DocumentStatusId.LOCKED, true, DocumentTypeId.CX_FRAME_CONTRACT, false, applicationId)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(settings), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2969,7 +3019,7 @@ public async Task DeleteRegistrationDocumentAsync_DocumentStatusId_Throws_Confli public async Task DeleteRegistrationDocumentAsync_Throws_ControllerArgumentException() { // Arrange; - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, _portalRepositories, null!, _identityService, _dateTimeProvider); // Act var Act = async () => await sut.DeleteRegistrationDocumentAsync(default).ConfigureAwait(false); @@ -2986,16 +3036,12 @@ public async Task DeleteRegistrationDocumentAsync_Throws_ControllerArgumentExcep private void SetupRepositories() { var invitedUserRole = _fixture.CreateMany(2).AsEnumerable(); - var invitedUser = _fixture.CreateMany(1).ToAsyncEnumerable(); + var invitedUser = _fixture.CreateMany<(InvitationStatusId InvitationStatus, string? EmailId, IEnumerable Roles)>(1).ToAsyncEnumerable(); A.CallTo(() => _invitationRepository.GetInvitedUserDetailsUntrackedAsync(_existingApplicationId)) .Returns(invitedUser); A.CallTo(() => _invitationRepository.GetInvitedUserDetailsUntrackedAsync(Guid.Empty)).Throws(new Exception()); - A.CallTo(() => _provisioningManager.GetClientRoleMappingsForUserAsync(A._, A._)) - .Returns(invitedUserRole); - A.CallTo(() => _provisioningManager.GetClientRoleMappingsForUserAsync(string.Empty, string.Empty)).Throws(new Exception()); - A.CallTo(() => _applicationRepository.IsValidApplicationForCompany(_existingApplicationId, _identity.CompanyId)) .Returns(true); A.CallTo(() => _applicationRepository.IsValidApplicationForCompany(_existingApplicationId, A.That.Not.Matches(x => x == _identity.CompanyId))) diff --git a/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs b/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs index 384b1c7d36..3985c90f5d 100644 --- a/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs +++ b/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs @@ -37,7 +37,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Registration.Service.Tests; public class RegistrationControllerTest { - private readonly IdentityData _identity = new("7478542d-7878-47a8-a931-08bd8779532d", Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + private readonly IIdentityData _identity; private readonly IFixture _fixture; private readonly RegistrationController _controller; private readonly IRegistrationBusinessLogic _registrationBusinessLogicFake; @@ -45,6 +45,10 @@ public class RegistrationControllerTest public RegistrationControllerTest() { _fixture = new Fixture(); + _identity = A.Fake(); + A.CallTo(() => _identity.IdentityId).Returns(Guid.NewGuid()); + A.CallTo(() => _identity.IdentityTypeId).Returns(IdentityTypeId.COMPANY_USER); + A.CallTo(() => _identity.CompanyId).Returns(Guid.NewGuid()); _registrationBusinessLogicFake = A.Fake(); _controller = new RegistrationController(_registrationBusinessLogicFake); _controller.AddControllerContextWithClaimAndBearer("ac-token", _identity); diff --git a/tests/shared/Tests.Shared/Extensions/ControllerExtensions.cs b/tests/shared/Tests.Shared/Extensions/ControllerExtensions.cs index 639fc60194..a27c6f3545 100644 --- a/tests/shared/Tests.Shared/Extensions/ControllerExtensions.cs +++ b/tests/shared/Tests.Shared/Extensions/ControllerExtensions.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -20,7 +19,6 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; -using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Identities; using System.Security.Claims; @@ -38,15 +36,12 @@ public static class ControllerExtensions /// The controller that should be enriched /// Id of the iamUser /// identity of the user - public static void AddControllerContextWithClaim(this ControllerBase controller, string iamUserId, IdentityData? identity = null) + public static void AddControllerContextWithClaim(this ControllerBase controller, IIdentityData? identity = null) { var claimsIdentity = new ClaimsIdentity(); - claimsIdentity.AddClaims(new[] { new Claim("sub", iamUserId) }); if (identity != null) { - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.IdentityId, identity.UserId.ToString()) }); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.IdentityType, Enum.GetName(identity.IdentityType) ?? throw new UnexpectedConditionException("itentityType should never be out of enum-values range here")) }); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.CompanyId, identity.CompanyId.ToString()) }); + claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.PreferredUserName, identity.IdentityId.ToString()) }); } var httpContext = new DefaultHttpContext @@ -68,13 +63,10 @@ public static void AddControllerContextWithClaim(this ControllerBase controller, /// The controller that should be enriched /// Access token /// Identity of the user - public static void AddControllerContextWithClaimAndBearer(this ControllerBase controller, string accessToken, IdentityData identity) + public static void AddControllerContextWithClaimAndBearer(this ControllerBase controller, string accessToken, IIdentityData identity) { var claimsIdentity = new ClaimsIdentity(); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.Sub, identity.UserEntityId) }); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.IdentityId, identity.UserId.ToString()) }); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.IdentityType, Enum.GetName(identity.IdentityType) ?? throw new UnexpectedConditionException("itentityType should never be out of enum-values range here")) }); - claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.CompanyId, identity.CompanyId.ToString()) }); + claimsIdentity.AddClaims(new[] { new Claim(PortalClaimTypes.PreferredUserName, identity.IdentityId.ToString()) }); var httpContext = new DefaultHttpContext { diff --git a/tests/shared/Tests.Shared/FakeIdentityService.cs b/tests/shared/Tests.Shared/FakeIdentityService.cs index 704db8d436..df83688ff5 100644 --- a/tests/shared/Tests.Shared/FakeIdentityService.cs +++ b/tests/shared/Tests.Shared/FakeIdentityService.cs @@ -26,11 +26,9 @@ public class FakeIdentityService : IIdentityService { private readonly Guid _identityId = new("ac1cf001-7fbc-1f2f-817f-bce058020001"); - public ValueTask GetIdentityData() => ValueTask.FromResult(IdentityData); - /// - public IdentityData IdentityData => - new("3d8142f1-860b-48aa-8c2b-1ccb18699f65", _identityId, IdentityTypeId.COMPANY_USER, new Guid("2dc4249f-b5ca-4d42-bef1-7a7a950a4f87")); + public IIdentityData IdentityData => + new FakeIdentityData(_identityId, IdentityTypeId.COMPANY_USER, new Guid("2dc4249f-b5ca-4d42-bef1-7a7a950a4f87")); - public Guid IdentityId { get => _identityId; } + private record FakeIdentityData(Guid IdentityId, IdentityTypeId IdentityTypeId, Guid CompanyId) : IIdentityData; } diff --git a/tests/shared/Tests.Shared/IntegrationTests/FakePolicyEvaluator.cs b/tests/shared/Tests.Shared/IntegrationTests/FakePolicyEvaluator.cs index feb5df5de6..dab99eed9f 100644 --- a/tests/shared/Tests.Shared/IntegrationTests/FakePolicyEvaluator.cs +++ b/tests/shared/Tests.Shared/IntegrationTests/FakePolicyEvaluator.cs @@ -1,5 +1,4 @@ /******************************************************************************** - * Copyright (c) 2021, 2023 BMW Group AG * Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional @@ -23,7 +22,6 @@ using Microsoft.AspNetCore.Authorization.Policy; using Microsoft.AspNetCore.Http; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using System.Security.Claims; namespace Org.Eclipse.TractusX.Portal.Backend.Tests.Shared.IntegrationTests; @@ -35,12 +33,9 @@ public async Task AuthenticateAsync(AuthorizationPolicy poli var testScheme = "FakeScheme"; var principal = new ClaimsPrincipal(); principal.AddIdentity(new ClaimsIdentity(new[] { - new Claim(PortalClaimTypes.Sub, "3d8142f1-860b-48aa-8c2b-1ccb18699f65"), + new Claim(PortalClaimTypes.PreferredUserName, "ac1cf001-7fbc-1f2f-817f-bce058020001"), new Claim(ClaimTypes.Role, "Administrator"), - new Claim(ClaimTypes.NameIdentifier, "John"), - new Claim(PortalClaimTypes.IdentityId, "ac1cf001-7fbc-1f2f-817f-bce058020001"), - new Claim(PortalClaimTypes.IdentityType, IdentityTypeId.COMPANY_USER.ToString()), - new Claim(PortalClaimTypes.CompanyId, "2dc4249f-b5ca-4d42-bef1-7a7a950a4f87") + new Claim(ClaimTypes.NameIdentifier, "John") }, testScheme)); return await Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, diff --git a/tests/shared/Tests.Shared/IntegrationTests/IntegrationTestFactory.cs b/tests/shared/Tests.Shared/IntegrationTests/IntegrationTestFactory.cs index b51d8afddd..3bab7d76c4 100644 --- a/tests/shared/Tests.Shared/IntegrationTests/IntegrationTestFactory.cs +++ b/tests/shared/Tests.Shared/IntegrationTests/IntegrationTestFactory.cs @@ -28,7 +28,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Org.Eclipse.TractusX.Portal.Backend.Framework.Logging; -using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Identities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.Migrations.Seeder; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Auditing; @@ -62,7 +61,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) }); builder.ConfigureTestServices(services => { - var identityService = services.SingleOrDefault(d => d.ServiceType == typeof(IdentityService)); + var identityService = services.SingleOrDefault(d => d.ServiceType.GetInterfaces().Contains(typeof(IIdentityService))); if (identityService != null) services.Remove(identityService); services.AddScoped(); diff --git a/tests/shared/Tests.Shared/TestSeeds/BaseSeed.cs b/tests/shared/Tests.Shared/TestSeeds/BaseSeed.cs index d54fe2dd76..776d95ff34 100644 --- a/tests/shared/Tests.Shared/TestSeeds/BaseSeed.cs +++ b/tests/shared/Tests.Shared/TestSeeds/BaseSeed.cs @@ -59,9 +59,6 @@ public static Action SeedBaseData() => dbContext => { new(new Guid("ac1cf001-7fbc-1f2f-817f-bce058020001"), DateTimeOffset.UtcNow, new Guid("2dc4249f-b5ca-4d42-bef1-7a7a950a4f87"), UserStatusId.ACTIVE, IdentityTypeId.COMPANY_USER) - { - UserEntityId = "3d8142f1-860b-48aa-8c2b-1ccb18699f65" - } }); dbContext.CompanyUsers.AddRange(new List