diff --git a/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs index cf32908b8a..ebdd4d233d 100644 --- a/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/DocumentsBusinessLogic.cs @@ -26,6 +26,7 @@ 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; namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLogic; @@ -35,22 +36,24 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public class DocumentsBusinessLogic : IDocumentsBusinessLogic { private readonly IPortalRepositories _portalRepositories; + private readonly IIdentityService _identityService; private readonly DocumentSettings _settings; /// /// Creates a new instance /// - public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IOptions options) + public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IOptions options) { _portalRepositories = portalRepositories; + _identityService = identityService; _settings = options.Value; } /// - public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentAsync(Guid documentId, Guid companyId) + public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentAsync(Guid documentId) { var documentDetails = await _portalRepositories.GetInstance() - .GetDocumentDataAndIsCompanyUserAsync(documentId, companyId) + .GetDocumentDataAndIsCompanyUserAsync(documentId, _identityService.IdentityData.CompanyId) .ConfigureAwait(false); if (documentDetails == default) { @@ -84,10 +87,10 @@ public DocumentsBusinessLogic(IPortalRepositories portalRepositories, IOptions - public async Task DeleteDocumentAsync(Guid documentId, Guid companyUserId) + public async Task DeleteDocumentAsync(Guid documentId) { var documentRepository = _portalRepositories.GetInstance(); - var details = await documentRepository.GetDocumentDetailsForIdUntrackedAsync(documentId, companyUserId).ConfigureAwait(false); + var details = await documentRepository.GetDocumentDetailsForIdUntrackedAsync(documentId, _identityService.IdentityData.UserId).ConfigureAwait(false); if (details.DocumentId == Guid.Empty) { diff --git a/src/administration/Administration.Service/BusinessLogic/IDocumentsBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IDocumentsBusinessLogic.cs index cefe377cfe..cd90e89744 100644 --- a/src/administration/Administration.Service/BusinessLogic/IDocumentsBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IDocumentsBusinessLogic.cs @@ -31,9 +31,8 @@ public interface IDocumentsBusinessLogic /// Gets the document with the given id /// /// Id of the document to get - /// Company of the user /// Returns the filename and content of the file - Task<(string FileName, byte[] Content, string MediaType)> GetDocumentAsync(Guid documentId, Guid companyId); + Task<(string FileName, byte[] Content, string MediaType)> GetDocumentAsync(Guid documentId); /// /// Gets the selfdescription document with the given id @@ -46,9 +45,8 @@ public interface IDocumentsBusinessLogic /// Deletes the document and the corresponding consent from the persistence layer. /// /// Id of the document that should be deleted - /// /// Returns true if the document and corresponding consent were deleted successfully. Otherwise a specific error is thrown. - Task DeleteDocumentAsync(Guid documentId, Guid companyUserId); + Task DeleteDocumentAsync(Guid documentId); /// /// Gets the document as json for the seeding data diff --git a/src/administration/Administration.Service/BusinessLogic/IIdentityProviderBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IIdentityProviderBusinessLogic.cs index ad7198144a..d80c8a3ca8 100644 --- a/src/administration/Administration.Service/BusinessLogic/IIdentityProviderBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IIdentityProviderBusinessLogic.cs @@ -33,12 +33,12 @@ public interface IIdentityProviderBusinessLogic ValueTask SetOwnCompanyIdentityProviderStatusAsync(Guid identityProviderId, bool enabled); ValueTask UpdateOwnCompanyIdentityProviderAsync(Guid identityProviderId, IdentityProviderEditableDetails details); ValueTask DeleteCompanyIdentityProviderAsync(Guid identityProviderId); - IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync(IEnumerable identityProviderIds, Guid companyId, bool unlinkedUsersOnly); - (Stream FileStream, string ContentType, string FileName, Encoding Encoding) GetOwnCompanyUsersIdentityProviderLinkDataStream(IEnumerable identityProviderIds, Guid companyId, bool unlinkedUsersOnly); - ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataAsync(IFormFile document, Guid companyId, CancellationToken cancellationToken); - ValueTask CreateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, UserIdentityProviderLinkData identityProviderLinkData, Guid companyId); - ValueTask CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, UserLinkData userLinkData, Guid companyId); - ValueTask GetOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId); - ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId); + IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync(IEnumerable identityProviderIds, bool unlinkedUsersOnly); + (Stream FileStream, string ContentType, string FileName, Encoding Encoding) GetOwnCompanyUsersIdentityProviderLinkDataStream(IEnumerable identityProviderIds, bool unlinkedUsersOnly); + ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataAsync(IFormFile document, CancellationToken cancellationToken); + ValueTask CreateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, UserIdentityProviderLinkData identityProviderLinkData); + ValueTask CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, UserLinkData userLinkData); + ValueTask GetOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId); + ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid companyUserId, Guid identityProviderId); ValueTask GetOwnIdentityProviderWithConnectedCompanies(Guid identityProviderId); } diff --git a/src/administration/Administration.Service/BusinessLogic/IServiceAccountBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IServiceAccountBusinessLogic.cs index 74972bb9df..3e80897454 100644 --- a/src/administration/Administration.Service/BusinessLogic/IServiceAccountBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IServiceAccountBusinessLogic.cs @@ -27,11 +27,11 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public interface IServiceAccountBusinessLogic { - Task CreateOwnCompanyServiceAccountAsync(ServiceAccountCreationInfo serviceAccountCreationInfos, Guid companyId); - Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId, Guid companyId); - Task GetOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, Guid companyId); - Task UpdateOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, ServiceAccountEditableDetails serviceAccountDetails, Guid companyId); - Task ResetOwnCompanyServiceAccountSecretAsync(Guid serviceAccountId, Guid companyId); - Task> GetOwnCompanyServiceAccountsDataAsync(int page, int size, Guid companyId, string? clientId, bool? isOwner); - IAsyncEnumerable GetServiceAccountRolesAsync(Guid companyId, string? languageShortName); + Task CreateOwnCompanyServiceAccountAsync(ServiceAccountCreationInfo serviceAccountCreationInfos); + Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId); + Task GetOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId); + Task UpdateOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, ServiceAccountEditableDetails serviceAccountDetails); + Task ResetOwnCompanyServiceAccountSecretAsync(Guid serviceAccountId); + Task> GetOwnCompanyServiceAccountsDataAsync(int page, int size, string? clientId, bool? isOwner); + IAsyncEnumerable GetServiceAccountRolesAsync(string? languageShortName); } diff --git a/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs index c2ee708094..a4163be04e 100644 --- a/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/ISubscriptionConfigurationBusinessLogic.cs @@ -60,12 +60,12 @@ public interface ISubscriptionConfigurationBusinessLogic /// /// Id of the users company /// The detail data - Task GetProviderCompanyDetailsAsync(Guid companyId); + Task GetProviderCompanyDetailsAsync(); /// /// Sets service provider company details /// /// Detail data for the service provider /// Id of the users company - Task SetProviderCompanyDetailsAsync(ProviderDetailData data, Guid companyId); + Task SetProviderCompanyDetailsAsync(ProviderDetailData data); } diff --git a/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs index cbf8b21a2f..ce4289f661 100644 --- a/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IUserBusinessLogic.cs @@ -29,16 +29,16 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog /// public interface IUserBusinessLogic { - IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable userList, (Guid UserId, Guid CompanyId) identity); - Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, UserCreationInfoIdp userCreationInfo, (Guid UserId, Guid CompanyId) identity); - Task> GetOwnCompanyUserDatasAsync(Guid companyId, int page, int size, GetOwnCompanyUsersFilter filter); + IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable userList); + Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, UserCreationInfoIdp userCreationInfo); + Task> GetOwnCompanyUserDatasAsync(int page, int size, GetOwnCompanyUsersFilter filter); [Obsolete("to be replaced by UserRolesBusinessLogic.GetAppRolesAsync. Remove as soon frontend is adjusted")] IAsyncEnumerable GetClientRolesAsync(Guid appId, string? languageShortName = null); - Task GetOwnCompanyUserDetailsAsync(Guid userId, Guid companyId); - Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId, IEnumerable businessPartnerNumbers, Guid companyId); - Task AddOwnCompanyUsersBusinessPartnerNumberAsync(Guid userId, string businessPartnerNumber, Guid companyId); - Task GetOwnUserDetails(Guid userId); - Task UpdateOwnUserDetails(Guid companyUserId, OwnCompanyUserEditableDetails ownCompanyUserEditableDetails, Guid userId); + Task GetOwnCompanyUserDetailsAsync(Guid userId); + Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId, IEnumerable businessPartnerNumbers); + Task AddOwnCompanyUsersBusinessPartnerNumberAsync(Guid userId, string businessPartnerNumber); + Task GetOwnUserDetails(); + Task UpdateOwnUserDetails(Guid companyUserId, OwnCompanyUserEditableDetails ownCompanyUserEditableDetails); /// /// Delete User Own Account using userId @@ -46,9 +46,9 @@ public interface IUserBusinessLogic /// /// /// - Task DeleteOwnUserAsync(Guid companyUserId, Guid userId); - IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable userIds, Guid companyId); - Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId, (Guid UserId, Guid CompanyId) identity); - Task> GetOwnCompanyAppUsersAsync(Guid appId, Guid userId, int page, int size, CompanyUserFilter filter); - Task DeleteOwnUserBusinessPartnerNumbersAsync(Guid userId, string businessPartnerNumber, (Guid UserId, Guid CompanyId) identity); + Task DeleteOwnUserAsync(Guid companyUserId); + IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable userIds); + Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId); + Task> GetOwnCompanyAppUsersAsync(Guid appId, int page, int size, CompanyUserFilter filter); + Task DeleteOwnUserBusinessPartnerNumbersAsync(Guid userId, string businessPartnerNumber); } diff --git a/src/administration/Administration.Service/BusinessLogic/IUserRolesBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IUserRolesBusinessLogic.cs index 1334043b2b..76f6022206 100644 --- a/src/administration/Administration.Service/BusinessLogic/IUserRolesBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IUserRolesBusinessLogic.cs @@ -25,8 +25,8 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public interface IUserRolesBusinessLogic { - IAsyncEnumerable GetCoreOfferRoles(Guid companyId, string? languageShortName); - IAsyncEnumerable GetAppRolesAsync(Guid appId, Guid companyId, string? languageShortName); + IAsyncEnumerable GetCoreOfferRoles(string? languageShortName); + IAsyncEnumerable GetAppRolesAsync(Guid appId, string? languageShortName); /// /// Update Role to User @@ -34,9 +34,8 @@ public interface IUserRolesBusinessLogic /// /// /// - /// CompanyId of Admin User /// messages - Task> ModifyCoreOfferUserRolesAsync(Guid offerId, Guid companyUserId, IEnumerable roles, Guid companyId); + Task> ModifyCoreOfferUserRolesAsync(Guid offerId, Guid companyUserId, IEnumerable roles); /// /// Update Role to User @@ -44,17 +43,15 @@ public interface IUserRolesBusinessLogic /// /// /// - /// CompanyId of Admin User /// messages - Task> ModifyAppUserRolesAsync(Guid appId, Guid companyUserId, IEnumerable roles, Guid companyId); + Task> ModifyAppUserRolesAsync(Guid appId, Guid companyUserId, IEnumerable roles); /// /// Update Role to User /// /// app Id /// User and Role Information like CompanyUser Id and Role Name - /// CompanyId of Admin User /// messages [Obsolete("to be replaced by endpoint UserRolesBusinessLogic.ModifyAppUserRolesAsync. Remove as soon frontend is adjusted")] - Task> ModifyUserRoleAsync(Guid appId, UserRoleInfo userRoleInfo, Guid companyId); + Task> ModifyUserRoleAsync(Guid appId, UserRoleInfo userRoleInfo); } diff --git a/src/administration/Administration.Service/BusinessLogic/IUserUploadBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IUserUploadBusinessLogic.cs index d984353291..95628f3ba7 100644 --- a/src/administration/Administration.Service/BusinessLogic/IUserUploadBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IUserUploadBusinessLogic.cs @@ -24,6 +24,6 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Administration.Service.BusinessLog public interface IUserUploadBusinessLogic { - ValueTask UploadOwnCompanyIdpUsersAsync(Guid identityProviderId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken); - ValueTask UploadOwnCompanySharedIdpUsersAsync(IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken); + ValueTask UploadOwnCompanyIdpUsersAsync(Guid identityProviderId, IFormFile document, CancellationToken cancellationToken); + ValueTask UploadOwnCompanySharedIdpUsersAsync(IFormFile document, CancellationToken cancellationToken); } diff --git a/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs index 6b6440652e..b9f3c6e231 100644 --- a/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/IdentityProviderBusinessLogic.cs @@ -138,8 +138,7 @@ private async ValueTask CreateOwnCompanyIdentityProvide public async ValueTask GetOwnCompanyIdentityProviderAsync(Guid identityProviderId) { - var companyId = _identityService.IdentityData.CompanyId; - var (alias, category, typeId) = await ValidateGetOwnCompanyIdentityProviderArguments(identityProviderId, companyId).ConfigureAwait(false); + var (alias, category, typeId) = await ValidateGetOwnCompanyIdentityProviderArguments(identityProviderId).ConfigureAwait(false); return category switch { @@ -149,8 +148,9 @@ public async ValueTask GetOwnCompanyIdentityProviderAsy }; } - private async ValueTask<(string Alias, IdentityProviderCategoryId Category, IdentityProviderTypeId TypeId)> ValidateGetOwnCompanyIdentityProviderArguments(Guid identityProviderId, Guid companyId) + private async ValueTask<(string Alias, IdentityProviderCategoryId Category, IdentityProviderTypeId TypeId)> ValidateGetOwnCompanyIdentityProviderArguments(Guid identityProviderId) { + var companyId = _identityService.IdentityData.CompanyId; var (alias, category, isOwnOrOwnerCompany, typeId) = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderAliasUntrackedAsync(identityProviderId, companyId).ConfigureAwait(false); if (!isOwnOrOwnerCompany) { @@ -172,8 +172,7 @@ public async ValueTask GetOwnCompanyIdentityProviderAsy public async ValueTask SetOwnCompanyIdentityProviderStatusAsync(Guid identityProviderId, bool enabled) { - var companyId = _identityService.IdentityData.CompanyId; - var (category, alias, typeId) = await ValidateSetOwnCompanyIdentityProviderStatusArguments(identityProviderId, enabled, companyId).ConfigureAwait(false); + var (category, alias, typeId) = await ValidateSetOwnCompanyIdentityProviderStatusArguments(identityProviderId, enabled).ConfigureAwait(false); switch (category) { @@ -191,8 +190,9 @@ public async ValueTask SetOwnCompanyIdentityProviderSta } } - private async ValueTask<(IdentityProviderCategoryId Category, string Alias, IdentityProviderTypeId TypeId)> ValidateSetOwnCompanyIdentityProviderStatusArguments(Guid identityProviderId, bool enabled, Guid companyId) + private async ValueTask<(IdentityProviderCategoryId Category, string Alias, IdentityProviderTypeId TypeId)> ValidateSetOwnCompanyIdentityProviderStatusArguments(Guid identityProviderId, bool enabled) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(identityProviderId, companyId, true).ConfigureAwait(false); if (result == default) { @@ -323,7 +323,7 @@ private async ValueTask ValidateOtherActiveIdentityProvider(string? alias, public async ValueTask DeleteCompanyIdentityProviderAsync(Guid identityProviderId) { var companyId = _identityService.IdentityData.CompanyId; - var (alias, typeId) = await ValidateDeleteOwnCompanyIdentityProviderArguments(identityProviderId, companyId).ConfigureAwait(false); + var (alias, typeId) = await ValidateDeleteOwnCompanyIdentityProviderArguments(identityProviderId).ConfigureAwait(false); _portalRepositories.Remove(new CompanyIdentityProvider(companyId, identityProviderId)); @@ -341,8 +341,9 @@ public async ValueTask DeleteCompanyIdentityProviderAsync(Guid identityProviderI await _portalRepositories.SaveAsync().ConfigureAwait(false); } - private async ValueTask<(string? Alias, IdentityProviderTypeId TypeId)> ValidateDeleteOwnCompanyIdentityProviderArguments(Guid identityProviderId, Guid companyId) + private async ValueTask<(string? Alias, IdentityProviderTypeId TypeId)> ValidateDeleteOwnCompanyIdentityProviderArguments(Guid identityProviderId) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyIdentityProviderUpdateDataUntrackedAsync(identityProviderId, companyId, true).ConfigureAwait(false); if (result == default) { @@ -470,8 +471,9 @@ private async ValueTask GetIdentityProviderDetailsSaml( }; } - public async ValueTask CreateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, UserIdentityProviderLinkData identityProviderLinkData, Guid companyId) + public async ValueTask CreateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, UserIdentityProviderLinkData identityProviderLinkData) { + var companyId = _identityService.IdentityData.CompanyId; var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderLinkData.identityProviderId, companyId).ConfigureAwait(false); try @@ -495,8 +497,9 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync( identityProviderLinkData.userName); } - public async ValueTask CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, UserLinkData userLinkData, Guid companyId) + 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); try @@ -521,8 +524,9 @@ await _provisioningManager.AddProviderUserLinkToCentralUserAsync( userLinkData.userName); } - public async ValueTask GetOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) + public async ValueTask GetOwnCompanyUserIdentityProviderLinkDataAsync(Guid companyUserId, Guid identityProviderId) { + var companyId = _identityService.IdentityData.CompanyId; var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); var result = await _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId).FirstOrDefaultAsync(identityProviderLink => identityProviderLink.Alias == alias).ConfigureAwait(false); @@ -537,8 +541,9 @@ public async ValueTask GetOwnCompanyUserIdentityPr result.UserName); } - public async ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid companyUserId, Guid identityProviderId, Guid companyId) + public async ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync(Guid companyUserId, Guid identityProviderId) { + var companyId = _identityService.IdentityData.CompanyId; var (userEntityId, alias) = await GetUserAliasDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); try { @@ -580,8 +585,9 @@ public async ValueTask GetOwnIden return new(details.identityProviderId, details.alias, details.identityProviderCategoryId, details.IdentityProviderTypeId, details.displayName, details.redirectUrl, details.enabled, connectedCompanies); } - public async IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync(IEnumerable identityProviderIds, Guid companyId, bool unlinkedUsersOnly) + public async IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync(IEnumerable identityProviderIds, bool unlinkedUsersOnly) { + var companyId = _identityService.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(); @@ -607,24 +613,26 @@ public async IAsyncEnumerable GetOwnCompanyUsersIdenti } } - public (Stream FileStream, string ContentType, string FileName, Encoding Encoding) GetOwnCompanyUsersIdentityProviderLinkDataStream(IEnumerable identityProviderIds, Guid companyId, bool unlinkedUsersOnly) + public (Stream FileStream, string ContentType, string FileName, Encoding Encoding) GetOwnCompanyUsersIdentityProviderLinkDataStream(IEnumerable identityProviderIds, bool unlinkedUsersOnly) { + var companyId = _identityService.IdentityData.CompanyId; var csvSettings = _settings.CsvSettings; return (new AsyncEnumerableStringStream(GetOwnCompanyUsersIdentityProviderDataLines(identityProviderIds, unlinkedUsersOnly, companyId), csvSettings.Encoding), csvSettings.ContentType, csvSettings.FileName, csvSettings.Encoding); } - public ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataAsync(IFormFile document, Guid companyId, CancellationToken cancellationToken) + public ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataAsync(IFormFile document, CancellationToken cancellationToken) { if (!document.ContentType.Equals(_settings.CsvSettings.ContentType, StringComparison.OrdinalIgnoreCase)) { throw new UnsupportedMediaTypeException($"Only contentType {_settings.CsvSettings.ContentType} files are allowed."); } - return UploadOwnCompanyUsersIdentityProviderLinkDataInternalAsync(document, companyId, cancellationToken); + return UploadOwnCompanyUsersIdentityProviderLinkDataInternalAsync(document, cancellationToken); } - private async ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataInternalAsync(IFormFile document, Guid companyId, CancellationToken cancellationToken) + private async ValueTask UploadOwnCompanyUsersIdentityProviderLinkDataInternalAsync(IFormFile document, CancellationToken cancellationToken) { var userRepository = _portalRepositories.GetInstance(); + var companyId = _identityService.IdentityData.CompanyId; var (sharedIdpAlias, existingAliase) = await GetCompanyAliasDataAsync(companyId).ConfigureAwait(false); using var stream = document.OpenReadStream(); diff --git a/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs index 4004f04cbc..917b3d3da1 100644 --- a/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/ServiceAccountBusinessLogic.cs @@ -26,6 +26,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Enums; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; @@ -38,21 +39,24 @@ public class ServiceAccountBusinessLogic : IServiceAccountBusinessLogic private readonly IProvisioningManager _provisioningManager; private readonly IPortalRepositories _portalRepositories; private readonly IServiceAccountCreation _serviceAccountCreation; + private readonly IIdentityService _identityService; private readonly ServiceAccountSettings _settings; public ServiceAccountBusinessLogic( IProvisioningManager provisioningManager, IPortalRepositories portalRepositories, IOptions options, - IServiceAccountCreation serviceAccountCreation) + IServiceAccountCreation serviceAccountCreation, + IIdentityService identityService) { _provisioningManager = provisioningManager; _portalRepositories = portalRepositories; _serviceAccountCreation = serviceAccountCreation; + _identityService = identityService; _settings = options.Value; } - public async Task CreateOwnCompanyServiceAccountAsync(ServiceAccountCreationInfo serviceAccountCreationInfos, Guid companyId) + public async Task CreateOwnCompanyServiceAccountAsync(ServiceAccountCreationInfo serviceAccountCreationInfos) { if (serviceAccountCreationInfos.IamClientAuthMethod != IamClientAuthMethod.SECRET) { @@ -63,6 +67,7 @@ public async Task CreateOwnCompanyServiceAccountAsync(Ser throw new ControllerArgumentException("name must not be empty", "name"); } + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().GetBpnAndTechnicalUserRoleIds(companyId, _settings.ClientId).ConfigureAwait(false); if (result == default) { @@ -94,9 +99,10 @@ public async Task CreateOwnCompanyServiceAccountAsync(Ser serviceAccountData.AuthData.Secret); } - public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId, Guid companyId) + public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId) { var serviceAccountRepository = _portalRepositories.GetInstance(); + var companyId = _identityService.IdentityData.CompanyId; var result = await serviceAccountRepository.GetOwnCompanyServiceAccountWithIamServiceAccountRolesAsync(serviceAccountId, companyId).ConfigureAwait(false); if (result == default) { @@ -139,8 +145,9 @@ public async Task DeleteOwnCompanyServiceAccountAsync(Guid serviceAccountId return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async Task GetOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, Guid companyId) + public async Task GetOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(serviceAccountId, companyId); if (result == null) { @@ -165,8 +172,9 @@ public async Task GetOwnCompanyServiceAccountD result.SubscriptionId); } - public async Task ResetOwnCompanyServiceAccountSecretAsync(Guid serviceAccountId, Guid companyId) + public async Task ResetOwnCompanyServiceAccountSecretAsync(Guid serviceAccountId) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().GetOwnCompanyServiceAccountDetailedDataUntrackedAsync(serviceAccountId, companyId); if (result == null) { @@ -189,7 +197,7 @@ public async Task ResetOwnCompanyServiceAccountSecretAsyn result.SubscriptionId); } - public async Task UpdateOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, ServiceAccountEditableDetails serviceAccountDetails, Guid companyId) + public async Task UpdateOwnCompanyServiceAccountDetailsAsync(Guid serviceAccountId, ServiceAccountEditableDetails serviceAccountDetails) { if (serviceAccountDetails.IamClientAuthMethod != IamClientAuthMethod.SECRET) { @@ -199,6 +207,8 @@ 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 serviceAccountRepository = _portalRepositories.GetInstance(); var result = await serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(serviceAccountId, companyId).ConfigureAwait(false); if (result == null) @@ -254,13 +264,13 @@ await _provisioningManager.UpdateCentralClientAsync( result.OfferSubscriptionId); } - public Task> GetOwnCompanyServiceAccountsDataAsync(int page, int size, Guid companyId, string? clientId, bool? isOwner) => + public Task> GetOwnCompanyServiceAccountsDataAsync(int page, int size, string? clientId, bool? isOwner) => Pagination.CreateResponseAsync( page, size, 15, - _portalRepositories.GetInstance().GetOwnCompanyServiceAccountsUntracked(companyId, clientId, isOwner)); + _portalRepositories.GetInstance().GetOwnCompanyServiceAccountsUntracked(_identityService.IdentityData.CompanyId, clientId, isOwner)); - IAsyncEnumerable IServiceAccountBusinessLogic.GetServiceAccountRolesAsync(Guid companyId, string? languageShortName) => - _portalRepositories.GetInstance().GetServiceAccountRolesAsync(companyId, _settings.ClientId, languageShortName ?? Constants.DefaultLanguage); + public IAsyncEnumerable GetServiceAccountRolesAsync(string? languageShortName) => + _portalRepositories.GetInstance().GetServiceAccountRolesAsync(_identityService.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 049e25c8cd..e349e01f19 100644 --- a/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/SubscriptionConfigurationBusinessLogic.cs @@ -24,6 +24,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Processes.OfferSubscription.Library; using Org.Eclipse.TractusX.Portal.Backend.Processes.OfferSubscription.Library.Extensions; @@ -33,16 +34,19 @@ public class SubscriptionConfigurationBusinessLogic : ISubscriptionConfiguration { private readonly IOfferSubscriptionProcessService _offerSubscriptionProcessService; private readonly IPortalRepositories _portalRepositories; + private readonly IIdentityService _identityService; - public SubscriptionConfigurationBusinessLogic(IOfferSubscriptionProcessService offerSubscriptionProcessService, IPortalRepositories portalRepositories) + public SubscriptionConfigurationBusinessLogic(IOfferSubscriptionProcessService offerSubscriptionProcessService, IPortalRepositories portalRepositories, IIdentityService identityService) { _offerSubscriptionProcessService = offerSubscriptionProcessService; _portalRepositories = portalRepositories; + _identityService = identityService; } /// - public async Task GetProviderCompanyDetailsAsync(Guid companyId) + public async Task GetProviderCompanyDetailsAsync() { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance() .GetProviderCompanyDetailAsync(CompanyRoleId.SERVICE_PROVIDER, companyId) .ConfigureAwait(false); @@ -59,7 +63,7 @@ public async Task GetProviderCompanyDetailsAsync(Guid } /// - public Task SetProviderCompanyDetailsAsync(ProviderDetailData data, Guid companyId) + public Task SetProviderCompanyDetailsAsync(ProviderDetailData data) { data.Url.EnsureValidHttpsUrl(() => nameof(data.Url)); data.CallbackUrl?.EnsureValidHttpsUrl(() => nameof(data.CallbackUrl)); @@ -70,7 +74,7 @@ public Task SetProviderCompanyDetailsAsync(ProviderDetailData data, Guid company "the maximum allowed length is 100 characters", nameof(data.Url)); } - return SetOfferProviderCompanyDetailsInternalAsync(data, companyId); + return SetOfferProviderCompanyDetailsInternalAsync(data, _identityService.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 18b9d3fc79..4fe574bad2 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserBusinessLogic.cs @@ -28,6 +28,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Provisioning.DBAccess; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; @@ -44,6 +45,7 @@ public class UserBusinessLogic : IUserBusinessLogic private readonly IUserProvisioningService _userProvisioningService; private readonly IProvisioningDBAccess _provisioningDbAccess; private readonly IPortalRepositories _portalRepositories; + private readonly IIdentityService _identityService; private readonly IMailingService _mailingService; private readonly ILogger _logger; private readonly UserSettings _settings; @@ -54,6 +56,7 @@ public class UserBusinessLogic : IUserBusinessLogic /// Provisioning Manager /// User Provisioning Service /// Provisioning DBAccess + /// Access to the identity /// Mailing Service /// logger /// Settings @@ -63,6 +66,7 @@ public UserBusinessLogic( IUserProvisioningService userProvisioningService, IProvisioningDBAccess provisioningDbAccess, IPortalRepositories portalRepositories, + IIdentityService identityService, IMailingService mailingService, ILogger logger, IOptions settings) @@ -71,12 +75,13 @@ public UserBusinessLogic( _userProvisioningService = userProvisioningService; _provisioningDbAccess = provisioningDbAccess; _portalRepositories = portalRepositories; + _identityService = identityService; _mailingService = mailingService; _logger = logger; _settings = settings.Value; } - public IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable userList, (Guid UserId, Guid CompanyId) identity) + public IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable userList) { var noUserNameAndEmail = userList.Where(user => string.IsNullOrEmpty(user.userName) && string.IsNullOrEmpty(user.eMail)); if (noUserNameAndEmail.Any()) @@ -88,16 +93,16 @@ public IAsyncEnumerable CreateOwnCompanyUsersAsync(IEnumerable user.userName ?? user.eMail))}'"); } - return CreateOwnCompanyUsersInternalAsync(userList, identity); + return CreateOwnCompanyUsersInternalAsync(userList); } - private async IAsyncEnumerable CreateOwnCompanyUsersInternalAsync(IEnumerable userList, (Guid UserId, Guid CompanyId) identity) + private async IAsyncEnumerable CreateOwnCompanyUsersInternalAsync(IEnumerable userList) { - var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(identity.UserId).ConfigureAwait(false); + var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identityService.IdentityData.UserId).ConfigureAwait(false); var distinctRoles = userList.SelectMany(user => user.Roles).Distinct().ToList(); - var roleDatas = await GetOwnCompanyUserRoleData(distinctRoles, identity.CompanyId).ConfigureAwait(false); + var roleDatas = await GetOwnCompanyUserRoleData(distinctRoles).ConfigureAwait(false); var userCreationInfoIdps = userList.Select(user => new UserCreationRoleDataIdpInfo( @@ -148,19 +153,19 @@ private async IAsyncEnumerable CreateOwnCompanyUsersInternalAsync(IEnume } } - private Task> GetOwnCompanyUserRoleData(IEnumerable roles, Guid companyId) + private Task> GetOwnCompanyUserRoleData(IEnumerable roles) { if (!roles.Any()) { Task.FromResult(Enumerable.Empty()); } - return _userProvisioningService.GetOwnCompanyPortalRoleDatas(_settings.Portal.KeycloakClientID, roles, companyId); + return _userProvisioningService.GetOwnCompanyPortalRoleDatas(_settings.Portal.KeycloakClientID, roles, _identityService.IdentityData.CompanyId); } - public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, UserCreationInfoIdp userCreationInfo, (Guid UserId, Guid CompanyId) identity) + public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, UserCreationInfoIdp userCreationInfo) { - var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, identity.UserId).ConfigureAwait(false); + var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, _identityService.IdentityData.UserId).ConfigureAwait(false); var displayName = await _userProvisioningService.GetIdentityProviderDisplayName(companyNameIdpAliasData.IdpAlias).ConfigureAwait(false); if (!userCreationInfo.Roles.Any()) @@ -168,7 +173,7 @@ public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, Us throw new ControllerArgumentException($"at least one role must be specified", nameof(userCreationInfo.Roles)); } - var roleDatas = await GetOwnCompanyUserRoleData(userCreationInfo.Roles, identity.CompanyId).ConfigureAwait(false); + var roleDatas = await GetOwnCompanyUserRoleData(userCreationInfo.Roles).ConfigureAwait(false); var result = await _userProvisioningService.CreateOwnCompanyIdpUsersAsync( companyNameIdpAliasData, @@ -218,11 +223,10 @@ public async Task CreateOwnCompanyIdpUserAsync(Guid identityProviderId, Us return result.CompanyUserId; } - public Task> GetOwnCompanyUserDatasAsync(Guid companyId, int page, int size, GetOwnCompanyUsersFilter filter) + public Task> GetOwnCompanyUserDatasAsync(int page, int size, GetOwnCompanyUsersFilter filter) { - var companyUsers = _portalRepositories.GetInstance().GetOwnCompanyUserQuery( - companyId, + _identityService.IdentityData.CompanyId, filter.CompanyUserId, filter.UserEntityId, filter.FirstName, @@ -272,8 +276,9 @@ public async IAsyncEnumerable GetClientRolesAsync(Guid appId, strin } } - public async Task GetOwnCompanyUserDetailsAsync(Guid userId, Guid companyId) + public async Task GetOwnCompanyUserDetailsAsync(Guid userId) { + var companyId = _identityService.IdentityData.CompanyId; var details = await _portalRepositories.GetInstance().GetOwnCompanyUserDetailsUntrackedAsync(userId, companyId).ConfigureAwait(false); if (details == null) { @@ -282,12 +287,13 @@ public async Task GetOwnCompanyUserDetailsAsync(Guid userId, return details; } - public async Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId, IEnumerable businessPartnerNumbers, Guid companyId) + public async Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId, IEnumerable businessPartnerNumbers) { if (businessPartnerNumbers.Any(businessPartnerNumber => businessPartnerNumber.Length > 20)) { 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) { @@ -304,11 +310,12 @@ public async Task AddOwnCompanyUsersBusinessPartnerNumbersAsync(Guid userId return await _portalRepositories.SaveAsync(); } - public Task AddOwnCompanyUsersBusinessPartnerNumberAsync(Guid userId, string businessPartnerNumber, Guid companyId) => - AddOwnCompanyUsersBusinessPartnerNumbersAsync(userId, Enumerable.Repeat(businessPartnerNumber, 1), companyId); + public Task AddOwnCompanyUsersBusinessPartnerNumberAsync(Guid userId, string businessPartnerNumber) => + AddOwnCompanyUsersBusinessPartnerNumbersAsync(userId, Enumerable.Repeat(businessPartnerNumber, 1)); - public async Task GetOwnUserDetails(Guid userId) + public async Task GetOwnUserDetails() { + var userId = _identityService.IdentityData.UserId; var userRoleIds = await _portalRepositories.GetInstance() .GetUserRoleIdsUntrackedAsync(_settings.UserAdminRoles).ToListAsync().ConfigureAwait(false); var details = await _portalRepositories.GetInstance().GetUserDetailsUntrackedAsync(userId, userRoleIds).ConfigureAwait(false); @@ -319,8 +326,9 @@ public async Task GetOwnUserDetails(Guid userId) return details; } - public async Task UpdateOwnUserDetails(Guid companyUserId, OwnCompanyUserEditableDetails ownCompanyUserEditableDetails, Guid userId) + public async Task UpdateOwnUserDetails(Guid companyUserId, OwnCompanyUserEditableDetails ownCompanyUserEditableDetails) { + var userId = _identityService.IdentityData.UserId; if (companyUserId != userId) { throw new ForbiddenException($"invalid userId {companyUserId} for user {userId}"); @@ -377,8 +385,9 @@ await _provisioningManager.UpdateSharedRealmUserAsync( }; } - public async Task DeleteOwnUserAsync(Guid companyUserId, Guid userId) + public async Task DeleteOwnUserAsync(Guid companyUserId) { + var userId = _identityService.IdentityData.UserId; if (companyUserId != userId) { throw new ForbiddenException($"companyUser {companyUserId} is not the id of user {userId}"); @@ -393,8 +402,9 @@ public async Task DeleteOwnUserAsync(Guid companyUserId, Guid userId) return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable userIds, Guid companyId) + public async IAsyncEnumerable DeleteOwnCompanyUsersAsync(IEnumerable userIds) { + var companyId = _identityService.IdentityData.CompanyId; var iamIdpAlias = await _portalRepositories.GetInstance().GetSharedIdentityProviderIamAliasDataUntrackedAsync(companyId); await foreach (var accountData in _portalRepositories.GetInstance().GetCompanyUserAccountDataUntrackedAsync(userIds, companyId).ConfigureAwait(false)) @@ -494,8 +504,9 @@ private async Task CanResetPassword(Guid userId) return false; } - public async Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId, (Guid UserId, Guid CompanyId) identity) + 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)) { @@ -509,20 +520,21 @@ public async Task ExecuteOwnCompanyUserPasswordReset(Guid companyUserId, ( throw new NotFoundException($"Cannot identify companyId or shared idp : userId {companyUserId} is not associated with admin users company {identity.CompanyId}"); } - public Task> GetOwnCompanyAppUsersAsync(Guid appId, Guid userId, int page, int size, CompanyUserFilter filter) => + public Task> GetOwnCompanyAppUsersAsync(Guid appId, int page, int size, CompanyUserFilter filter) => Pagination.CreateResponseAsync( page, size, 15, _portalRepositories.GetInstance().GetOwnCompanyAppUsersPaginationSourceAsync( appId, - userId, + _identityService.IdentityData.UserId, new[] { OfferSubscriptionStatusId.ACTIVE }, new[] { UserStatusId.ACTIVE, UserStatusId.INACTIVE }, filter)); - public async Task DeleteOwnUserBusinessPartnerNumbersAsync(Guid userId, string businessPartnerNumber, (Guid UserId, Guid CompanyId) identity) + 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); diff --git a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs index ea4d9e4157..0e24a9b480 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserRolesBusinessLogic.cs @@ -28,6 +28,7 @@ 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.Provisioning.Library; using System.Text.Json; @@ -38,26 +39,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 UserSettings _settings; - public UserRolesBusinessLogic(IPortalRepositories portalRepositories, IProvisioningManager provisioningManager, IOptions options) + public UserRolesBusinessLogic(IPortalRepositories portalRepositories, IProvisioningManager provisioningManager, IIdentityService identityService, IOptions options) { _portalRepositories = portalRepositories; _provisioningManager = provisioningManager; + _identityService = identityService; _settings = options.Value; } - public IAsyncEnumerable GetCoreOfferRoles(Guid companyId, string? languageShortName) => - _portalRepositories.GetInstance().GetCoreOfferRolesAsync(companyId, languageShortName ?? Constants.DefaultLanguage, _settings.Portal.KeycloakClientID) + public IAsyncEnumerable GetCoreOfferRoles(string? languageShortName) => + _portalRepositories.GetInstance().GetCoreOfferRolesAsync(_identityService.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, Guid companyId, string? languageShortName) => + public IAsyncEnumerable GetAppRolesAsync(Guid appId, string? languageShortName) => _portalRepositories.GetInstance() - .GetAppRolesAsync(appId, companyId, languageShortName ?? Constants.DefaultLanguage); + .GetAppRolesAsync(appId, _identityService.IdentityData.CompanyId, languageShortName ?? Constants.DefaultLanguage); - public Task> ModifyCoreOfferUserRolesAsync(Guid offerId, Guid companyUserId, IEnumerable roles, Guid companyId) + public Task> ModifyCoreOfferUserRolesAsync(Guid offerId, Guid companyUserId, IEnumerable roles) { + var companyId = _identityService.IdentityData.CompanyId; return ModifyUserRolesInternal( async () => { @@ -92,13 +96,13 @@ public Task> ModifyCoreOfferUserRolesAsync(Guid offe }); } - public Task> ModifyAppUserRolesAsync(Guid appId, Guid companyUserId, IEnumerable roles, Guid companyId) => + public Task> ModifyAppUserRolesAsync(Guid appId, Guid companyUserId, IEnumerable roles) => ModifyUserRolesInternal( () => _portalRepositories.GetInstance() - .GetAppAssignedIamClientUserDataUntrackedAsync(appId, companyUserId, companyId), + .GetAppAssignedIamClientUserDataUntrackedAsync(appId, companyUserId, _identityService.IdentityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), - appId, companyUserId, roles, companyId, + appId, companyUserId, roles, _identityService.IdentityData.CompanyId, data => { var userName = $"{data.firstname} {data.lastname}"; @@ -113,13 +117,13 @@ public Task> ModifyAppUserRolesAsync(Guid appId, Gui }); [Obsolete("to be replaced by endpoint UserRolesBusinessLogic.ModifyAppUserRolesAsync. Remove as soon frontend is adjusted")] - public Task> ModifyUserRoleAsync(Guid appId, UserRoleInfo userRoleInfo, Guid companyId) => + public Task> ModifyUserRoleAsync(Guid appId, UserRoleInfo userRoleInfo) => ModifyUserRolesInternal( () => _portalRepositories.GetInstance() - .GetAppAssignedIamClientUserDataUntrackedAsync(appId, userRoleInfo.CompanyUserId, companyId), + .GetAppAssignedIamClientUserDataUntrackedAsync(appId, userRoleInfo.CompanyUserId, _identityService.IdentityData.CompanyId), (Guid companyUserId, IEnumerable roles, Guid offerId) => _portalRepositories.GetInstance() .GetAssignedAndMatchingAppRoles(companyUserId, roles, offerId), - appId, userRoleInfo.CompanyUserId, userRoleInfo.Roles, companyId, null); + appId, userRoleInfo.CompanyUserId, userRoleInfo.Roles, _identityService.IdentityData.CompanyId, null); private async Task> ModifyUserRolesInternal( Func> getIamUserData, diff --git a/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs b/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs index a688e104c7..ef1ab4dfde 100644 --- a/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs +++ b/src/administration/Administration.Service/BusinessLogic/UserUploadBusinessLogic.cs @@ -22,9 +22,11 @@ using Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling; using Org.Eclipse.TractusX.Portal.Backend.Framework.IO; +using Org.Eclipse.TractusX.Portal.Backend.Framework.Web; using Org.Eclipse.TractusX.Portal.Backend.Mailing.SendMail; 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.Provisioning.Library.Models; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Service; using System.Runtime.CompilerServices; @@ -36,33 +38,38 @@ public class UserUploadBusinessLogic : IUserUploadBusinessLogic private readonly IUserProvisioningService _userProvisioningService; private readonly IMailingService _mailingService; private readonly UserSettings _settings; + private readonly IIdentityService _identityService; /// /// Constructor. /// /// User Provisioning Service /// Mailing Service + /// Access to the identity Service /// Settings public UserUploadBusinessLogic( IUserProvisioningService userProvisioningService, IMailingService mailingService, + IIdentityService identityService, IOptions settings) { _userProvisioningService = userProvisioningService; _mailingService = mailingService; + _identityService = identityService; _settings = settings.Value; } - public ValueTask UploadOwnCompanyIdpUsersAsync(Guid identityProviderId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) + public ValueTask UploadOwnCompanyIdpUsersAsync(Guid identityProviderId, IFormFile document, CancellationToken cancellationToken) { CsvParser.ValidateContentTypeTextCSV(document.ContentType); - return UploadOwnCompanyIdpUsersInternalAsync(identityProviderId, document, identity, cancellationToken); + return UploadOwnCompanyIdpUsersInternalAsync(identityProviderId, document, cancellationToken); } - private async ValueTask UploadOwnCompanyIdpUsersInternalAsync(Guid identityProviderId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) + private async ValueTask UploadOwnCompanyIdpUsersInternalAsync(Guid identityProviderId, IFormFile document, CancellationToken cancellationToken) { using var stream = document.OpenReadStream(); + var identity = _identityService.IdentityData; var (companyNameIdpAliasData, nameCreatedBy) = await _userProvisioningService.GetCompanyNameIdpAliasData(identityProviderId, identity.UserId).ConfigureAwait(false); var validRoleData = new List(); @@ -182,17 +189,17 @@ private static (string FirstName, string LastName, string Email, string Provider return (firstName, lastName, email, providerUserName, providerUserId, roles); } - public ValueTask UploadOwnCompanySharedIdpUsersAsync(IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) + public ValueTask UploadOwnCompanySharedIdpUsersAsync(IFormFile document, CancellationToken cancellationToken) { CsvParser.ValidateContentTypeTextCSV(document.ContentType); - return UploadOwnCompanySharedIdpUsersInternalAsync(document, identity, cancellationToken); + return UploadOwnCompanySharedIdpUsersInternalAsync(document, cancellationToken); } - private async ValueTask UploadOwnCompanySharedIdpUsersInternalAsync(IFormFile document, - (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) + private async ValueTask UploadOwnCompanySharedIdpUsersInternalAsync(IFormFile document, CancellationToken cancellationToken) { using var stream = document.OpenReadStream(); + var identity = _identityService.IdentityData; var (companyNameIdpAliasData, _) = await _userProvisioningService.GetCompanyNameSharedIdpAliasData(identity.UserId).ConfigureAwait(false); var validRoleData = new List(); diff --git a/src/administration/Administration.Service/Controllers/DocumentsController.cs b/src/administration/Administration.Service/Controllers/DocumentsController.cs index 9e3c564d90..4cc5c4559b 100644 --- a/src/administration/Administration.Service/Controllers/DocumentsController.cs +++ b/src/administration/Administration.Service/Controllers/DocumentsController.cs @@ -24,7 +24,6 @@ using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling.Library; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.PublicInfos; -using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; @@ -70,7 +69,7 @@ public DocumentsController(IDocumentsBusinessLogic documentsBusinessLogic) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status503ServiceUnavailable)] public async Task GetDocumentContentFileAsync([FromRoute] Guid documentId) { - var (fileName, content, mediaType) = await this.WithCompanyId(companyId => _businessLogic.GetDocumentAsync(documentId, companyId).ConfigureAwait(false)); + var (fileName, content, mediaType) = await _businessLogic.GetDocumentAsync(documentId).ConfigureAwait(false); return File(content, mediaType, fileName); } @@ -115,7 +114,7 @@ public async Task GetSelfDescriptionDocumentsAsync([FromRoute] Gui [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task DeleteDocumentAsync([FromRoute] Guid documentId) => - this.WithUserId(userId => _businessLogic.DeleteDocumentAsync(documentId, userId)); + _businessLogic.DeleteDocumentAsync(documentId); /// /// Gets the json the seed data for a specific document diff --git a/src/administration/Administration.Service/Controllers/IdentityProviderController.cs b/src/administration/Administration.Service/Controllers/IdentityProviderController.cs index de2208c728..f4e254c41a 100644 --- a/src/administration/Administration.Service/Controllers/IdentityProviderController.cs +++ b/src/administration/Administration.Service/Controllers/IdentityProviderController.cs @@ -24,7 +24,6 @@ using Org.Eclipse.TractusX.Portal.Backend.Administration.Service.Models; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling.Library; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Enums; @@ -244,7 +243,7 @@ public async Task DeleteOwnCompanyIdentityProvider([FromRoute] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public IAsyncEnumerable GetOwnCompanyUsersIdentityProviderDataAsync([FromQuery] IEnumerable identityProviderIds, [FromQuery] bool unlinkedUsersOnly = false) => - this.WithCompanyId(companyId => _businessLogic.GetOwnCompanyUsersIdentityProviderDataAsync(identityProviderIds, companyId, unlinkedUsersOnly)); + _businessLogic.GetOwnCompanyUsersIdentityProviderDataAsync(identityProviderIds, unlinkedUsersOnly); /// /// Gets the company users for the identity providers as a file @@ -267,7 +266,7 @@ public IAsyncEnumerable GetOwnCompanyUsersIdentityProv [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public IActionResult GetOwnCompanyUsersIdentityProviderFileAsync([FromQuery] IEnumerable identityProviderIds, [FromQuery] bool unlinkedUsersOnly = false) { - var (stream, contentType, fileName, encoding) = this.WithCompanyId(companyId => _businessLogic.GetOwnCompanyUsersIdentityProviderLinkDataStream(identityProviderIds, companyId, unlinkedUsersOnly)); + var (stream, contentType, fileName, encoding) = _businessLogic.GetOwnCompanyUsersIdentityProviderLinkDataStream(identityProviderIds, unlinkedUsersOnly); return File(stream, string.Join("; ", contentType, encoding.WebName), fileName); } @@ -296,7 +295,7 @@ public IActionResult GetOwnCompanyUsersIdentityProviderFileAsync([FromQuery] IEn [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsync([FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) => - this.WithCompanyId(companyId => _businessLogic.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(document, companyId, cancellationToken)); + _businessLogic.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(document, cancellationToken); /// /// Adds the user to the given identity provider @@ -328,7 +327,7 @@ public ValueTask UploadOwnCompanyUsersIdentityProvi [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public async ValueTask> AddOwnCompanyUserIdentityProviderDataAsync([FromRoute] Guid companyUserId, [FromBody] UserIdentityProviderLinkData identityProviderLinkData) { - var linkData = await this.WithCompanyId(companyId => _businessLogic.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderLinkData, companyId)).ConfigureAwait(false); + var linkData = await _businessLogic.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderLinkData).ConfigureAwait(false); return (ActionResult)CreatedAtRoute( nameof(GetOwnCompanyUserIdentityProviderDataAsync), new { companyUserId = companyUserId, identityProviderId = linkData.identityProviderId }, @@ -362,7 +361,7 @@ public async ValueTask> AddOwnCompany [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public ValueTask CreateOrUpdateOwnCompanyUserIdentityProviderDataAsync([FromRoute] Guid companyUserId, [FromRoute] Guid identityProviderId, [FromBody] UserLinkData userLinkData) => - this.WithCompanyId(companyId => _businessLogic.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, userLinkData, companyId)); + _businessLogic.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, userLinkData); /// /// Gets the given user for the given identity provider @@ -390,7 +389,7 @@ public ValueTask CreateOrUpdateOwnCompanyUserIdent [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public ValueTask GetOwnCompanyUserIdentityProviderDataAsync([FromRoute] Guid companyUserId, [FromRoute] Guid identityProviderId) => - this.WithCompanyId(companyId => _businessLogic.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId)); + _businessLogic.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId); /// /// Deletes the given user on the given identity provider @@ -419,7 +418,7 @@ public ValueTask GetOwnCompanyUserIdentityProvider [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public async ValueTask DeleteOwnCompanyUserIdentityProviderDataAsync([FromRoute] Guid companyUserId, [FromRoute] Guid identityProviderId) { - await this.WithCompanyId(companyId => _businessLogic.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId, companyId)).ConfigureAwait(false); + await _businessLogic.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); return (ActionResult)NoContent(); } } diff --git a/src/administration/Administration.Service/Controllers/ServiceAccountController.cs b/src/administration/Administration.Service/Controllers/ServiceAccountController.cs index 2ec3e28caa..21944bb1fc 100644 --- a/src/administration/Administration.Service/Controllers/ServiceAccountController.cs +++ b/src/administration/Administration.Service/Controllers/ServiceAccountController.cs @@ -65,7 +65,7 @@ public ServiceAccountController(IServiceAccountBusinessLogic logic) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task ExecuteCompanyUserCreation([FromBody] ServiceAccountCreationInfo serviceAccountCreationInfo) { - var serviceAccountDetails = await this.WithCompanyId(companyId => _logic.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfo, companyId).ConfigureAwait(false)); + var serviceAccountDetails = await _logic.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfo).ConfigureAwait(false); return CreatedAtRoute("GetServiceAccountDetails", new { serviceAccountId = serviceAccountDetails.ServiceAccountId }, serviceAccountDetails); } @@ -86,7 +86,7 @@ public async Task ExecuteCompanyUserCreation([FromBody] Se [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public Task DeleteServiceAccount([FromRoute] Guid serviceAccountId) => - this.WithCompanyId(companyId => _logic.DeleteOwnCompanyServiceAccountAsync(serviceAccountId, companyId)); + _logic.DeleteOwnCompanyServiceAccountAsync(serviceAccountId); /// /// Gets the service account details for the given id @@ -105,7 +105,7 @@ public Task DeleteServiceAccount([FromRoute] Guid serviceAccountId) => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public Task GetServiceAccountDetails([FromRoute] Guid serviceAccountId) => - this.WithCompanyId(companyId => _logic.GetOwnCompanyServiceAccountDetailsAsync(serviceAccountId, companyId)); + _logic.GetOwnCompanyServiceAccountDetailsAsync(serviceAccountId); /// /// Updates the service account details with the given id. @@ -132,7 +132,7 @@ public Task GetServiceAccountDetails([FromRout [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public Task PutServiceAccountDetails([FromRoute] Guid serviceAccountId, [FromBody] ServiceAccountEditableDetails serviceAccountDetails) => - this.WithCompanyId(companyId => _logic.UpdateOwnCompanyServiceAccountDetailsAsync(serviceAccountId, serviceAccountDetails, companyId)); + _logic.UpdateOwnCompanyServiceAccountDetailsAsync(serviceAccountId, serviceAccountDetails); /// /// Resets the service account credentials for the given service account Id. @@ -154,7 +154,7 @@ public Task PutServiceAccountDetails([FromRoute] Guid ser [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public Task ResetServiceAccountCredentials([FromRoute] Guid serviceAccountId) => - this.WithCompanyId(companyId => _logic.ResetOwnCompanyServiceAccountSecretAsync(serviceAccountId, companyId)); + _logic.ResetOwnCompanyServiceAccountSecretAsync(serviceAccountId); /// /// Gets the service account data as pagination @@ -172,7 +172,7 @@ public Task ResetServiceAccountCredentials([FromRoute] Gu [Route("owncompany/serviceaccounts")] [ProducesResponseType(typeof(Pagination.Response), StatusCodes.Status200OK)] public Task> GetServiceAccountsData([FromQuery] int page, [FromQuery] int size, [FromQuery] bool? isOwner, [FromQuery] string? clientId) => - this.WithCompanyId(companyId => _logic.GetOwnCompanyServiceAccountsDataAsync(page, size, companyId, clientId, isOwner)); + _logic.GetOwnCompanyServiceAccountsDataAsync(page, size, clientId, isOwner); /// /// Get all service account roles @@ -187,5 +187,5 @@ public Task ResetServiceAccountCredentials([FromRoute] Gu [Route("user/roles")] [ProducesResponseType(typeof(List), StatusCodes.Status200OK)] public IAsyncEnumerable GetServiceAccountRolesAsync(string? languageShortName = null) => - this.WithCompanyId(companyId => _logic.GetServiceAccountRolesAsync(companyId, languageShortName)); + _logic.GetServiceAccountRolesAsync(languageShortName); } diff --git a/src/administration/Administration.Service/Controllers/SubscriptionConfigurationController.cs b/src/administration/Administration.Service/Controllers/SubscriptionConfigurationController.cs index dba22e0a8c..5c1345f50d 100644 --- a/src/administration/Administration.Service/Controllers/SubscriptionConfigurationController.cs +++ b/src/administration/Administration.Service/Controllers/SubscriptionConfigurationController.cs @@ -69,7 +69,7 @@ public SubscriptionConfigurationController(ISubscriptionConfigurationBusinessLog [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] [PublicUrl(CompanyRoleId.SERVICE_PROVIDER, CompanyRoleId.APP_PROVIDER)] public Task GetServiceProviderCompanyDetail() => - this.WithCompanyId(companyId => _businessLogic.GetProviderCompanyDetailsAsync(companyId)); + _businessLogic.GetProviderCompanyDetailsAsync(); /// /// Sets detail data to the calling users service provider @@ -91,7 +91,7 @@ public Task GetServiceProviderCompanyDetail() => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task SetProviderCompanyDetail([FromBody] ProviderDetailData data) { - await this.WithCompanyId(companyId => _businessLogic.SetProviderCompanyDetailsAsync(data, companyId)).ConfigureAwait(false); + await _businessLogic.SetProviderCompanyDetailsAsync(data).ConfigureAwait(false); return NoContent(); } diff --git a/src/administration/Administration.Service/Controllers/UserController.cs b/src/administration/Administration.Service/Controllers/UserController.cs index ab44558c89..d2fa9a5b43 100644 --- a/src/administration/Administration.Service/Controllers/UserController.cs +++ b/src/administration/Administration.Service/Controllers/UserController.cs @@ -69,7 +69,7 @@ public UserController(IUserBusinessLogic logic, IUserUploadBusinessLogic uploadL [ProducesResponseType(typeof(IAsyncEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] public IAsyncEnumerable CreateOwnCompanyUsers([FromBody] IEnumerable usersToCreate) => - this.WithUserIdAndCompanyId(identity => _logic.CreateOwnCompanyUsersAsync(usersToCreate, identity)); + _logic.CreateOwnCompanyUsersAsync(usersToCreate); /// /// Create new users for the companies shared identityprovider by upload of csv-file @@ -96,7 +96,7 @@ public IAsyncEnumerable CreateOwnCompanyUsers([FromBody] IEnumerable UploadOwnCompanySharedIdpUsersFileAsync([FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) => - this.WithUserIdAndCompanyId(identity => _uploadLogic.UploadOwnCompanySharedIdpUsersAsync(document, identity, cancellationToken)); + _uploadLogic.UploadOwnCompanySharedIdpUsersAsync(document, cancellationToken); /// /// Create a new user for a specific identityprovider @@ -124,7 +124,7 @@ public ValueTask UploadOwnCompanySharedIdpUsersFileAsync([Fro [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task CreateOwnIdpOwnCompanyUser([FromBody] UserCreationInfoIdp userToCreate, [FromRoute] Guid identityProviderId) { - var result = await this.WithUserIdAndCompanyId(identity => _logic.CreateOwnCompanyIdpUserAsync(identityProviderId, userToCreate, identity)).ConfigureAwait(false); + var result = await _logic.CreateOwnCompanyIdpUserAsync(identityProviderId, userToCreate).ConfigureAwait(false); return CreatedAtRoute(nameof(GetOwnCompanyUserDetails), new { companyUserId = result }, result); } @@ -154,7 +154,7 @@ public async Task CreateOwnIdpOwnCompanyUser([FromBody] Us [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsync([FromRoute] Guid identityProviderId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) => - this.WithUserIdAndCompanyId(identity => _uploadLogic.UploadOwnCompanyIdpUsersAsync(identityProviderId, document, identity, cancellationToken)); + _uploadLogic.UploadOwnCompanyIdpUsersAsync(identityProviderId, document, cancellationToken); /// /// Get Company User Data @@ -183,11 +183,10 @@ public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsy [FromQuery] string? firstName = null, [FromQuery] string? lastName = null, [FromQuery] string? email = null) => - this.WithCompanyId(companyId => _logic.GetOwnCompanyUserDatasAsync( - companyId, + _logic.GetOwnCompanyUserDatasAsync( page, size, - new(companyUserId, userEntityId, firstName, lastName, email))); + new(companyUserId, userEntityId, firstName, lastName, email)); /// /// Gets the user details for the given user Id @@ -204,7 +203,7 @@ public ValueTask UploadOwnCompanyUsersIdentityProviderFileAsy [ProducesResponseType(typeof(CompanyUserDetails), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task GetOwnCompanyUserDetails([FromRoute] Guid companyUserId) => - this.WithCompanyId(companyId => _logic.GetOwnCompanyUserDetailsAsync(companyUserId, companyId)); + _logic.GetOwnCompanyUserDetailsAsync(companyUserId); /// /// Updates the portal-roles for the user @@ -225,7 +224,7 @@ public Task GetOwnCompanyUserDetails([FromRoute] Guid compan [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task> ModifyCoreUserRolesAsync([FromRoute] Guid companyUserId, [FromRoute] Guid offerId, [FromBody] IEnumerable roles) => - this.WithCompanyId(companyId => _rolesLogic.ModifyCoreOfferUserRolesAsync(offerId, companyUserId, roles, companyId)); + _rolesLogic.ModifyCoreOfferUserRolesAsync(offerId, companyUserId, roles); /// /// Updates the app-roles for the user @@ -246,7 +245,7 @@ public Task> ModifyCoreUserRolesAsync([FromRoute] Gu [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task> ModifyAppUserRolesAsync([FromRoute] Guid companyUserId, [FromRoute] Guid appId, [FromBody] IEnumerable roles) => - this.WithCompanyId(companyId => _rolesLogic.ModifyAppUserRolesAsync(appId, companyUserId, roles, companyId)); + _rolesLogic.ModifyAppUserRolesAsync(appId, companyUserId, roles); /// /// Adds the given business partner numbers to the user for the given id. @@ -266,7 +265,7 @@ public Task> ModifyAppUserRolesAsync([FromRoute] Gui [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task AddOwnCompanyUserBusinessPartnerNumbers(Guid companyUserId, IEnumerable businessPartnerNumbers) => - this.WithCompanyId(companyId => _logic.AddOwnCompanyUsersBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumbers, companyId)); + _logic.AddOwnCompanyUsersBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumbers); /// /// Adds the given business partner number to the user for the given id. @@ -290,7 +289,7 @@ public Task AddOwnCompanyUserBusinessPartnerNumbers(Guid companyUserId, IEn [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public Task AddOwnCompanyUserBusinessPartnerNumber(Guid companyUserId, string businessPartnerNumber) => - this.WithCompanyId(companyId => _logic.AddOwnCompanyUsersBusinessPartnerNumberAsync(companyUserId, businessPartnerNumber, companyId)); + _logic.AddOwnCompanyUsersBusinessPartnerNumberAsync(companyUserId, businessPartnerNumber); /// /// Deletes the users with the given ids. @@ -308,7 +307,7 @@ public Task AddOwnCompanyUserBusinessPartnerNumber(Guid companyUserId, stri [ProducesResponseType(typeof(IAsyncEnumerable), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public IAsyncEnumerable DeleteOwnCompanyUsers([FromBody] IEnumerable usersToDelete) => - this.WithCompanyId(companyId => _logic.DeleteOwnCompanyUsersAsync(usersToDelete, companyId)); + _logic.DeleteOwnCompanyUsersAsync(usersToDelete); /// /// Resets the password for the given user @@ -330,7 +329,7 @@ public IAsyncEnumerable DeleteOwnCompanyUsers([FromBody] IEnumerable [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public Task ResetOwnCompanyUserPassword([FromRoute] Guid companyUserId) => - this.WithUserIdAndCompanyId(identity => _logic.ExecuteOwnCompanyUserPasswordReset(companyUserId, identity)); + _logic.ExecuteOwnCompanyUserPasswordReset(companyUserId); /// /// Gets the core offer roles @@ -348,7 +347,7 @@ public Task ResetOwnCompanyUserPassword([FromRoute] Guid companyUserId) => [Route("owncompany/roles/coreoffers")] [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] public IAsyncEnumerable GetCoreOfferRoles([FromQuery] string? languageShortName = null) => - this.WithCompanyId(companyId => _rolesLogic.GetCoreOfferRoles(companyId, languageShortName)); + _rolesLogic.GetCoreOfferRoles(languageShortName); /// /// Gets the client roles for the given app. @@ -366,7 +365,7 @@ public IAsyncEnumerable GetCoreOfferRoles([FromQuery] string? la [Route("owncompany/roles/apps/{appId}")] [ProducesResponseType(typeof(OfferRoleInfos), StatusCodes.Status200OK)] public IAsyncEnumerable GetAppRolesAsync([FromRoute] Guid appId, [FromQuery] string? languageShortName = null) => - this.WithCompanyId(companyId => _rolesLogic.GetAppRolesAsync(appId, companyId, languageShortName)); + _rolesLogic.GetAppRolesAsync(appId, languageShortName); /// /// Gets the client roles for the given app. @@ -402,7 +401,7 @@ public IAsyncEnumerable GetClientRolesAsync([FromRoute] Guid appId, [ProducesResponseType(typeof(CompanyOwnUserDetails), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task GetOwnUserDetails() => - this.WithUserId(userId => _logic.GetOwnUserDetails(userId)); + _logic.GetOwnUserDetails(); /// /// Updates the user details for the given companyUserId. @@ -421,7 +420,7 @@ public Task GetOwnUserDetails() => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task UpdateOwnUserDetails([FromRoute] Guid companyUserId, [FromBody] OwnCompanyUserEditableDetails ownCompanyUserEditableDetails) => - this.WithUserId(userId => _logic.UpdateOwnUserDetails(companyUserId, ownCompanyUserEditableDetails, userId)); + _logic.UpdateOwnUserDetails(companyUserId, ownCompanyUserEditableDetails); /// /// Deletes the own user @@ -440,7 +439,7 @@ public Task UpdateOwnUserDetails([FromRoute] Guid companyUse [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public Task DeleteOwnUser([FromRoute] Guid companyUserId) => - this.WithUserId(userId => _logic.DeleteOwnUserAsync(companyUserId, userId)); + _logic.DeleteOwnUserAsync(companyUserId); /// /// Get for given app id all the company assigned users @@ -470,9 +469,8 @@ public Task DeleteOwnUser([FromRoute] Guid companyUserId) => [FromQuery] string? email = null, [FromQuery] string? roleName = null, [FromQuery] bool? hasRole = null) => - this.WithUserId(userId => _logic.GetOwnCompanyAppUsersAsync( + _logic.GetOwnCompanyAppUsersAsync( appId, - userId, page, size, new CompanyUserFilter( @@ -480,7 +478,7 @@ public Task DeleteOwnUser([FromRoute] Guid companyUserId) => lastName, email, roleName, - hasRole))); + hasRole)); /// /// Updates the roles for the user @@ -501,7 +499,7 @@ public Task DeleteOwnUser([FromRoute] Guid companyUserId) => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task> ModifyUserRolesAsync([FromRoute] Guid appId, [FromBody] UserRoleInfo userRoleInfo) => - this.WithCompanyId(companyId => _rolesLogic.ModifyUserRoleAsync(appId, userRoleInfo, companyId)); + _rolesLogic.ModifyUserRoleAsync(appId, userRoleInfo); /// /// Delete BPN assigned to user from DB and Keycloack. @@ -523,5 +521,5 @@ public Task> ModifyUserRolesAsync([FromRoute] Guid a [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public Task DeleteOwnCompanyUserBusinessPartnerNumber([FromRoute] Guid companyUserId, [FromRoute] string businessPartnerNumber) => - this.WithUserIdAndCompanyId(identity => _logic.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, identity)); + _logic.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber); } diff --git a/src/framework/Framework.Web/IdentityService.cs b/src/framework/Framework.Web/IdentityService.cs index 821a15f567..8e9c6926ec 100644 --- a/src/framework/Framework.Web/IdentityService.cs +++ b/src/framework/Framework.Web/IdentityService.cs @@ -28,6 +28,7 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Framework.Web; public class IdentityService : IIdentityService { private readonly IHttpContextAccessor _httpContextAccessor; + private IdentityData? _identityData; public IdentityService(IHttpContextAccessor httpContextAccessor) { @@ -36,6 +37,6 @@ public IdentityService(IHttpContextAccessor httpContextAccessor) /// public IdentityData IdentityData => - _httpContextAccessor.HttpContext?.User.GetIdentityData() ?? - throw new ConflictException("The identity should be set here"); + _identityData ??= _httpContextAccessor.HttpContext?.User.GetIdentityData() + ?? throw new ConflictException("The identity should be set here"); } diff --git a/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs b/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs index 0b6baabd59..bb08ffe2d7 100644 --- a/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs +++ b/src/keycloak/Keycloak.Authentication/ControllerExtensions.cs @@ -32,24 +32,9 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; /// public static class ControllerExtensions { - public static T WithIdentityData(this ControllerBase controller, Func consumingFunction) => - consumingFunction(controller.User.GetIdentityData()); - - public static T WithUserId(this ControllerBase controller, Func consumingFunction) => - consumingFunction(controller.User.Claims.GetGuidFromClaim(PortalClaimTypes.IdentityId)); - - public static T WithCompanyId(this ControllerBase controller, Func consumingFunction) => - consumingFunction(controller.User.Claims.GetGuidFromClaim(PortalClaimTypes.CompanyId)); - - public static T WithUserIdAndCompanyId(this ControllerBase controller, Func<(Guid UserId, Guid CompanyId), T> consumingFunction) => - consumingFunction((controller.User.Claims.GetGuidFromClaim(PortalClaimTypes.IdentityId), controller.User.Claims.GetGuidFromClaim(PortalClaimTypes.CompanyId))); - public static T WithBearerToken(this ControllerBase controller, Func tokenConsumingFunction) => tokenConsumingFunction(controller.GetBearerToken()); - public static T WithIdentityIdAndBearerToken(this ControllerBase controller, Func<(Guid UserId, string BearerToken), T> tokenConsumingFunction) => - tokenConsumingFunction((controller.User.Claims.GetGuidFromClaim(PortalClaimTypes.IdentityId), controller.GetBearerToken())); - public static IdentityData GetIdentityData(this ClaimsPrincipal user) { var sub = user.Claims.GetStringFromClaim(PortalClaimTypes.Sub); @@ -82,7 +67,7 @@ private static string GetStringFromClaim(this IEnumerable claims, string 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)); + throw new ControllerArgumentException($"Claim {claimType} must not be null or empty", nameof(claims)); } return claimValue; @@ -93,12 +78,12 @@ private static Guid GetGuidFromClaim(this IEnumerable claims, string clai var claimValue = claims.SingleOrDefault(x => x.Type == claimType)?.Value; if (string.IsNullOrWhiteSpace(claimValue)) { - throw new ControllerArgumentException($"Claim '{claimType} must not be null or empty."); + 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"); + throw new ControllerArgumentException($"Claim {claimType} must contain a Guid", nameof(claims)); } return result; @@ -109,12 +94,12 @@ private static T GetEnumFromClaim(this IEnumerable claims, string clai var claimValue = claims.SingleOrDefault(x => x.Type == claimType)?.Value; if (string.IsNullOrWhiteSpace(claimValue)) { - throw new ControllerArgumentException($"Claim '{claimType} must not be null or empty."); + throw new ControllerArgumentException($"Claim {claimType} must not be null or empty", nameof(claims)); } if (!Enum.TryParse(claimValue, true, out T result)) { - throw new ControllerArgumentException($"Claim {claimType} must contain a {typeof(T)}"); + throw new ControllerArgumentException($"Claim {claimType} must contain a {typeof(T)}", nameof(claims)); } return result; diff --git a/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs index 0edf3588d4..62d2639a9d 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/AppChangeBusinessLogic.cs @@ -57,16 +57,16 @@ public class AppChangeBusinessLogic : IAppChangeBusinessLogic /// access to the repositories /// the notification service /// The provisioning manager - /// Settings for the app change bl - /// Identity + /// Access to the identityService /// Offer Servicel + /// Settings for the app change bl public AppChangeBusinessLogic( IPortalRepositories portalRepositories, INotificationService notificationService, IProvisioningManager provisioningManager, IOfferService offerService, - IOptions settings, - IIdentityService identityService) + IIdentityService identityService, + IOptions settings) { _portalRepositories = portalRepositories; _notificationService = notificationService; @@ -77,14 +77,15 @@ public AppChangeBusinessLogic( } /// - public Task> AddActiveAppUserRoleAsync(Guid appId, IEnumerable appUserRolesDescription, (Guid UserId, Guid CompanyId) identity) + public Task> AddActiveAppUserRoleAsync(Guid appId, IEnumerable appUserRolesDescription) { AppExtensions.ValidateAppUserRole(appId, appUserRolesDescription); - return InsertActiveAppUserRoleAsync(appId, appUserRolesDescription, identity); + return InsertActiveAppUserRoleAsync(appId, appUserRolesDescription); } - private async Task> InsertActiveAppUserRoleAsync(Guid appId, IEnumerable userRoles, (Guid UserId, Guid CompanyId) identity) + 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) { @@ -123,19 +124,19 @@ private async Task> InsertActiveAppUserRoleAsync(Guid a } /// - public async Task> GetAppUpdateDescriptionByIdAsync(Guid appId, Guid companyId) + public async Task> GetAppUpdateDescriptionByIdAsync(Guid appId) { var offerRepository = _portalRepositories.GetInstance(); - return await ValidateAndGetAppDescription(appId, companyId, offerRepository); + return await ValidateAndGetAppDescription(appId, offerRepository); } /// - public async Task CreateOrUpdateAppDescriptionByIdAsync(Guid appId, Guid companyId, IEnumerable offerDescriptionDatas) + public async Task CreateOrUpdateAppDescriptionByIdAsync(Guid appId, IEnumerable offerDescriptionDatas) { var offerRepository = _portalRepositories.GetInstance(); offerRepository.CreateUpdateDeleteOfferDescriptions(appId, - await ValidateAndGetAppDescription(appId, companyId, offerRepository), + await ValidateAndGetAppDescription(appId, offerRepository), offerDescriptionDatas.Select(od => new ValueTuple(od.LanguageCode, od.LongDescription, od.ShortDescription))); offerRepository.AttachAndModifyOffer(appId, offer => @@ -143,8 +144,9 @@ await ValidateAndGetAppDescription(appId, companyId, offerRepository), await _portalRepositories.SaveAsync().ConfigureAwait(false); } - private static async Task> ValidateAndGetAppDescription(Guid appId, Guid companyId, IOfferRepository offerRepository) + private async Task> ValidateAndGetAppDescription(Guid appId, IOfferRepository offerRepository) { + var companyId = _identityService.IdentityData.CompanyId; var result = await offerRepository.GetActiveOfferDescriptionDataByIdAsync(appId, OfferTypeId.APP, companyId).ConfigureAwait(false); if (result == default) { @@ -170,13 +172,14 @@ private static async Task> ValidateAndGetAppDe } /// - public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, (Guid UserId, Guid CompanyId) identity, IFormFile document, CancellationToken cancellationToken) + public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, IFormFile document, CancellationToken cancellationToken) { var appLeadImageContentTypes = new[] { MediaTypeId.JPEG, MediaTypeId.PNG }; var documentContentType = document.ContentType.ParseMediaTypeId(); documentContentType.CheckDocumentContentType(appLeadImageContentTypes); var offerRepository = _portalRepositories.GetInstance(); + var identity = _identityService.IdentityData; var result = await offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, identity.CompanyId, OfferTypeId.APP).ConfigureAwait(false); if (result == default) @@ -214,14 +217,15 @@ public Task DeactivateOfferByAppIdAsync(Guid appId) => _offerService.DeactivateOfferIdAsync(appId, OfferTypeId.APP); /// - public Task UpdateTenantUrlAsync(Guid offerId, Guid subscriptionId, UpdateTenantData data, Guid companyId) + public Task UpdateTenantUrlAsync(Guid offerId, Guid subscriptionId, UpdateTenantData data) { data.Url.EnsureValidHttpUrl(() => nameof(data.Url)); - return UpdateTenantUrlAsyncInternal(offerId, subscriptionId, data.Url, companyId); + return UpdateTenantUrlAsyncInternal(offerId, subscriptionId, data.Url); } - private async Task UpdateTenantUrlAsyncInternal(Guid offerId, Guid subscriptionId, string url, Guid companyId) + private async Task UpdateTenantUrlAsyncInternal(Guid offerId, Guid subscriptionId, string url) { + var companyId = _identityService.IdentityData.CompanyId; var offerSubscriptionsRepository = _portalRepositories.GetInstance(); var result = await offerSubscriptionsRepository.GetUpdateUrlDataAsync(offerId, subscriptionId, companyId).ConfigureAwait(false); if (result == null) diff --git a/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs index e1bf94a55d..a52c75a256 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/AppReleaseBusinessLogic.cs @@ -31,6 +31,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Apps.Service.BusinessLogic; @@ -44,6 +45,7 @@ public class AppReleaseBusinessLogic : IAppReleaseBusinessLogic private readonly IOfferService _offerService; private readonly IOfferDocumentService _offerDocumentService; private readonly IOfferSetupService _offerSetupService; + private readonly IIdentityService _identityService; /// /// Constructor. @@ -53,31 +55,34 @@ public class AppReleaseBusinessLogic : IAppReleaseBusinessLogic /// /// /// - public AppReleaseBusinessLogic(IPortalRepositories portalRepositories, IOptions settings, IOfferService offerService, IOfferDocumentService offerDocumentService, IOfferSetupService offerSetupService) + /// Access to the identityService + public AppReleaseBusinessLogic(IPortalRepositories portalRepositories, IOptions settings, IOfferService offerService, IOfferDocumentService offerDocumentService, IOfferSetupService offerSetupService, IIdentityService identityService) { _portalRepositories = portalRepositories; _settings = settings.Value; _offerService = offerService; _offerDocumentService = offerDocumentService; _offerSetupService = offerSetupService; + _identityService = identityService; } /// - public Task CreateAppDocumentAsync(Guid appId, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) => - UploadAppDoc(appId, documentTypeId, document, identity, OfferTypeId.APP, cancellationToken); + public Task CreateAppDocumentAsync(Guid appId, DocumentTypeId documentTypeId, IFormFile document, CancellationToken cancellationToken) => + UploadAppDoc(appId, documentTypeId, document, OfferTypeId.APP, cancellationToken); - private async Task UploadAppDoc(Guid appId, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, OfferTypeId offerTypeId, CancellationToken cancellationToken) => - await _offerDocumentService.UploadDocumentAsync(appId, documentTypeId, document, identity, offerTypeId, _settings.UploadAppDocumentTypeIds, cancellationToken).ConfigureAwait(false); + private async Task UploadAppDoc(Guid appId, DocumentTypeId documentTypeId, IFormFile document, OfferTypeId offerTypeId, CancellationToken cancellationToken) => + await _offerDocumentService.UploadDocumentAsync(appId, documentTypeId, document, offerTypeId, _settings.UploadAppDocumentTypeIds, cancellationToken).ConfigureAwait(false); /// - public Task> AddAppUserRoleAsync(Guid appId, IEnumerable userRoles, Guid companyId) + public Task> AddAppUserRoleAsync(Guid appId, IEnumerable userRoles) { AppExtensions.ValidateAppUserRole(appId, userRoles); - return InsertAppUserRoleAsync(appId, userRoles, companyId); + return InsertAppUserRoleAsync(appId, userRoles); } - private async Task> InsertAppUserRoleAsync(Guid appId, IEnumerable userRoles, Guid companyId) + private async Task> InsertAppUserRoleAsync(Guid appId, IEnumerable userRoles) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance().IsProviderCompanyUserAsync(appId, companyId, OfferTypeId.APP).ConfigureAwait(false); if (result == default) { @@ -144,8 +149,9 @@ public async Task GetAppDetailsForStatusAsync(Guid appId) } /// - public async Task DeleteAppRoleAsync(Guid appId, Guid roleId, Guid companyId) + public async Task DeleteAppRoleAsync(Guid appId, Guid roleId) { + var companyId = _identityService.IdentityData.CompanyId; var appUserRole = await _portalRepositories.GetInstance().GetAppUserRoleUntrackedAsync(appId, companyId, OfferStatusId.CREATED, roleId).ConfigureAwait(false); if (!appUserRole.IsProviderCompanyUser) { @@ -164,11 +170,11 @@ public async Task DeleteAppRoleAsync(Guid appId, Guid roleId, Guid companyId) } /// - public IAsyncEnumerable GetAppProviderSalesManagersAsync(Guid companyId) => - _portalRepositories.GetInstance().GetUserDataByAssignedRoles(companyId, _settings.SalesManagerRoles); + public IAsyncEnumerable GetAppProviderSalesManagersAsync() => + _portalRepositories.GetInstance().GetUserDataByAssignedRoles(_identityService.IdentityData.CompanyId, _settings.SalesManagerRoles); /// - public Task AddAppAsync(AppRequestModel appRequestModel, Guid companyId) + public Task AddAppAsync(AppRequestModel appRequestModel) { var emptyLanguageCodes = appRequestModel.SupportedLanguageCodes.Where(string.IsNullOrWhiteSpace); if (emptyLanguageCodes.Any()) @@ -182,11 +188,12 @@ public Task AddAppAsync(AppRequestModel appRequestModel, Guid companyId) throw new ControllerArgumentException("Use Case Ids must not be null or empty", nameof(appRequestModel.UseCaseIds)); } - return this.CreateAppAsync(appRequestModel, companyId); + return this.CreateAppAsync(appRequestModel); } - private async Task CreateAppAsync(AppRequestModel appRequestModel, Guid companyId) + private async Task CreateAppAsync(AppRequestModel appRequestModel) { + var companyId = _identityService.IdentityData.CompanyId; if (appRequestModel.SalesManagerId.HasValue) { await _offerService.ValidateSalesManager(appRequestModel.SalesManagerId.Value, _settings.SalesManagerRoles).ConfigureAwait(false); @@ -232,8 +239,9 @@ private async Task CreateAppAsync(AppRequestModel appRequestModel, Guid co } /// - public async Task UpdateAppReleaseAsync(Guid appId, AppRequestModel appRequestModel, Guid companyId) + public async Task UpdateAppReleaseAsync(Guid appId, AppRequestModel appRequestModel) { + var companyId = _identityService.IdentityData.CompanyId; var appData = await _portalRepositories.GetInstance() .GetAppUpdateData( appId, @@ -386,8 +394,9 @@ public Task DeleteAppDocumentsAsync(Guid documentId) => _offerService.DeleteDocumentsAsync(documentId, _settings.DeleteDocumentTypeIds, OfferTypeId.APP); /// - public async Task DeleteAppAsync(Guid appId, Guid companyId) + public async Task DeleteAppAsync(Guid appId) { + var companyId = _identityService.IdentityData.CompanyId; var (isValidApp, isOfferType, isOfferStatus, isProviderCompanyUser, appData) = await _portalRepositories.GetInstance().GetAppDeleteDataAsync(appId, OfferTypeId.APP, companyId, OfferStatusId.CREATED).ConfigureAwait(false); if (!isValidApp) { @@ -422,7 +431,7 @@ public async Task DeleteAppAsync(Guid appId, Guid companyId) } /// - public Task SetInstanceType(Guid appId, AppInstanceSetupData data, Guid companyId) + public Task SetInstanceType(Guid appId, AppInstanceSetupData data) { if (data.IsSingleInstance) { @@ -434,11 +443,12 @@ public Task SetInstanceType(Guid appId, AppInstanceSetupData data, Guid companyI nameof(data.InstanceUrl)); } - return SetInstanceTypeInternal(appId, data, companyId); + return SetInstanceTypeInternal(appId, data); } - private async Task SetInstanceTypeInternal(Guid appId, AppInstanceSetupData data, Guid companyId) + private async Task SetInstanceTypeInternal(Guid appId, AppInstanceSetupData data) { + var companyId = _identityService.IdentityData.CompanyId; var result = await _portalRepositories.GetInstance() .GetOfferWithSetupDataById(appId, companyId, OfferTypeId.APP) .ConfigureAwait(false); diff --git a/src/marketplace/Apps.Service/BusinessLogic/IAppChangeBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/IAppChangeBusinessLogic.cs index dc703d49be..0545f6f2a1 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/IAppChangeBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/IAppChangeBusinessLogic.cs @@ -33,33 +33,29 @@ public interface IAppChangeBusinessLogic /// /// /// - /// /// List of the created AppRoles - Task> AddActiveAppUserRoleAsync(Guid appId, IEnumerable appUserRolesDescription, (Guid UserId, Guid CompanyId) identity); + Task> AddActiveAppUserRoleAsync(Guid appId, IEnumerable appUserRolesDescription); /// /// Get OfferDescription by appId /// /// Id of the app - /// - Task> GetAppUpdateDescriptionByIdAsync(Guid appId, Guid companyId); + Task> GetAppUpdateDescriptionByIdAsync(Guid appId); /// /// Create or Update OfferDescription by appId /// /// Id of the app - /// /// OfferDescription Data - Task CreateOrUpdateAppDescriptionByIdAsync(Guid appId, Guid companyId, IEnumerable offerDescriptionDatas); + Task CreateOrUpdateAppDescriptionByIdAsync(Guid appId, IEnumerable offerDescriptionDatas); /// /// Upload OfferAssigned AppLeadImage Document by appId /// /// Id of the app - /// /// Document Data /// cancellationToken - Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, (Guid UserId, Guid CompanyId) identity, IFormFile document, CancellationToken cancellationToken); + Task UploadOfferAssignedAppLeadImageDocumentByIdAsync(Guid appId, IFormFile document, CancellationToken cancellationToken); /// /// Deactivate Offer Status by appId @@ -73,8 +69,7 @@ public interface IAppChangeBusinessLogic /// Id of the offer /// If of the subscription /// the data to update the url - /// - Task UpdateTenantUrlAsync(Guid offerId, Guid subscriptionId, UpdateTenantData data, Guid companyId); + Task UpdateTenantUrlAsync(Guid offerId, Guid subscriptionId, UpdateTenantData data); /// /// Gets the Active App Documents diff --git a/src/marketplace/Apps.Service/BusinessLogic/IAppReleaseBusinessLogic.cs b/src/marketplace/Apps.Service/BusinessLogic/IAppReleaseBusinessLogic.cs index 2331f02c96..acddacae0b 100644 --- a/src/marketplace/Apps.Service/BusinessLogic/IAppReleaseBusinessLogic.cs +++ b/src/marketplace/Apps.Service/BusinessLogic/IAppReleaseBusinessLogic.cs @@ -37,19 +37,17 @@ public interface IAppReleaseBusinessLogic /// /// /// - /// /// /// - Task CreateAppDocumentAsync(Guid appId, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken); + Task CreateAppDocumentAsync(Guid appId, DocumentTypeId documentTypeId, IFormFile document, CancellationToken cancellationToken); /// /// Add User Role for App /// /// /// - /// /// - Task> AddAppUserRoleAsync(Guid appId, IEnumerable userRoles, Guid companyId); + Task> AddAppUserRoleAsync(Guid appId, IEnumerable userRoles); /// /// Return Agreements for App_Contract Category @@ -84,33 +82,29 @@ public interface IAppReleaseBusinessLogic /// /// /// - /// /// - Task DeleteAppRoleAsync(Guid appId, Guid roleId, Guid companyId); + Task DeleteAppRoleAsync(Guid appId, Guid roleId); /// /// Get Sales Manager Data /// - /// /// - IAsyncEnumerable GetAppProviderSalesManagersAsync(Guid companyId); + IAsyncEnumerable GetAppProviderSalesManagersAsync(); /// /// Creates an application and returns its generated ID. /// /// - /// /// Guid of the created app. - Task AddAppAsync(AppRequestModel appRequestModel, Guid companyId); + Task AddAppAsync(AppRequestModel appRequestModel); /// /// Creates an application and returns its generated ID. /// /// /// - /// /// Guid of the created app. - Task UpdateAppReleaseAsync(Guid appId, AppRequestModel appRequestModel, Guid companyId); + Task UpdateAppReleaseAsync(Guid appId, AppRequestModel appRequestModel); /// /// Retrieves all in review status apps in the marketplace. @@ -161,17 +155,15 @@ public interface IAppReleaseBusinessLogic /// Delete App /// /// - /// /// - Task DeleteAppAsync(Guid appId, Guid companyId); + Task DeleteAppAsync(Guid appId); /// /// Sets the instance type and all related data for the app /// /// Id of the app /// the data for the app instance - /// id of the current user - Task SetInstanceType(Guid appId, AppInstanceSetupData data, Guid companyId); + Task SetInstanceType(Guid appId, AppInstanceSetupData data); /// /// Get technical user profiles for a specific offer diff --git a/src/marketplace/Apps.Service/Controllers/AppChangeController.cs b/src/marketplace/Apps.Service/Controllers/AppChangeController.cs index 872100ec8a..ac2939566f 100644 --- a/src/marketplace/Apps.Service/Controllers/AppChangeController.cs +++ b/src/marketplace/Apps.Service/Controllers/AppChangeController.cs @@ -24,7 +24,6 @@ using Org.Eclipse.TractusX.Portal.Backend.Apps.Service.ViewModels; using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling.Library; using Org.Eclipse.TractusX.Portal.Backend.Framework.Models; -using Org.Eclipse.TractusX.Portal.Backend.Keycloak.Authentication; using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; namespace Org.Eclipse.TractusX.Portal.Backend.Apps.Service.Controllers; @@ -70,8 +69,8 @@ public AppChangeController(IAppChangeBusinessLogic businessLogic) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] - public async Task> AddActiveAppUserRole([FromRoute] Guid appId, [FromBody] IEnumerable userRoles) => - await this.WithUserIdAndCompanyId(identity => _businessLogic.AddActiveAppUserRoleAsync(appId, userRoles, identity)).ConfigureAwait(false); + public Task> AddActiveAppUserRole([FromRoute] Guid appId, [FromBody] IEnumerable userRoles) => + _businessLogic.AddActiveAppUserRoleAsync(appId, userRoles); /// /// Get description of the app by Id. @@ -88,8 +87,8 @@ public async Task> AddActiveAppUserRole([FromRoute] Gui [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] - public async Task> GetAppUpdateDescriptionsAsync([FromRoute] Guid appId) => - await this.WithCompanyId(companyId => _businessLogic.GetAppUpdateDescriptionByIdAsync(appId, companyId)).ConfigureAwait(false); + public Task> GetAppUpdateDescriptionsAsync([FromRoute] Guid appId) => + _businessLogic.GetAppUpdateDescriptionByIdAsync(appId); /// /// Create or Update description of the app by Id. @@ -108,7 +107,7 @@ public async Task> GetAppUpdateDescriptionsAsy [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task CreateOrUpdateAppDescriptionsByIdAsync([FromRoute] Guid appId, [FromBody] IEnumerable offerDescriptionDatas) { - await this.WithCompanyId(companyId => _businessLogic.CreateOrUpdateAppDescriptionByIdAsync(appId, companyId, offerDescriptionDatas)).ConfigureAwait(false); + await _businessLogic.CreateOrUpdateAppDescriptionByIdAsync(appId, offerDescriptionDatas).ConfigureAwait(false); return NoContent(); } /// @@ -135,7 +134,7 @@ public async Task CreateOrUpdateAppDescriptionsByIdAsync([FromR [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync([FromRoute] Guid appId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) { - await this.WithUserIdAndCompanyId(identity => _businessLogic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, identity, document, cancellationToken)); + await _businessLogic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, document, cancellationToken); return NoContent(); } @@ -183,7 +182,7 @@ public async Task DeactivateApp([FromRoute] Guid appId) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task UpdateTenantUrl([FromRoute] Guid appId, [FromRoute] Guid subscriptionId, [FromBody] UpdateTenantData data) { - await this.WithCompanyId(companyId => _businessLogic.UpdateTenantUrlAsync(appId, subscriptionId, data, companyId)).ConfigureAwait(false); + await _businessLogic.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); return NoContent(); } diff --git a/src/marketplace/Apps.Service/Controllers/AppReleaseProcessController.cs b/src/marketplace/Apps.Service/Controllers/AppReleaseProcessController.cs index 9333999d93..bb40e9cb03 100644 --- a/src/marketplace/Apps.Service/Controllers/AppReleaseProcessController.cs +++ b/src/marketplace/Apps.Service/Controllers/AppReleaseProcessController.cs @@ -79,7 +79,7 @@ public AppReleaseProcessController(IAppReleaseBusinessLogic appReleaseBusinessLo [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] public async Task UpdateAppDocumentAsync([FromRoute] Guid appId, [FromRoute] DocumentTypeId documentTypeId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) { - await this.WithUserIdAndCompanyId(identity => _appReleaseBusinessLogic.CreateAppDocumentAsync(appId, documentTypeId, document, identity, cancellationToken)); + await _appReleaseBusinessLogic.CreateAppDocumentAsync(appId, documentTypeId, document, cancellationToken); return NoContent(); } @@ -101,8 +101,8 @@ public async Task UpdateAppDocumentAsync([FromRoute] Guid appId [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] - public async Task> AddAppUserRole([FromRoute] Guid appId, [FromBody] IEnumerable userRoles) => - await this.WithCompanyId(companyId => _appReleaseBusinessLogic.AddAppUserRoleAsync(appId, userRoles, companyId)).ConfigureAwait(false); + public Task> AddAppUserRole([FromRoute] Guid appId, [FromBody] IEnumerable userRoles) => + _appReleaseBusinessLogic.AddAppUserRoleAsync(appId, userRoles); /// /// Return Agreement Data for offer_type_id App @@ -193,7 +193,7 @@ public Task GetAppDetailsForStatusAsync([FromRoute] Guid ap [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task DeleteAppRoleAsync([FromRoute] Guid appId, [FromRoute] Guid roleId) { - await this.WithCompanyId(companyId => _appReleaseBusinessLogic.DeleteAppRoleAsync(appId, roleId, companyId)); + await _appReleaseBusinessLogic.DeleteAppRoleAsync(appId, roleId); return NoContent(); } @@ -208,7 +208,7 @@ public async Task DeleteAppRoleAsync([FromRoute] Guid appId, [F [Authorize(Policy = PolicyTypes.ValidCompany)] [ProducesResponseType(typeof(IAsyncEnumerable), StatusCodes.Status200OK)] public IAsyncEnumerable GetAppProviderSalesManagerAsync() => - this.WithCompanyId(companyId => _appReleaseBusinessLogic.GetAppProviderSalesManagersAsync(companyId)); + _appReleaseBusinessLogic.GetAppProviderSalesManagersAsync(); /// /// Creates an app according to request model @@ -228,7 +228,7 @@ public IAsyncEnumerable GetAppProviderSalesManagerAsync() = [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task ExecuteAppCreation([FromBody] AppRequestModel appRequestModel) { - var appId = await this.WithCompanyId(companyId => _appReleaseBusinessLogic.AddAppAsync(appRequestModel, companyId).ConfigureAwait(false)); + var appId = await _appReleaseBusinessLogic.AddAppAsync(appRequestModel).ConfigureAwait(false); return CreatedAtRoute(nameof(AppsController.GetAppDetailsByIdAsync), new { controller = "Apps", appId = appId }, appId); } @@ -255,7 +255,7 @@ public async Task ExecuteAppCreation([FromBody] AppRequest [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task UpdateAppRelease([FromRoute] Guid appId, [FromBody] AppRequestModel appRequestModel) { - await this.WithCompanyId(companyId => _appReleaseBusinessLogic.UpdateAppReleaseAsync(appId, appRequestModel, companyId).ConfigureAwait(false)); + await _appReleaseBusinessLogic.UpdateAppReleaseAsync(appId, appRequestModel).ConfigureAwait(false); return NoContent(); } @@ -426,7 +426,7 @@ public async Task DeleteAppDocumentsAsync([FromRoute] Guid docu [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task DeleteAppAsync([FromRoute] Guid appId) { - await this.WithCompanyId(companyId => _appReleaseBusinessLogic.DeleteAppAsync(appId, companyId)).ConfigureAwait(false); + await _appReleaseBusinessLogic.DeleteAppAsync(appId).ConfigureAwait(false); return NoContent(); } @@ -450,7 +450,7 @@ public async Task DeleteAppAsync([FromRoute] Guid appId) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task SetInstanceType([FromRoute] Guid appId, [FromBody] AppInstanceSetupData data) { - await this.WithCompanyId(companyId => _appReleaseBusinessLogic.SetInstanceType(appId, data, companyId)).ConfigureAwait(false); + await _appReleaseBusinessLogic.SetInstanceType(appId, data).ConfigureAwait(false); return NoContent(); } diff --git a/src/marketplace/Offers.Library.Web/IOfferDocumentService.cs b/src/marketplace/Offers.Library.Web/IOfferDocumentService.cs index 25a537108d..e4b76da924 100644 --- a/src/marketplace/Offers.Library.Web/IOfferDocumentService.cs +++ b/src/marketplace/Offers.Library.Web/IOfferDocumentService.cs @@ -35,9 +35,8 @@ public interface IOfferDocumentService /// /// /// - /// /// /// /// - Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, OfferTypeId offerTypeId, IEnumerable uploadDocumentTypeIdSettings, CancellationToken cancellationToken); + Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IFormFile document, OfferTypeId offerTypeId, IEnumerable uploadDocumentTypeIdSettings, CancellationToken cancellationToken); } diff --git a/src/marketplace/Offers.Library.Web/OfferDocumentService.cs b/src/marketplace/Offers.Library.Web/OfferDocumentService.cs index 519af98cc6..a686b17573 100644 --- a/src/marketplace/Offers.Library.Web/OfferDocumentService.cs +++ b/src/marketplace/Offers.Library.Web/OfferDocumentService.cs @@ -26,23 +26,27 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Extensions; 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.Offers.Library.Web; public class OfferDocumentService : IOfferDocumentService { private readonly IPortalRepositories _portalRepositories; + private readonly IIdentityService _identityService; /// /// Constructor. /// /// Factory to access the repositories - public OfferDocumentService(IPortalRepositories portalRepositories) + /// Access to the identity + public OfferDocumentService(IPortalRepositories portalRepositories, IIdentityService identityService) { _portalRepositories = portalRepositories; + _identityService = identityService; } - public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, OfferTypeId offerTypeId, IEnumerable uploadDocumentTypeIdSettings, CancellationToken cancellationToken) + public async Task UploadDocumentAsync(Guid id, DocumentTypeId documentTypeId, IFormFile document, OfferTypeId offerTypeId, IEnumerable uploadDocumentTypeIdSettings, CancellationToken cancellationToken) { if (id == Guid.Empty) { @@ -54,6 +58,7 @@ 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) { diff --git a/src/marketplace/Services.Service/BusinessLogic/IServiceReleaseBusinessLogic.cs b/src/marketplace/Services.Service/BusinessLogic/IServiceReleaseBusinessLogic.cs index 5b40ac72c5..d312dfd047 100644 --- a/src/marketplace/Services.Service/BusinessLogic/IServiceReleaseBusinessLogic.cs +++ b/src/marketplace/Services.Service/BusinessLogic/IServiceReleaseBusinessLogic.cs @@ -94,8 +94,7 @@ public interface IServiceReleaseBusinessLogic /// /// Id of the service to update /// Data of the updated entry - /// CompanyId of User - Task UpdateServiceAsync(Guid serviceId, ServiceUpdateRequestData data, Guid companyId); + Task UpdateServiceAsync(Guid serviceId, ServiceUpdateRequestData data); /// /// Update app status and create notification @@ -123,10 +122,9 @@ public interface IServiceReleaseBusinessLogic /// /// /// - /// /// /// - Task CreateServiceDocumentAsync(Guid serviceId, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken); + Task CreateServiceDocumentAsync(Guid serviceId, DocumentTypeId documentTypeId, IFormFile document, CancellationToken cancellationToken); /// /// Delete the Service Document diff --git a/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs b/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs index 96fa2c752c..d427ff037f 100644 --- a/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs +++ b/src/marketplace/Services.Service/BusinessLogic/ServiceReleaseBusinessLogic.cs @@ -28,6 +28,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Services.Service.ViewModels; namespace Org.Eclipse.TractusX.Portal.Backend.Services.Service.BusinessLogic; @@ -40,6 +41,7 @@ public class ServiceReleaseBusinessLogic : IServiceReleaseBusinessLogic private readonly IPortalRepositories _portalRepositories; private readonly IOfferService _offerService; private readonly IOfferDocumentService _offerDocumentService; + private readonly IIdentityService _identityService; private readonly ServiceSettings _settings; /// @@ -48,16 +50,19 @@ public class ServiceReleaseBusinessLogic : IServiceReleaseBusinessLogic /// Factory to access the repositories /// Access to the offer service /// Access to the offer document service + /// Access to identity /// Access to the settings public ServiceReleaseBusinessLogic( IPortalRepositories portalRepositories, IOfferService offerService, IOfferDocumentService offerDocumentService, + IIdentityService identityService, IOptions settings) { _portalRepositories = portalRepositories; _offerService = offerService; _offerDocumentService = offerDocumentService; + _identityService = identityService; _settings = settings.Value; } @@ -160,8 +165,9 @@ public Task CreateServiceOfferingAsync(ServiceOfferingData data) => _offerService.CreateServiceOfferingAsync(data, OfferTypeId.SERVICE); /// - public async Task UpdateServiceAsync(Guid serviceId, ServiceUpdateRequestData data, Guid companyId) + public async Task UpdateServiceAsync(Guid serviceId, ServiceUpdateRequestData data) { + var companyId = _identityService.IdentityData.CompanyId; var serviceData = await _portalRepositories .GetInstance() .GetServiceUpdateData(serviceId, data.ServiceTypeIds, companyId) @@ -242,8 +248,8 @@ public Task DeclineServiceRequestAsync(Guid serviceId, OfferDeclineRequest data) _offerService.DeclineOfferAsync(serviceId, data, OfferTypeId.SERVICE, NotificationTypeId.SERVICE_RELEASE_REJECTION, _settings.ServiceManagerRoles, _settings.ServiceMarketplaceAddress, _settings.SubmitServiceNotificationTypeIds, _settings.CatenaAdminRoles); /// - public Task CreateServiceDocumentAsync(Guid serviceId, DocumentTypeId documentTypeId, IFormFile document, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) => - _offerDocumentService.UploadDocumentAsync(serviceId, documentTypeId, document, identity, OfferTypeId.SERVICE, _settings.UploadServiceDocumentTypeIds, cancellationToken); + public Task CreateServiceDocumentAsync(Guid serviceId, DocumentTypeId documentTypeId, IFormFile document, CancellationToken cancellationToken) => + _offerDocumentService.UploadDocumentAsync(serviceId, documentTypeId, document, OfferTypeId.SERVICE, _settings.UploadServiceDocumentTypeIds, cancellationToken); /// public Task DeleteServiceDocumentsAsync(Guid documentId) => diff --git a/src/marketplace/Services.Service/Controllers/ServiceReleaseController.cs b/src/marketplace/Services.Service/Controllers/ServiceReleaseController.cs index cd0078ed6d..8871f12aa2 100644 --- a/src/marketplace/Services.Service/Controllers/ServiceReleaseController.cs +++ b/src/marketplace/Services.Service/Controllers/ServiceReleaseController.cs @@ -237,7 +237,7 @@ public async Task CreateServiceOffering([FromBody] Service [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task UpdateService([FromRoute] Guid serviceId, [FromBody] ServiceUpdateRequestData data) { - await this.WithCompanyId(companyId => _serviceReleaseBusinessLogic.UpdateServiceAsync(serviceId, data, companyId)); + await _serviceReleaseBusinessLogic.UpdateServiceAsync(serviceId, data); return NoContent(); } @@ -342,7 +342,7 @@ public async Task DeclineServiceRequest([FromRoute] Guid servic [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] public async Task UpdateServiceDocumentAsync([FromRoute] Guid serviceId, [FromRoute] DocumentTypeId documentTypeId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) { - await this.WithUserIdAndCompanyId(identity => _serviceReleaseBusinessLogic.CreateServiceDocumentAsync(serviceId, documentTypeId, document, identity, cancellationToken)); + await _serviceReleaseBusinessLogic.CreateServiceDocumentAsync(serviceId, documentTypeId, document, cancellationToken); return NoContent(); } diff --git a/src/notifications/Notifications.Service/BusinessLogic/INotificationBusinessLogic.cs b/src/notifications/Notifications.Service/BusinessLogic/INotificationBusinessLogic.cs index 239cc764b0..0a174b04fa 100644 --- a/src/notifications/Notifications.Service/BusinessLogic/INotificationBusinessLogic.cs +++ b/src/notifications/Notifications.Service/BusinessLogic/INotificationBusinessLogic.cs @@ -34,46 +34,40 @@ public interface INotificationBusinessLogic /// /// the requested page /// the requested size - /// The id of the current user /// additional filters to query notifications /// Returns a collection of the users notification - Task> GetNotificationsAsync(int page, int size, Guid receiverUserId, NotificationFilters filters); + Task> GetNotificationsAsync(int page, int size, NotificationFilters filters); /// /// Gets a specific notification for the given user. /// - /// The id of the current user /// The id of the notification /// Returns a notification - Task GetNotificationDetailDataAsync(Guid userId, Guid notificationId); + Task GetNotificationDetailDataAsync(Guid notificationId); /// /// Gets the notification account for the given user /// - /// Id of the current identity /// OPTIONAL: filter for read or unread notifications /// Returns the count of the notifications - Task GetNotificationCountAsync(Guid userId, bool? isRead); + Task GetNotificationCountAsync(bool? isRead); /// /// Gets the count details of the notifications for the given user /// - /// Id of the current identity /// Returns the count details of the notifications - Task GetNotificationCountDetailsAsync(Guid userId); + Task GetNotificationCountDetailsAsync(); /// /// Sets the status of the notification with the given id to read /// - /// Id of the notification receiver /// Id of the notification /// Read or unread - Task SetNotificationStatusAsync(Guid userId, Guid notificationId, bool isRead); + Task SetNotificationStatusAsync(Guid notificationId, bool isRead); /// /// Deletes the given notification /// - /// Id of the notification receiver /// Id of the notification that should be deleted - Task DeleteNotificationAsync(Guid userId, Guid notificationId); + Task DeleteNotificationAsync(Guid notificationId); } diff --git a/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs b/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs index c47458862a..17ea3936af 100644 --- a/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs +++ b/src/notifications/Notifications.Service/BusinessLogic/NotificationBusinessLogic.cs @@ -26,6 +26,7 @@ using Org.Eclipse.TractusX.Portal.Backend.PortalBackend.DBAccess.Models; 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.Notifications.Service.BusinessLogic; @@ -33,28 +34,31 @@ namespace Org.Eclipse.TractusX.Portal.Backend.Notifications.Service.BusinessLogi public class NotificationBusinessLogic : INotificationBusinessLogic { private readonly IPortalRepositories _portalRepositories; + private readonly IIdentityService _identityService; private readonly NotificationSettings _settings; /// /// Creates a new instance of /// /// Access to the repository factory. + /// Access to the identity /// Access to the notifications options - public NotificationBusinessLogic(IPortalRepositories portalRepositories, IOptions settings) + public NotificationBusinessLogic(IPortalRepositories portalRepositories, IIdentityService identityService, IOptions settings) { _portalRepositories = portalRepositories; + _identityService = identityService; _settings = settings.Value; } /// - public Task> GetNotificationsAsync(int page, int size, Guid receiverUserId, NotificationFilters filters) => + public Task> GetNotificationsAsync(int page, int size, NotificationFilters filters) => Pagination.CreateResponseAsync(page, size, _settings.MaxPageSize, _portalRepositories.GetInstance() - .GetAllNotificationDetailsByReceiver(receiverUserId, filters.IsRead, filters.TypeId, filters.TopicId, filters.OnlyDueDate, filters.Sorting ?? NotificationSorting.DateDesc, filters.DoneState, filters.SearchTypeIds, filters.SearchQuery)); + .GetAllNotificationDetailsByReceiver(_identityService.IdentityData.UserId, filters.IsRead, filters.TypeId, filters.TopicId, filters.OnlyDueDate, filters.Sorting ?? NotificationSorting.DateDesc, filters.DoneState, filters.SearchTypeIds, filters.SearchQuery)); /// - public async Task GetNotificationDetailDataAsync(Guid userId, Guid notificationId) + public async Task GetNotificationDetailDataAsync(Guid notificationId) { - var result = await _portalRepositories.GetInstance().GetNotificationByIdAndValidateReceiverAsync(notificationId, userId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetNotificationByIdAndValidateReceiverAsync(notificationId, _identityService.IdentityData.UserId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"Notification {notificationId} does not exist."); @@ -67,13 +71,13 @@ public async Task GetNotificationDetailDataAsync(Guid us } /// - public Task GetNotificationCountAsync(Guid userId, bool? isRead) => - _portalRepositories.GetInstance().GetNotificationCountForUserAsync(userId, isRead); + public Task GetNotificationCountAsync(bool? isRead) => + _portalRepositories.GetInstance().GetNotificationCountForUserAsync(_identityService.IdentityData.UserId, isRead); /// - public async Task GetNotificationCountDetailsAsync(Guid userId) + public async Task GetNotificationCountDetailsAsync() { - var details = await _portalRepositories.GetInstance().GetCountDetailsForUserAsync(userId).ToListAsync().ConfigureAwait(false); + var details = await _portalRepositories.GetInstance().GetCountDetailsForUserAsync(_identityService.IdentityData.UserId).ToListAsync().ConfigureAwait(false); var unreadNotifications = details.Where(x => !x.IsRead); return new NotificationCountDetails( details.Where(x => x.IsRead).Sum(x => x.Count), @@ -85,9 +89,9 @@ public async Task GetNotificationCountDetailsAsync(Gui } /// - public async Task SetNotificationStatusAsync(Guid userId, Guid notificationId, bool isRead) + public async Task SetNotificationStatusAsync(Guid notificationId, bool isRead) { - var isReadFlag = await CheckNotificationExistsAndValidateReceiver(notificationId, userId).ConfigureAwait(false); + var isReadFlag = await CheckNotificationExistsAndValidateReceiver(notificationId).ConfigureAwait(false); _portalRepositories.GetInstance().AttachAndModifyNotification(notificationId, notification => { @@ -102,17 +106,17 @@ public async Task SetNotificationStatusAsync(Guid userId, Guid notificationId, b } /// - public async Task DeleteNotificationAsync(Guid userId, Guid notificationId) + public async Task DeleteNotificationAsync(Guid notificationId) { - await CheckNotificationExistsAndValidateReceiver(notificationId, userId).ConfigureAwait(false); + await CheckNotificationExistsAndValidateReceiver(notificationId).ConfigureAwait(false); _portalRepositories.GetInstance().DeleteNotification(notificationId); await _portalRepositories.SaveAsync().ConfigureAwait(false); } - private async Task CheckNotificationExistsAndValidateReceiver(Guid notificationId, Guid userId) + private async Task CheckNotificationExistsAndValidateReceiver(Guid notificationId) { - var result = await _portalRepositories.GetInstance().CheckNotificationExistsByIdAndValidateReceiverAsync(notificationId, userId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().CheckNotificationExistsByIdAndValidateReceiverAsync(notificationId, _identityService.IdentityData.UserId).ConfigureAwait(false); if (result == default || !result.IsNotificationExisting) { throw new NotFoundException($"Notification {notificationId} does not exist."); diff --git a/src/notifications/Notifications.Service/Controllers/NotificationController.cs b/src/notifications/Notifications.Service/Controllers/NotificationController.cs index 4a96fa2c2b..173784213e 100644 --- a/src/notifications/Notifications.Service/Controllers/NotificationController.cs +++ b/src/notifications/Notifications.Service/Controllers/NotificationController.cs @@ -84,7 +84,7 @@ public NotificationController(INotificationBusinessLogic logic) [FromQuery] bool? doneState = null, [FromQuery] string? searchQuery = null ) => - this.WithUserId(userId => _logic.GetNotificationsAsync(page, size, userId, new NotificationFilters(isRead, notificationTypeId, notificationTopicId, onlyDueDate, sorting, doneState, searchTypeIds, searchQuery))); + _logic.GetNotificationsAsync(page, size, new NotificationFilters(isRead, notificationTypeId, notificationTopicId, onlyDueDate, sorting, doneState, searchTypeIds, searchQuery)); /// /// Gets a notification for the logged in user @@ -102,7 +102,7 @@ public NotificationController(INotificationBusinessLogic logic) [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task GetNotification([FromRoute] Guid notificationId) => - this.WithUserId(userId => _logic.GetNotificationDetailDataAsync(userId, notificationId)); + _logic.GetNotificationDetailDataAsync(notificationId); /// /// Gets the notification count for the current logged in user @@ -122,7 +122,7 @@ public Task GetNotification([FromRoute] Guid notificatio [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task NotificationCount([FromQuery] bool? isRead) => - this.WithUserId(userId => _logic.GetNotificationCountAsync(userId, isRead)); + _logic.GetNotificationCountAsync(isRead); /// /// Gets the notification count for the current logged in user @@ -136,7 +136,7 @@ public Task NotificationCount([FromQuery] bool? isRead) => [Authorize(Policy = PolicyTypes.ValidIdentity)] [ProducesResponseType(typeof(NotificationCountDetails), StatusCodes.Status200OK)] public Task NotificationCountDetails() => - this.WithUserId(userId => _logic.GetNotificationCountDetailsAsync(userId)); + _logic.GetNotificationCountDetailsAsync(); /// /// Changes the read status of a notification @@ -158,7 +158,7 @@ public Task NotificationCountDetails() => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task SetNotificationToRead([FromRoute] Guid notificationId, [FromQuery] bool isRead = true) { - await this.WithUserId(userId => _logic.SetNotificationStatusAsync(userId, notificationId, isRead)).ConfigureAwait(false); + await _logic.SetNotificationStatusAsync(notificationId, isRead).ConfigureAwait(false); return NoContent(); } @@ -180,7 +180,7 @@ public async Task SetNotificationToRead([FromRoute] Guid notificat [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public async Task DeleteNotification([FromRoute] Guid notificationId) { - await this.WithUserId(userId => _logic.DeleteNotificationAsync(userId, notificationId)).ConfigureAwait(false); + await _logic.DeleteNotificationAsync(notificationId).ConfigureAwait(false); return NoContent(); } } diff --git a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs index 0d10101730..01e67538c5 100644 --- a/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/IRegistrationBusinessLogic.cs @@ -29,31 +29,30 @@ public interface IRegistrationBusinessLogic { Task GetCompanyBpdmDetailDataByBusinessPartnerNumber(string businessPartnerNumber, string token, CancellationToken cancellationToken); IAsyncEnumerable GetClientRolesCompositeAsync(); - Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken); + Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken); /// /// Gets the file content from the persistence store for the given user /// /// The Id of the document that should be get - /// The Identity of the current user /// - Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId, Guid userId); + Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId); - IAsyncEnumerable GetAllApplicationsForUserWithStatus(Guid companyId); - Task GetCompanyDetailData(Guid applicationId, Guid companyId); - Task SetCompanyDetailDataAsync(Guid applicationId, CompanyDetailData companyDetails, Guid companyId); - Task InviteNewUserAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo, (Guid UserId, Guid CompanyId) identity); - Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, CompanyApplicationStatusId status, Guid companyId); - Task GetOwnCompanyApplicationStatusAsync(Guid applicationId, Guid companyId); - Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgreementConsents roleAgreementConsentStatuses, Guid userId, Guid companyId); - Task GetRoleAgreementConsentsAsync(Guid applicationId, Guid userId); + IAsyncEnumerable GetAllApplicationsForUserWithStatus(); + Task GetCompanyDetailData(Guid applicationId); + Task SetCompanyDetailDataAsync(Guid applicationId, CompanyDetailData companyDetails); + Task InviteNewUserAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo); + Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, CompanyApplicationStatusId status); + Task GetOwnCompanyApplicationStatusAsync(Guid applicationId); + Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgreementConsents roleAgreementConsentStatuses); + Task GetRoleAgreementConsentsAsync(Guid applicationId); Task GetCompanyRoleAgreementDataAsync(); - Task SubmitRegistrationAsync(Guid applicationId, Guid userId); + Task SubmitRegistrationAsync(Guid applicationId); IAsyncEnumerable GetInvitedUsersAsync(Guid applicationId); - Task> GetUploadedDocumentsAsync(Guid applicationId, DocumentTypeId documentTypeId, Guid userId); - Task SetInvitationStatusAsync(Guid userId); - Task GetRegistrationDataAsync(Guid applicationId, Guid companyId); - Task DeleteRegistrationDocumentAsync(Guid documentId, Guid companyId); + Task> GetUploadedDocumentsAsync(Guid applicationId, DocumentTypeId documentTypeId); + Task SetInvitationStatusAsync(); + Task GetRegistrationDataAsync(Guid applicationId); + Task DeleteRegistrationDocumentAsync(Guid documentId); IAsyncEnumerable GetCompanyRoles(string? languageShortName = null); Task> GetCompanyIdentifiers(string alpha2Code); Task<(string fileName, byte[] content, string mediaType)> GetRegistrationDocumentAsync(Guid documentId); diff --git a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs index 3cb894e71a..d33e2aa287 100644 --- a/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs +++ b/src/registration/Registration.Service/BusinessLogic/RegistrationBusinessLogic.cs @@ -31,6 +31,7 @@ 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.Processes.ApplicationChecklist.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library; using Org.Eclipse.TractusX.Portal.Backend.Provisioning.Library.Models; @@ -50,6 +51,7 @@ public class RegistrationBusinessLogic : IRegistrationBusinessLogic private readonly IPortalRepositories _portalRepositories; private readonly ILogger _logger; private readonly IApplicationChecklistCreationService _checklistService; + private readonly IIdentityService _identityService; private static readonly Regex bpnRegex = new(@"(\w|\d){16}", RegexOptions.None, TimeSpan.FromSeconds(1)); @@ -61,7 +63,8 @@ public RegistrationBusinessLogic( IUserProvisioningService userProvisioningService, ILogger logger, IPortalRepositories portalRepositories, - IApplicationChecklistCreationService checklistService) + IApplicationChecklistCreationService checklistService, + IIdentityService identityService) { _settings = settings.Value; _mailingService = mailingService; @@ -71,6 +74,7 @@ public RegistrationBusinessLogic( _logger = logger; _portalRepositories = portalRepositories; _checklistService = checklistService; + _identityService = identityService; } public IAsyncEnumerable GetClientRolesCompositeAsync() => @@ -138,7 +142,7 @@ private async Task GetCompanyBpdmDetailDataByBusinessPart } } - public async Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, (Guid UserId, Guid CompanyId) identity, CancellationToken cancellationToken) + public async Task UploadDocumentAsync(Guid applicationId, IFormFile document, DocumentTypeId documentTypeId, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(document.FileName)) { @@ -156,6 +160,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); if (!validApplicationForCompany) { @@ -172,10 +177,10 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId, Guid userId) + public async Task<(string FileName, byte[] Content, string MediaType)> GetDocumentContentAsync(Guid documentId) { var documentRepository = _portalRepositories.GetInstance(); - var documentDetails = await documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, userId).ConfigureAwait(false); + var documentDetails = await documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identityService.IdentityData.UserId).ConfigureAwait(false); if (documentDetails.DocumentId == Guid.Empty) { throw new NotFoundException($"document {documentId} does not exist."); @@ -194,12 +199,12 @@ public async Task UploadDocumentAsync(Guid applicationId, IFormFile documen return (document.DocumentName, document.DocumentContent, document.MediaTypeId.MapToMediaType()); } - public IAsyncEnumerable GetAllApplicationsForUserWithStatus(Guid companyId) => - _portalRepositories.GetInstance().GetApplicationsWithStatusUntrackedAsync(companyId); + public IAsyncEnumerable GetAllApplicationsForUserWithStatus() => + _portalRepositories.GetInstance().GetApplicationsWithStatusUntrackedAsync(_identityService.IdentityData.CompanyId); - public async Task GetCompanyDetailData(Guid applicationId, Guid companyId) + public async Task GetCompanyDetailData(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetCompanyApplicationDetailDataAsync(applicationId, companyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetCompanyApplicationDetailDataAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); if (result == null) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -224,7 +229,7 @@ public async Task GetCompanyDetailData(Guid applicationId, Gu ); } - public Task SetCompanyDetailDataAsync(Guid applicationId, CompanyDetailData companyDetails, Guid companyId) + public Task SetCompanyDetailDataAsync(Guid applicationId, CompanyDetailData companyDetails) { if (string.IsNullOrWhiteSpace(companyDetails.Name)) { @@ -253,17 +258,17 @@ public Task SetCompanyDetailDataAsync(Guid applicationId, CompanyDetailData comp var duplicateIds = companyDetails.UniqueIds.Except(distinctIds); throw new ControllerArgumentException($"uniqueIds must not contain duplicate types: '{string.Join(", ", duplicateIds.Select(uniqueId => uniqueId.UniqueIdentifierId))}'", nameof(companyDetails.UniqueIds)); } - return SetCompanyDetailDataInternal(applicationId, companyDetails, companyId); + return SetCompanyDetailDataInternal(applicationId, companyDetails); } - private async Task SetCompanyDetailDataInternal(Guid applicationId, CompanyDetailData companyDetails, Guid companyId) + private async Task SetCompanyDetailDataInternal(Guid applicationId, CompanyDetailData companyDetails) { await ValidateCountryAssignedIdentifiers(companyDetails).ConfigureAwait(false); var applicationRepository = _portalRepositories.GetInstance(); var companyRepository = _portalRepositories.GetInstance(); - var companyApplicationData = await GetAndValidateApplicationData(applicationId, companyDetails, companyId, applicationRepository).ConfigureAwait(false); + var companyApplicationData = await GetAndValidateApplicationData(applicationId, companyDetails, applicationRepository).ConfigureAwait(false); var addressId = CreateOrModifyAddress(companyApplicationData, companyDetails, companyRepository); @@ -298,10 +303,10 @@ private async Task ValidateCountryAssignedIdentifiers(CompanyDetailData companyD } } - private static async Task GetAndValidateApplicationData(Guid applicationId, CompanyDetailData companyDetails, Guid companyId, IApplicationRepository applicationRepository) + private async Task GetAndValidateApplicationData(Guid applicationId, CompanyDetailData companyDetails, IApplicationRepository applicationRepository) { var companyApplicationData = await applicationRepository - .GetCompanyApplicationDetailDataAsync(applicationId, companyId, companyDetails.CompanyId) + .GetCompanyApplicationDetailDataAsync(applicationId, _identityService.IdentityData.CompanyId, companyDetails.CompanyId) .ConfigureAwait(false); if (companyApplicationData == null) @@ -383,17 +388,18 @@ private static void ModifyCompany(Guid addressId, CompanyApplicationDetailData i c.AddressId = addressId; }); - public Task InviteNewUserAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo, (Guid UserId, Guid CompanyId) identity) + public Task InviteNewUserAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo) { if (string.IsNullOrEmpty(userCreationInfo.eMail)) { throw new ControllerArgumentException($"email must not be empty"); } - return InviteNewUserInternalAsync(applicationId, userCreationInfo, identity); + return InviteNewUserInternalAsync(applicationId, userCreationInfo); } - private async Task InviteNewUserInternalAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo, (Guid UserId, Guid CompanyId) identity) + private async Task InviteNewUserInternalAsync(Guid applicationId, UserCreationInfoWithMessage userCreationInfo) { + var identity = _identityService.IdentityData; if (await _portalRepositories.GetInstance().IsOwnCompanyUserWithEmailExisting(userCreationInfo.eMail, identity.CompanyId)) { throw new ControllerArgumentException($"user with email {userCreationInfo.eMail} does already exist"); @@ -454,7 +460,7 @@ private async Task InviteNewUserInternalAsync(Guid applicationId, UserCreat return modified; } - public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, CompanyApplicationStatusId status, Guid companyId) + public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, CompanyApplicationStatusId status) { if (status == 0) { @@ -462,7 +468,7 @@ public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, C } var applicationRepository = _portalRepositories.GetInstance(); - var applicationUserData = await applicationRepository.GetOwnCompanyApplicationUserDataAsync(applicationId, companyId).ConfigureAwait(false); + var applicationUserData = await applicationRepository.GetOwnCompanyApplicationUserDataAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); if (!applicationUserData.Exists) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -473,9 +479,9 @@ public async Task SetOwnCompanyApplicationStatusAsync(Guid applicationId, C return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async Task GetOwnCompanyApplicationStatusAsync(Guid applicationId, Guid companyId) + public async Task GetOwnCompanyApplicationStatusAsync(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetOwnCompanyApplicationStatusUserDataUntrackedAsync(applicationId, companyId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetOwnCompanyApplicationStatusUserDataUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); if (!result.Exists) { throw new NotFoundException($"CompanyApplication {applicationId} not found"); @@ -487,7 +493,7 @@ public async Task GetOwnCompanyApplicationStatusAsyn return result.ApplicationStatus; } - public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgreementConsents roleAgreementConsentStatuses, Guid userId, Guid companyId) + public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgreementConsents roleAgreementConsentStatuses) { var companyRoleIdsToSet = roleAgreementConsentStatuses.CompanyRoleIds; var agreementConsentsToSet = roleAgreementConsentStatuses.AgreementConsentStatuses; @@ -502,6 +508,8 @@ public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgr throw new NotFoundException($"application {applicationId} does not exist"); } + var companyId = _identityService.IdentityData.CompanyId; + var userId = _identityService.IdentityData.UserId; var (applicationCompanyId, applicationStatusId, companyAssignedRoleIds, consents) = companyRoleAgreementConsentData; if (applicationCompanyId != companyId) { @@ -542,9 +550,9 @@ public async Task SubmitRoleConsentAsync(Guid applicationId, CompanyRoleAgr return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async Task GetRoleAgreementConsentsAsync(Guid applicationId, Guid userId) + public async Task GetRoleAgreementConsentsAsync(Guid applicationId) { - var result = await _portalRepositories.GetInstance().GetCompanyRoleAgreementConsentStatusUntrackedAsync(applicationId, userId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetCompanyRoleAgreementConsentStatusUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId).ConfigureAwait(false); if (result == null) { throw new ForbiddenException($"user is not assigned with CompanyApplication {applicationId}"); @@ -558,9 +566,9 @@ public async Task GetCompanyRoleAgreementDataAsync() = (await _portalRepositories.GetInstance().GetAgreementsForCompanyRolesUntrackedAsync().ToListAsync().ConfigureAwait(false)).AsEnumerable() ); - public async Task SubmitRegistrationAsync(Guid applicationId, Guid userId) + public async Task SubmitRegistrationAsync(Guid applicationId) { - var applicationUserData = await GetAndValidateCompanyDataDetails(applicationId, userId, _settings.SubmitDocumentTypeIds).ConfigureAwait(false); + var applicationUserData = await GetAndValidateCompanyDataDetails(applicationId, _settings.SubmitDocumentTypeIds).ConfigureAwait(false); if (GetAndValidateUpdateApplicationStatus(applicationUserData.CompanyApplicationStatusId, UpdateApplicationSteps.SubmitRegistration) != CompanyApplicationStatusId.SUBMITTED) { @@ -605,14 +613,15 @@ public async Task SubmitRegistrationAsync(Guid applicationId, Guid userId) } else { - _logger.LogInformation("user {userId} has no email-address", userId); + _logger.LogInformation("user {userId} has no email-address", _identityService.IdentityData.UserId); } return true; } - private async ValueTask GetAndValidateCompanyDataDetails(Guid applicationId, Guid userId, IEnumerable docTypeIds) + private async ValueTask GetAndValidateCompanyDataDetails(Guid applicationId, IEnumerable docTypeIds) { + var userId = _identityService.IdentityData.UserId; var applicationUserData = await _portalRepositories.GetInstance() .GetOwnCompanyApplicationUserEmailDataAsync(applicationId, userId, docTypeIds).ConfigureAwait(false); @@ -681,9 +690,9 @@ public async IAsyncEnumerable GetInvitedUsersAsync(Guid application } } - public async Task> GetUploadedDocumentsAsync(Guid applicationId, DocumentTypeId documentTypeId, Guid userId) + public async Task> GetUploadedDocumentsAsync(Guid applicationId, DocumentTypeId documentTypeId) { - var result = await _portalRepositories.GetInstance().GetUploadedDocumentsAsync(applicationId, documentTypeId, userId).ConfigureAwait(false); + var result = await _portalRepositories.GetInstance().GetUploadedDocumentsAsync(applicationId, documentTypeId, _identityService.IdentityData.UserId).ConfigureAwait(false); if (result == default) { throw new NotFoundException($"application {applicationId} not found"); @@ -695,9 +704,9 @@ public async Task> GetUploadedDocumentsAsync(Guid a return result.Documents; } - public async Task SetInvitationStatusAsync(Guid userId) + public async Task SetInvitationStatusAsync() { - var invitationData = await _portalRepositories.GetInstance().GetInvitationStatusAsync(userId).ConfigureAwait(false); + var invitationData = await _portalRepositories.GetInstance().GetInvitationStatusAsync(_identityService.IdentityData.UserId).ConfigureAwait(false); if (invitationData == null) { @@ -712,9 +721,9 @@ public async Task SetInvitationStatusAsync(Guid userId) return await _portalRepositories.SaveAsync().ConfigureAwait(false); } - public async Task GetRegistrationDataAsync(Guid applicationId, Guid companyId) + public async Task GetRegistrationDataAsync(Guid applicationId) { - var (isValidApplicationId, isValidCompany, data) = await _portalRepositories.GetInstance().GetRegistrationDataUntrackedAsync(applicationId, companyId, _settings.DocumentTypeIds).ConfigureAwait(false); + var (isValidApplicationId, isValidCompany, data) = await _portalRepositories.GetInstance().GetRegistrationDataUntrackedAsync(applicationId, _identityService.IdentityData.CompanyId, _settings.DocumentTypeIds).ConfigureAwait(false); if (!isValidApplicationId) { throw new NotFoundException($"application {applicationId} does not exist"); @@ -857,14 +866,14 @@ _ when (applicationStatusId == CompanyApplicationStatusId.SUBMITTED || }; } - public async Task DeleteRegistrationDocumentAsync(Guid documentId, Guid companyId) + public async Task DeleteRegistrationDocumentAsync(Guid documentId) { if (documentId == Guid.Empty) { throw new ControllerArgumentException($"documentId must not be empty"); } var documentRepository = _portalRepositories.GetInstance(); - var details = await documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, companyId, _settings.ApplicationStatusIds).ConfigureAwait(false); + var details = await documentRepository.GetDocumentDetailsForApplicationUntrackedAsync(documentId, _identityService.IdentityData.CompanyId, _settings.ApplicationStatusIds).ConfigureAwait(false); if (details == default) { throw new NotFoundException("Document does not exist."); diff --git a/src/registration/Registration.Service/Controllers/RegistrationController.cs b/src/registration/Registration.Service/Controllers/RegistrationController.cs index 9359017af6..c9034bcb55 100644 --- a/src/registration/Registration.Service/Controllers/RegistrationController.cs +++ b/src/registration/Registration.Service/Controllers/RegistrationController.cs @@ -95,7 +95,7 @@ public Task GetCompanyBpdmDetailDataAsync([FromRoute] str [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status415UnsupportedMediaType)] public Task UploadDocumentAsync([FromRoute] Guid applicationId, [FromRoute] DocumentTypeId documentTypeId, [FromForm(Name = "document")] IFormFile document, CancellationToken cancellationToken) => - this.WithUserIdAndCompanyId(identity => _registrationBusinessLogic.UploadDocumentAsync(applicationId, document, documentTypeId, identity, cancellationToken)); + _registrationBusinessLogic.UploadDocumentAsync(applicationId, document, documentTypeId, cancellationToken); /// /// Gets a specific document by its id @@ -116,7 +116,7 @@ public Task UploadDocumentAsync([FromRoute] Guid applicationId, [FromRoute] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public async Task GetDocumentContentFileAsync([FromRoute] Guid documentId) { - var (fileName, content, mediaType) = await this.WithUserId(userId => _registrationBusinessLogic.GetDocumentContentAsync(documentId, userId)); + var (fileName, content, mediaType) = await _registrationBusinessLogic.GetDocumentContentAsync(documentId); return File(content, mediaType, fileName); } @@ -138,7 +138,7 @@ public async Task GetDocumentContentFileAsync([FromRoute] Guid doc [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] public Task> GetUploadedDocumentsAsync([FromRoute] Guid applicationId, [FromRoute] DocumentTypeId documentTypeId) => - this.WithUserId(userId => _registrationBusinessLogic.GetUploadedDocumentsAsync(applicationId, documentTypeId, userId)); + _registrationBusinessLogic.GetUploadedDocumentsAsync(applicationId, documentTypeId); /// /// Get all composite client roles @@ -165,7 +165,7 @@ public IAsyncEnumerable GetClientRolesComposite() => [Route("applications")] [ProducesResponseType(typeof(IAsyncEnumerable), StatusCodes.Status200OK)] public IAsyncEnumerable GetApplicationsWithStatusAsync() => - this.WithCompanyId(companyId => _registrationBusinessLogic.GetAllApplicationsForUserWithStatus(companyId)); + _registrationBusinessLogic.GetAllApplicationsForUserWithStatus(); /// /// Sets the status of a specific application. @@ -187,7 +187,7 @@ public IAsyncEnumerable GetApplicationsWithStatusA [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task SetApplicationStatusAsync([FromRoute] Guid applicationId, [FromQuery] CompanyApplicationStatusId status) => - this.WithCompanyId(companyId => _registrationBusinessLogic.SetOwnCompanyApplicationStatusAsync(applicationId, status, companyId)); + _registrationBusinessLogic.SetOwnCompanyApplicationStatusAsync(applicationId, status); /// /// Gets the status of an application for the given id @@ -206,7 +206,7 @@ public Task SetApplicationStatusAsync([FromRoute] Guid applicationId, [From [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task GetApplicationStatusAsync([FromRoute] Guid applicationId) => - this.WithCompanyId(companyId => _registrationBusinessLogic.GetOwnCompanyApplicationStatusAsync(applicationId, companyId)); + _registrationBusinessLogic.GetOwnCompanyApplicationStatusAsync(applicationId); /// /// Gets the company of a specific application with its address @@ -225,8 +225,7 @@ public Task GetApplicationStatusAsync([FromRoute] Gu [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task GetCompanyDetailDataAsync([FromRoute] Guid applicationId) => - this.WithCompanyId(companyId => - _registrationBusinessLogic.GetCompanyDetailData(applicationId, companyId)); + _registrationBusinessLogic.GetCompanyDetailData(applicationId); /// /// Sets the company with its address for the given application id @@ -247,7 +246,7 @@ public Task GetCompanyDetailDataAsync([FromRoute] Guid applic [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task SetCompanyDetailDataAsync([FromRoute] Guid applicationId, [FromBody] CompanyDetailData companyDetailData) => - this.WithCompanyId(companyId => _registrationBusinessLogic.SetCompanyDetailDataAsync(applicationId, companyDetailData, companyId)); + _registrationBusinessLogic.SetCompanyDetailDataAsync(applicationId, companyDetailData); /// /// Invites the given user to the given application @@ -270,7 +269,7 @@ public Task SetCompanyDetailDataAsync([FromRoute] Guid applicationId, [FromBody] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status502BadGateway)] public Task InviteNewUserAsync([FromRoute] Guid applicationId, [FromBody] UserCreationInfoWithMessage userCreationInfo) => - this.WithUserIdAndCompanyId(identity => _registrationBusinessLogic.InviteNewUserAsync(applicationId, userCreationInfo, identity)); + _registrationBusinessLogic.InviteNewUserAsync(applicationId, userCreationInfo); /// /// Post the agreement consent status for the given application. @@ -293,7 +292,7 @@ public Task InviteNewUserAsync([FromRoute] Guid applicationId, [FromBody] U [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status404NotFound)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status400BadRequest)] public Task SubmitCompanyRoleConsentToAgreementsAsync([FromRoute] Guid applicationId, [FromBody] CompanyRoleAgreementConsents companyRolesAgreementConsents) => - this.WithUserIdAndCompanyId(identity => _registrationBusinessLogic.SubmitRoleConsentAsync(applicationId, companyRolesAgreementConsents, identity.UserId, identity.CompanyId)); + _registrationBusinessLogic.SubmitRoleConsentAsync(applicationId, companyRolesAgreementConsents); /// /// Gets the agreement consent statuses for the given application @@ -310,7 +309,7 @@ public Task SubmitCompanyRoleConsentToAgreementsAsync([FromRoute] Guid appl [ProducesResponseType(typeof(CompanyRoleAgreementConsents), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task GetAgreementConsentStatusesAsync([FromRoute] Guid applicationId) => - this.WithUserId(userId => _registrationBusinessLogic.GetRoleAgreementConsentsAsync(applicationId, userId)); + _registrationBusinessLogic.GetRoleAgreementConsentsAsync(applicationId); /// /// Gets the company role agreement data @@ -345,7 +344,7 @@ public Task GetCompanyRoleAgreementDataAsync() => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status500InternalServerError)] public Task SubmitRegistrationAsync([FromRoute] Guid applicationId) => - this.WithUserId(userId => _registrationBusinessLogic.SubmitRegistrationAsync(applicationId, userId)); + _registrationBusinessLogic.SubmitRegistrationAsync(applicationId); /// /// Gets all invited users for a given application @@ -375,7 +374,7 @@ public IAsyncEnumerable GetInvitedUsersAsync([FromRoute] Guid appli [ProducesResponseType(typeof(int), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] public Task SetInvitationStatusAsync() => - this.WithUserId(userId => _registrationBusinessLogic.SetInvitationStatusAsync(userId)); + _registrationBusinessLogic.SetInvitationStatusAsync(); /// /// Gets the registration data for the given application id @@ -396,8 +395,7 @@ public Task SetInvitationStatusAsync() => [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status403Forbidden)] [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status503ServiceUnavailable)] public Task GetRegistrationDataAsync([FromRoute] Guid applicationId) => - this.WithCompanyId(companyId => - _registrationBusinessLogic.GetRegistrationDataAsync(applicationId, companyId)); + _registrationBusinessLogic.GetRegistrationDataAsync(applicationId); /// /// Gets the company roles and roles description @@ -435,7 +433,7 @@ public IAsyncEnumerable GetCompanyRolesAsync([FromQuery] st [ProducesResponseType(typeof(ErrorResponse), StatusCodes.Status409Conflict)] public async Task DeleteRegistrationDocument([FromRoute] Guid documentId) { - await this.WithCompanyId(companyId => _registrationBusinessLogic.DeleteRegistrationDocumentAsync(documentId, companyId)); + await _registrationBusinessLogic.DeleteRegistrationDocumentAsync(documentId); return NoContent(); } diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs index 1078806779..dbd2f0718e 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/DocumentsBusinessLogicTests.cs @@ -39,6 +39,7 @@ public class DocumentsBusinessLogicTests private readonly IPortalRepositories _portalRepositories; private readonly IOptions _options; private readonly DocumentsBusinessLogic _sut; + private readonly IIdentityService _identityService; public DocumentsBusinessLogicTests() { @@ -53,9 +54,11 @@ public DocumentsBusinessLogicTests() { EnableSeedEndpoint = true }); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_documentRepository); - _sut = new DocumentsBusinessLogic(_portalRepositories, _options); + _sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); } #region GetSeedData @@ -65,7 +68,7 @@ public async Task GetSeedData_WithValidId_ReturnsValidData() { // Arrange SetupFakesForGetSeedData(); - var sut = new DocumentsBusinessLogic(_portalRepositories, _options); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act var result = await sut.GetSeedData(ValidDocumentId).ConfigureAwait(false); @@ -80,7 +83,7 @@ public async Task CreateConnectorAsync_WithInvalidId_ThrowsNotFoundException() // Arrange var invalidId = Guid.NewGuid(); SetupFakesForGetSeedData(); - var sut = new DocumentsBusinessLogic(_portalRepositories, _options); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act async Task Act() => await sut.GetSeedData(invalidId).ConfigureAwait(false); @@ -96,7 +99,7 @@ public async Task CreateConnectorAsync_WithCallFromTest_ThrowsForbiddenException // Arrange SetupFakesForGetSeedData(); _options.Value.EnableSeedEndpoint = false; - var sut = new DocumentsBusinessLogic(_portalRepositories, _options); + var sut = new DocumentsBusinessLogic(_portalRepositories, _identityService, _options); // Act async Task Act() => await sut.GetSeedData(ValidDocumentId).ConfigureAwait(false); @@ -117,7 +120,7 @@ public async Task GetDocumentAsync_WithValidData_ReturnsExpected() SetupFakesForGetDocument(); // Act - var result = await _sut.GetDocumentAsync(ValidDocumentId, _identity.CompanyId).ConfigureAwait(false); + var result = await _sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -133,7 +136,7 @@ public async Task GetDocumentAsync_WithNotExistingDocument_ThrowsNotFoundExcepti SetupFakesForGetDocument(); // Act - async Task Act() => await _sut.GetDocumentAsync(documentId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.GetDocumentAsync(documentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -145,10 +148,11 @@ public async Task GetDocumentAsync_WithWrongUser_ThrowsForbiddenException() { // Arrange var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); SetupFakesForGetDocument(); // Act - async Task Act() => await _sut.GetDocumentAsync(ValidDocumentId, identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.GetDocumentAsync(ValidDocumentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs index 8def00ec89..063e12c547 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/IdentityProviderBusinessLogicTests.cs @@ -132,7 +132,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncAllUncha _options, _logger); - var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Updated.Should().Be(0); result.Unchanged.Should().Be(numUsers); @@ -168,7 +168,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncWrongCon _options, _logger); - async Task Act() => await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be($"Only contentType {_csvSettings.ContentType} files are allowed."); @@ -217,7 +217,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncEmailCha _options, _logger); - var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Updated.Should().Be(1); result.Unchanged.Should().Be(numUsers - 1); @@ -263,7 +263,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncSharedId _options, _logger); - var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Updated.Should().Be(0); result.Unchanged.Should().Be(numUsers - 1); @@ -307,7 +307,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncOtherIdp _options, _logger); - var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Updated.Should().Be(1); result.Unchanged.Should().Be(numUsers - 1); @@ -350,7 +350,7 @@ public async Task TestUploadOwnCompanyUsersIdentityProviderLinkDataAsyncUnknownC _options, _logger); - var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, _identity.CompanyId, CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyUsersIdentityProviderLinkDataAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Updated.Should().Be(0); result.Unchanged.Should().Be(numUsers - 1); @@ -1481,7 +1481,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .Create(); @@ -1491,11 +1490,11 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns(((string?, string?, bool))default); // Act - async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1508,7 +1507,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .Create(); @@ -1518,11 +1516,11 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUs _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((null, "cl1", false)); // Act - async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1536,7 +1534,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias var identityProviderId = Guid.NewGuid(); var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .Create(); @@ -1546,11 +1543,11 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), null, false)); // Act - async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1564,7 +1561,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameC var identityProviderId = Guid.NewGuid(); var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .Create(); @@ -1574,15 +1570,15 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameC _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", false)); // Act - async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {companyId}"); + ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {_identity.CompanyId}"); } [Fact] @@ -1592,7 +1588,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithKeycloak var identityProviderId = Guid.NewGuid(); var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .Create(); @@ -1602,13 +1597,13 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithKeycloak _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId.ToString(), A._)) .Throws(new KeycloakEntityConflictException("test")); // Act - async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1622,7 +1617,6 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Ca var identityProviderId = Guid.NewGuid(); var userEntityId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.identityProviderId, identityProviderId) .With(x => x.userName, "test-user") @@ -1633,11 +1627,11 @@ public async Task CreateOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Ca _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); // Act - var result = await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data, companyId).ConfigureAwait(false); + var result = await sut.CreateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.AddProviderUserLinkToCentralUserAsync(userEntityId.ToString(), A._)) @@ -1655,7 +1649,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.userName, "user-name") .Create(); @@ -1665,11 +1658,11 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns(((string?, string?, bool))default); // Act - async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1682,7 +1675,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.userName, "user-name") .Create(); @@ -1692,11 +1684,11 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((null, "cl1", false)); // Act - async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1710,7 +1702,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.userName, "user-name") .Create(); @@ -1720,11 +1711,11 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), null, false)); // Act - async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1738,7 +1729,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.userName, "user-name") .Create(); @@ -1748,15 +1738,15 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", false)); // Act - async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data, companyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {companyId}"); + ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {_identity.CompanyId}"); } [Fact] @@ -1766,7 +1756,6 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var data = _fixture.Build() .With(x => x.userName, "user-name") .Create(); @@ -1776,11 +1765,11 @@ public async Task CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync_With _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); // Act - var result = await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data, companyId).ConfigureAwait(false); + var result = await sut.CreateOrUpdateOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) @@ -1800,18 +1789,17 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUserI // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns(((string?, string?, bool))default); // Act - async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1824,18 +1812,17 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutIamUserI // Arrange var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((null, "cl1", false)); // Act - async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1849,18 +1836,17 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutAlias_Th var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), null, false)); // Act - async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1874,22 +1860,21 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutSameComp var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", false)); // Act - async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {companyId}"); + ex.Message.Should().Be($"identityProvider {identityProviderId} is not associated with company {_identity.CompanyId}"); } [Fact] @@ -1899,20 +1884,19 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithoutExisting var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); A.CallTo(() => _provisioningManager.GetProviderUserLinkDataForCentralUserIdAsync(userEntityId.ToString())) .Returns(Enumerable.Empty().ToAsyncEnumerable()); // Act - async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1926,20 +1910,19 @@ public async Task GetOwnCompanyUserIdentityProviderLinkDataAsync_WithValid_Calls var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + 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()); // Act - var result = await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + var result = await sut.GetOwnCompanyUserIdentityProviderLinkDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert result.userName.Should().Be("user-name"); @@ -1956,20 +1939,19 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithKeycloakErro var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) .Throws(new KeycloakEntityNotFoundException("just a test")); // Act - async Task Act() => await sut.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1983,18 +1965,17 @@ public async Task DeleteOwnCompanyUserIdentityProviderDataAsync_WithValid_CallsE var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); // Act - await sut.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId, companyId).ConfigureAwait(false); + await sut.DeleteOwnCompanyUserIdentityProviderDataAsync(companyUserId, identityProviderId).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.DeleteProviderUserLinkToCentralUserAsync(userEntityId.ToString(), "cl1")) @@ -2012,18 +1993,17 @@ public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutIdentityPro var userEntityId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var companyUserId = Guid.NewGuid(); - var companyId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, _provisioningManager, _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, companyId)) + A.CallTo(() => _identityProviderRepository.GetIamUserIsOwnCompanyIdentityProviderAliasAsync(companyUserId, identityProviderId, _identity.CompanyId)) .Returns((userEntityId.ToString(), "cl1", true)); // Act - async Task Act() => await sut.GetOwnCompanyUsersIdentityProviderDataAsync(Enumerable.Empty(), companyId, false).ToListAsync().ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUsersIdentityProviderDataAsync(Enumerable.Empty(), false).ToListAsync().ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -2034,7 +2014,6 @@ public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutIdentityPro public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutMatchingIdps_ThrowsControllerArgumentException() { // Arrange - var companyId = Guid.NewGuid(); var identityProviderId = Guid.NewGuid(); var sut = new IdentityProviderBusinessLogic( _portalRepositories, @@ -2042,15 +2021,15 @@ public async Task GetOwnCompanyUsersIdentityProviderDataAsync_WithoutMatchingIdp _identityService, _options, _logger); - A.CallTo(() => _identityProviderRepository.GetOwnCompanyIdentityProviderAliasDataUntracked(companyId, A>._)) + A.CallTo(() => _identityProviderRepository.GetOwnCompanyIdentityProviderAliasDataUntracked(_identity.CompanyId, A>._)) .Returns(Enumerable.Empty<(Guid, string)>().ToAsyncEnumerable()); // Act - async Task Act() => await sut.GetOwnCompanyUsersIdentityProviderDataAsync(Enumerable.Repeat(identityProviderId, 1), companyId, false).ToListAsync().ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyUsersIdentityProviderDataAsync(Enumerable.Repeat(identityProviderId, 1), false).ToListAsync().ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); - ex.Message.Should().Be($"invalid identityProviders: [{identityProviderId}] for company {companyId} (Parameter 'identityProviderIds')"); + ex.Message.Should().Be($"invalid identityProviders: [{identityProviderId}] for company {_identity.CompanyId} (Parameter 'identityProviderIds')"); } #endregion diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs index c255a5c163..67f45502c2 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/ServiceAccountBusinessLogicTests.cs @@ -59,6 +59,7 @@ public class ServiceAccountBusinessLogicTests private readonly IPortalRepositories _portalRepositories; private readonly IFixture _fixture; private readonly IOptions _options; + private readonly IIdentityService _identityService; public ServiceAccountBusinessLogicTests() { @@ -76,6 +77,9 @@ public ServiceAccountBusinessLogicTests() _portalRepositories = A.Fake(); _serviceAccountCreation = A.Fake(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + _options = Options.Create(new ServiceAccountSettings { ClientId = ClientId @@ -90,10 +94,10 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithValidInput_ReturnsCrea // Arrange SetupCreateOwnCompanyServiceAccount(); var serviceAccountCreationInfos = new ServiceAccountCreationInfo("TheName", "Just a short description", IamClientAuthMethod.SECRET, Enumerable.Repeat(UserRoleId1, 1)); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation, _identityService); // Act - var result = await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -105,12 +109,13 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithInvalidUser_NotFoundEx { // Arrange 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)); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation, _identityService); // Act - async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos, identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -123,10 +128,10 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithEmptyName_ThrowsContro // Arrange SetupCreateOwnCompanyServiceAccount(); var serviceAccountCreationInfos = new ServiceAccountCreationInfo(string.Empty, "Just a short description", IamClientAuthMethod.SECRET, Enumerable.Repeat(UserRoleId1, 1)); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation, _identityService); // Act - async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -140,10 +145,10 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithInvalidIamClientAuthMe // Arrange SetupCreateOwnCompanyServiceAccount(); var serviceAccountCreationInfos = new ServiceAccountCreationInfo("TheName", "Just a short description", IamClientAuthMethod.JWT, Enumerable.Repeat(UserRoleId1, 1)); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation, _identityService); // Act - async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -158,10 +163,10 @@ public async Task CreateOwnCompanyServiceAccountAsync_WithInvalidUserRoleId_Thro var wrongUserRoleId = Guid.NewGuid(); SetupCreateOwnCompanyServiceAccount(); var serviceAccountCreationInfos = new ServiceAccountCreationInfo("TheName", "Just a short description", IamClientAuthMethod.SECRET, new[] { UserRoleId1, wrongUserRoleId }); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, _serviceAccountCreation, _identityService); // Act - async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyServiceAccountAsync(serviceAccountCreationInfos).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -178,10 +183,10 @@ public async Task GetOwnCompanyServiceAccountDetailsAsync_WithValidInput_GetsAll { // Arrange SetupGetOwnCompanyServiceAccountDetails(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - var result = await sut.GetOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.GetOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -194,10 +199,11 @@ public async Task GetOwnCompanyServiceAccountDetailsAsync_WithInvalidUser_NotFou // Arrange SetupGetOwnCompanyServiceAccountDetails(); var invalidCompanyId = Guid.NewGuid(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = invalidCompanyId }); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.GetOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, invalidCompanyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -210,10 +216,10 @@ public async Task GetOwnCompanyServiceAccountDetailsAsync_WithInvalidServiceAcco // Arrange SetupGetOwnCompanyServiceAccountDetails(); var invalidServiceAccountId = Guid.NewGuid(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.GetOwnCompanyServiceAccountDetailsAsync(invalidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnCompanyServiceAccountDetailsAsync(invalidServiceAccountId).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -229,10 +235,10 @@ public async Task ResetOwnCompanyServiceAccountSecretAsync_WithValidInput_GetsAl { // Arrange SetupResetOwnCompanyServiceAccountSecret(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - var result = await sut.ResetOwnCompanyServiceAccountSecretAsync(ValidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.ResetOwnCompanyServiceAccountSecretAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -245,10 +251,11 @@ public async Task ResetOwnCompanyServiceAccountSecretAsync_WithInvalidUser_NotFo // Arrange SetupResetOwnCompanyServiceAccountSecret(); var invalidUser = _fixture.Create(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + A.CallTo(() => _identityService.IdentityData).Returns(invalidUser); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.ResetOwnCompanyServiceAccountSecretAsync(ValidServiceAccountId, invalidUser.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.ResetOwnCompanyServiceAccountSecretAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -261,10 +268,10 @@ public async Task ResetOwnCompanyServiceAccountSecretAsync_WithInvalidServiceAcc // Arrange SetupResetOwnCompanyServiceAccountSecret(); var invalidServiceAccountId = Guid.NewGuid(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.ResetOwnCompanyServiceAccountSecretAsync(invalidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.ResetOwnCompanyServiceAccountSecretAsync(invalidServiceAccountId).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -281,10 +288,10 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithValidData_Retur // Arrange SetupUpdateOwnCompanyServiceAccountDetails(); var data = new ServiceAccountEditableDetails(ValidServiceAccountId, "new name", "changed description", IamClientAuthMethod.SECRET); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - var result = await sut.UpdateOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, data, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.UpdateOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, data).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -297,10 +304,10 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithInvalidAuthMeth // Arrange SetupUpdateOwnCompanyServiceAccountDetails(); var data = new ServiceAccountEditableDetails(ValidServiceAccountId, "new name", "changed description", IamClientAuthMethod.JWT); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(ValidServiceAccountId, data).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -313,10 +320,10 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithDifferentServic // Arrange SetupUpdateOwnCompanyServiceAccountDetails(); var data = new ServiceAccountEditableDetails(ValidServiceAccountId, "new name", "changed description", IamClientAuthMethod.SECRET); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(Guid.NewGuid(), data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(Guid.NewGuid(), data).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -332,10 +339,10 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithNotExistingServ A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(invalidServiceAccountId, _identity.CompanyId)) .Returns((CompanyServiceAccountWithRoleDataClientId?)null); var data = new ServiceAccountEditableDetails(invalidServiceAccountId, "new name", "changed description", IamClientAuthMethod.SECRET); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(invalidServiceAccountId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(invalidServiceAccountId, data).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -353,10 +360,10 @@ public async Task UpdateOwnCompanyServiceAccountDetailsAsync_WithInactiveService A.CallTo(() => _serviceAccountRepository.GetOwnCompanyServiceAccountWithIamClientIdAsync(InactiveServiceAccount, _identity.CompanyId)) .Returns(inactive); var data = new ServiceAccountEditableDetails(InactiveServiceAccount, "new name", "changed description", IamClientAuthMethod.SECRET); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(InactiveServiceAccount, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.UpdateOwnCompanyServiceAccountDetailsAsync(InactiveServiceAccount, data).ConfigureAwait(false); // Assert var exception = await Assert.ThrowsAsync(Act); @@ -376,10 +383,10 @@ public async Task GetOwnCompanyServiceAccountsDataAsync_GetsExpectedData() .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); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - var result = await sut.GetOwnCompanyServiceAccountsDataAsync(1, 10, _identity.CompanyId, null, null).ConfigureAwait(false); + var result = await sut.GetOwnCompanyServiceAccountsDataAsync(1, 10, null, null).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -397,10 +404,10 @@ public async Task DeleteOwnCompanyServiceAccountAsync_WithNotExistingServiceAcco var serviceAccountId = Guid.NewGuid(); SetupDeleteOwnCompanyServiceAccount(false, false); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(serviceAccountId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(serviceAccountId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -413,10 +420,10 @@ public async Task DeleteOwnCompanyServiceAccountAsync_WithExistingOfferSubscript // Arrange SetupDeleteOwnCompanyServiceAccountForValidOfferSubscription(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -429,10 +436,10 @@ public async Task DeleteOwnCompanyServiceAccountAsync_WithInvalidConnectorStatus // Arrange SetupDeleteOwnCompanyServiceAccountForInvalidConnectorStatus(); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -455,10 +462,10 @@ public async Task DeleteOwnCompanyServiceAccountAsync_WithoutClient_CallsExpecte .With(x => x.CompanyServiceAccountId, ValidServiceAccountId) .Create(); SetupDeleteOwnCompanyServiceAccount(withServiceAccount, withClient, connector, identity); - var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + var sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId, _identity.CompanyId).ConfigureAwait(false); + await sut.DeleteOwnCompanyServiceAccountAsync(ValidServiceAccountId).ConfigureAwait(false); // Assert if (withClient) @@ -491,10 +498,10 @@ public async Task GetServiceAccountRolesAsync_GetsExpectedData() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRolesRepository); - IServiceAccountBusinessLogic sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!); + IServiceAccountBusinessLogic sut = new ServiceAccountBusinessLogic(_provisioningManager, _portalRepositories, _options, null!, _identityService); // Act - var result = await sut.GetServiceAccountRolesAsync(_identity.CompanyId, null).ToListAsync().ConfigureAwait(false); + var result = await sut.GetServiceAccountRolesAsync(null).ToListAsync().ConfigureAwait(false); // Assert A.CallTo(() => _userRolesRepository.GetServiceAccountRolesAsync(_identity.CompanyId, ClientId, A._)).MustHaveHappenedOnceExactly(); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs index efd4e2d466..a5deb6ffb6 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/SubscriptionConfigurationBusinessLogicTests.cs @@ -47,6 +47,7 @@ public class SubscriptionConfigurationBusinessLogicTests private readonly IPortalRepositories _portalRepositories; private readonly IFixture _fixture; private readonly ISubscriptionConfigurationBusinessLogic _sut; + private readonly IIdentityService _identityService; public SubscriptionConfigurationBusinessLogicTests() { @@ -62,11 +63,14 @@ public SubscriptionConfigurationBusinessLogicTests() _serviceProviderDetails = new HashSet(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + A.CallTo(() => _portalRepositories.GetInstance()).Returns(_companyRepository); A.CallTo(() => _portalRepositories.GetInstance()) .Returns(_offerSubscriptionsRepository); - _sut = new SubscriptionConfigurationBusinessLogic(_offerSubscriptionProcessService, _portalRepositories); + _sut = new SubscriptionConfigurationBusinessLogic(_offerSubscriptionProcessService, _portalRepositories, _identityService); } #region GetProcessStepsForSubscription @@ -189,7 +193,7 @@ public async Task SetProviderCompanyDetailsAsync_EmptyProviderDetailsId_ReturnsE .Returns((Guid.Empty, null!)); // Act - await _sut.SetProviderCompanyDetailsAsync(providerDetailData, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetProviderCompanyDetailsAsync(providerDetailData).ConfigureAwait(false); // Assert A.CallTo(() => _companyRepository.CreateProviderCompanyDetail(A._, A._, A>._)).MustHaveHappened(); @@ -224,7 +228,7 @@ public async Task SetProviderCompanyDetailsAsync_WithServiceProviderDetailsId_Re }); //Act - await _sut.SetProviderCompanyDetailsAsync(providerDetailData, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetProviderCompanyDetailsAsync(providerDetailData).ConfigureAwait(false); //Assert A.CallTo(() => _companyRepository.CreateProviderCompanyDetail(A._, A._, null)).MustNotHaveHappened(); @@ -240,11 +244,12 @@ public async Task SetProviderCompanyDetailsAsync_WithServiceProviderDetailsId_Re public async Task SetServiceProviderCompanyDetailsAsync_WithUnknownUser_ThrowsException() { //Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); SetupProviderCompanyDetails(); var providerDetailData = new ProviderDetailData("https://www.service-url.com", null); //Act - async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData, Guid.NewGuid()).ConfigureAwait(false); + async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData).ConfigureAwait(false); //Assert await Assert.ThrowsAsync(Action); @@ -256,11 +261,12 @@ public async Task SetServiceProviderCompanyDetailsAsync_WithUnknownUser_ThrowsEx public async Task SetServiceProviderCompanyDetailsAsync_WithNotServiceProvider_ThrowsException() { //Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_noServiceProviderIdentity); SetupProviderCompanyDetails(); var providerDetailData = new ProviderDetailData("https://www.service-url.com", null); //Act - async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData, _noServiceProviderIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData).ConfigureAwait(false); //Assert var ex = await Assert.ThrowsAsync(Action); @@ -282,7 +288,7 @@ public async Task SetServiceProviderCompanyDetailsAsync_WithInvalidUrl_ThrowsExc var providerDetailData = new ProviderDetailData(url!, null); //Act - async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData, _identity.CompanyId).ConfigureAwait(false); + async Task Action() => await _sut.SetProviderCompanyDetailsAsync(providerDetailData).ConfigureAwait(false); //Assert var ex = await Assert.ThrowsAsync(Action); @@ -302,7 +308,7 @@ public async Task GetProviderCompanyDetailsAsync_WithValidUser_ReturnsDetails() SetupProviderCompanyDetails(); //Act - var result = await _sut.GetProviderCompanyDetailsAsync(_identity.CompanyId).ConfigureAwait(false); + var result = await _sut.GetProviderCompanyDetailsAsync().ConfigureAwait(false); //Assert result.Should().NotBeNull(); @@ -312,10 +318,11 @@ public async Task GetProviderCompanyDetailsAsync_WithValidUser_ReturnsDetails() public async Task GetProviderCompanyDetailsAsync_WithInvalidUser_ThrowsException() { //Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); SetupProviderCompanyDetails(); //Act - async Task Action() => await _sut.GetProviderCompanyDetailsAsync(Guid.NewGuid()).ConfigureAwait(false); + async Task Action() => await _sut.GetProviderCompanyDetailsAsync().ConfigureAwait(false); //Assert await Assert.ThrowsAsync(Action); @@ -330,7 +337,7 @@ public async Task GetProviderCompanyDetailsAsync_WithInvalidServiceProvider_Thro .ReturnsLazily(() => (new ProviderDetailReturnData(Guid.NewGuid(), Guid.NewGuid(), "https://new-test-service.de"), false)); //Act - async Task Action() => await _sut.GetProviderCompanyDetailsAsync(_identity.CompanyId).ConfigureAwait(false); + async Task Action() => await _sut.GetProviderCompanyDetailsAsync().ConfigureAwait(false); //Assert await Assert.ThrowsAsync(Action); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs index 41703ae599..31aba10d8f 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/UserBusinessLogicTests.cs @@ -73,6 +73,7 @@ public class UserBusinessLogicTests private readonly Func _companyUserSelectFunction; private readonly Exception _error; private readonly UserSettings _settings; + private readonly IIdentityService _identityService; public UserBusinessLogicTests() { @@ -113,6 +114,9 @@ public UserBusinessLogicTests() _processLine = A.Fake>(); _companyUserSelectFunction = A.Fake>(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + _settings = new UserSettings { Portal = new UserSetting @@ -147,11 +151,12 @@ public async Task TestUserCreationAllSuccess() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - var result = await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + var result = await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); A.CallTo(() => _mockLogger.Log(A.That.IsEqualTo(LogLevel.Error), A._, A._)).MustNotHaveHappened(); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappenedANumberOfTimesMatching(times => times == userList.Count()); @@ -185,11 +190,12 @@ public async Task TestUserCreation_NoUserNameAndEmail_Throws() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - var Act = async () => await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + var Act = async () => await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -217,11 +223,12 @@ public async Task TestUserCreation_NoRoles_Throws() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - var Act = async () => await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + var Act = async () => await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -260,11 +267,12 @@ public async Task TestUserCreationCreationError() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - var result = await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + var result = await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(u => u.FirstName == userCreationInfo.firstName && @@ -306,11 +314,12 @@ public async Task TestUserCreationCreationThrows() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - async Task Act() => await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + async Task Act() => await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -350,11 +359,12 @@ public async Task TestUserCreationSendMailError() _userProvisioningService, null!, _portalRepositories, + _identityService, _mailingService, _logger, _options); - var result = await sut.CreateOwnCompanyUsersAsync(userList, (_identity.UserId, _identity.CompanyId)).ToListAsync().ConfigureAwait(false); + var result = await sut.CreateOwnCompanyUsersAsync(userList).ToListAsync().ConfigureAwait(false); A.CallTo(() => _mockLogger.Log(A.That.IsEqualTo(LogLevel.Error), A._, A._)).MustHaveHappenedOnceExactly(); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappenedANumberOfTimesMatching(times => times == 5); @@ -379,11 +389,12 @@ public async Task TestCreateOwnCompanyIdpUserAsyncSuccess() _userProvisioningService, null!, null!, + _identityService, _mailingService, _logger, _options); - var result = await sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + var result = await sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp).ConfigureAwait(false); result.Should().NotBe(Guid.Empty); A.CallTo(() => _mailingService.SendMails(A.That.IsEqualTo(userCreationInfoIdp.Email), A>.That.Matches(x => x["companyName"] == _displayName), A>._)).MustHaveHappened(); A.CallTo(() => _mockLogger.Log(A.That.IsEqualTo(LogLevel.Error), A._, A._)).MustNotHaveHappened(); @@ -406,11 +417,12 @@ public async Task TestCreateOwnCompanyIdpUserNoRolesThrowsArgumentException() _userProvisioningService, null!, null!, + _identityService, _mailingService, _logger, _options); - Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be("at least one role must be specified (Parameter 'Roles')"); @@ -435,11 +447,12 @@ public async Task TestCreateOwnCompanyIdpUserAsyncError() _userProvisioningService, null!, null!, + _identityService, _mailingService, _logger, _options); - Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be(_error.Message); @@ -460,11 +473,12 @@ public async Task TestCreateOwnCompanyIdpUserAsyncThrows() _userProvisioningService, null!, null!, + _identityService, _mailingService, _logger, _options); - Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be(_error.Message); @@ -485,11 +499,12 @@ public async Task TestCreateOwnCompanyIdpUserAsyncMailingErrorLogs() _userProvisioningService, null!, null!, + _identityService, _mailingService, _logger, _options); - var result = await sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + var result = await sut.CreateOwnCompanyIdpUserAsync(_identityProviderId, userCreationInfoIdp).ConfigureAwait(false); result.Should().NotBe(Guid.Empty); A.CallTo(() => _mailingService.SendMails(A._, A>._, A>._)).MustHaveHappened(); A.CallTo(() => _mockLogger.Log(A.That.IsEqualTo(LogLevel.Error), A._, A._)).MustHaveHappened(); @@ -509,6 +524,7 @@ public async Task TestDeleteOwnUserSuccess() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options @@ -528,7 +544,7 @@ public async Task TestDeleteOwnUserSuccess() modify.Invoke(_companyUser); }); - await sut.DeleteOwnUserAsync(_companyUserId, _identity.UserId).ConfigureAwait(false); + await sut.DeleteOwnUserAsync(_companyUserId).ConfigureAwait(false); A.CallTo(() => _provisioningManager.GetProviderUserIdForCentralUserIdAsync(A._, A._)).MustHaveHappened(); A.CallTo(() => _provisioningManager.DeleteSharedRealmUserAsync(A._, A._)).MustHaveHappened(); @@ -548,6 +564,7 @@ public async Task TestDeleteOwnUserInvalidUserThrows() SetupFakesForUserDeletion(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _userRepository.GetSharedIdentityProviderUserAccountDataUntrackedAsync(identity.UserId)) .Returns(((string?, CompanyUserAccountData))default!); @@ -557,12 +574,13 @@ public async Task TestDeleteOwnUserInvalidUserThrows() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - Task Act() => sut.DeleteOwnUserAsync(identity.UserId, identity.UserId); + Task Act() => sut.DeleteOwnUserAsync(identity.UserId); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be($"user {identity.UserId} does not exist"); @@ -579,18 +597,20 @@ public async Task TestDeleteOwnUserInvalidCompanyUserThrows() SetupFakesForUserDeletion(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); var sut = new UserBusinessLogic( _provisioningManager, null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - Task Act() => sut.DeleteOwnUserAsync(_companyUserId, identity.UserId); + 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}"); @@ -609,11 +629,13 @@ public async Task TestDeleteOwnUserInvalidCompanyUserThrows() public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -625,7 +647,7 @@ public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase( "Buyer", "Supplier" }); - await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo, _createdCentralIdentity.CompanyId).ConfigureAwait(false); + await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo).ConfigureAwait(false); // Assert _companyUserAssignedRole.Should().HaveCount(2); @@ -635,11 +657,13 @@ public async Task ModifyUserRoleAsync_WithTwoNewRoles_AddsTwoRolesToTheDatabase( public async Task ModifyUserRoleAsync_WithOneRoleToDelete_DeletesTheRole() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -648,7 +672,7 @@ public async Task ModifyUserRoleAsync_WithOneRoleToDelete_DeletesTheRole() { "Company Admin" }); - await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo, _adminIdentity.CompanyId).ConfigureAwait(false); + await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo).ConfigureAwait(false); // Assert A.CallTo(() => _portalRepositories.RemoveRange(A>.That.Matches(x => x.Count() == 1))).MustHaveHappenedOnceExactly(); @@ -658,11 +682,13 @@ public async Task ModifyUserRoleAsync_WithOneRoleToDelete_DeletesTheRole() public async Task ModifyUserRoleAsync_WithNotExistingRole_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -672,7 +698,7 @@ public async Task ModifyUserRoleAsync_WithNotExistingRole_ThrowsException() "NotExisting", "Buyer" }); - async Task Action() => await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -683,11 +709,13 @@ public async Task ModifyUserRoleAsync_WithNotExistingRole_ThrowsException() public async Task ModifyUserRoleAsync_WithNotFoundCompanyUser_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -698,7 +726,7 @@ public async Task ModifyUserRoleAsync_WithNotFoundCompanyUser_ThrowsException() "Buyer", "Supplier" }); - async Task Action() => await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyUserRoleAsync(_validOfferId, userRoleInfo).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -709,11 +737,13 @@ public async Task ModifyUserRoleAsync_WithNotFoundCompanyUser_ThrowsException() public async Task ModifyUserRoleAsync_WithInvalidOfferId_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); var invalidAppId = Guid.NewGuid(); @@ -725,7 +755,7 @@ public async Task ModifyUserRoleAsync_WithInvalidOfferId_ThrowsException() "Buyer", "Supplier" }); - async Task Action() => await sut.ModifyUserRoleAsync(invalidAppId, userRoleInfo, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyUserRoleAsync(invalidAppId, userRoleInfo).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -741,11 +771,13 @@ public async Task ModifyCoreOfferUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTh { // Arrange var notifications = new List(); + A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); SetupFakesForUserRoleModification(notifications); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -757,7 +789,7 @@ public async Task ModifyCoreOfferUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTh "Buyer", "Supplier" }; - await sut.ModifyCoreOfferUserRolesAsync(_validOfferId, _companyUserId, userRoles, _createdCentralIdentity.CompanyId).ConfigureAwait(false); + await sut.ModifyCoreOfferUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert _companyUserAssignedRole.Should().HaveCount(2); @@ -775,11 +807,13 @@ public async Task ModifyAppUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTheDatab { // Arrange var notifications = new List(); + A.CallTo(() => _identityService.IdentityData).Returns(_createdCentralIdentity); SetupFakesForUserRoleModification(notifications); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -791,7 +825,7 @@ public async Task ModifyAppUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTheDatab "Buyer", "Supplier" }; - await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles, _createdCentralIdentity.CompanyId).ConfigureAwait(false); + await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert _companyUserAssignedRole.Should().HaveCount(2); @@ -804,12 +838,14 @@ public async Task ModifyAppUserRolesAsync_WithTwoNewRoles_AddsTwoRolesToTheDatab public async Task ModifyAppUserRolesAsync_WithOneRoleToDelete_DeletesTheRole() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); var notifications = new List(); SetupFakesForUserRoleModification(notifications); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -818,7 +854,7 @@ public async Task ModifyAppUserRolesAsync_WithOneRoleToDelete_DeletesTheRole() { "Company Admin" }; - await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles, _adminIdentity.CompanyId).ConfigureAwait(false); + await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert A.CallTo(() => _portalRepositories.RemoveRange(A>.That.Matches(x => x.Count() == 1))).MustHaveHappenedOnceExactly(); @@ -831,11 +867,13 @@ public async Task ModifyAppUserRolesAsync_WithOneRoleToDelete_DeletesTheRole() public async Task ModifyAppUserRolesAsync_WithNotExistingRole_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -845,7 +883,7 @@ public async Task ModifyAppUserRolesAsync_WithNotExistingRole_ThrowsException() "NotExisting", "Buyer" }; - async Task Action() => await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyAppUserRolesAsync(_validOfferId, _companyUserId, userRoles).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -858,11 +896,13 @@ public async Task ModifyAppUserRolesAsync_WithNotExistingRole_ThrowsException() public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -874,7 +914,7 @@ public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsExceptio "Buyer", "Supplier" }; - async Task Action() => await sut.ModifyAppUserRolesAsync(_validOfferId, companyUserId, userRoles, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyAppUserRolesAsync(_validOfferId, companyUserId, userRoles).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -887,11 +927,13 @@ public async Task ModifyAppUserRolesAsync_WithNotFoundCompanyUser_ThrowsExceptio public async Task ModifyAppUserRolesAsync_WithInvalidOfferId_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); var invalidAppId = Guid.NewGuid(); @@ -903,7 +945,7 @@ public async Task ModifyAppUserRolesAsync_WithInvalidOfferId_ThrowsException() "Buyer", "Supplier" }; - async Task Action() => await sut.ModifyAppUserRolesAsync(invalidAppId, _companyUserId, userRoles, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyAppUserRolesAsync(invalidAppId, _companyUserId, userRoles).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -916,11 +958,13 @@ public async Task ModifyAppUserRolesAsync_WithInvalidOfferId_ThrowsException() public async Task ModifyAppUserRolesAsync_WithoutOfferName_ThrowsException() { // Arrange + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); SetupFakesForUserRoleModification(); var sut = new UserRolesBusinessLogic( _portalRepositories, _provisioningManager, + _identityService, Options.Create(_settings) ); @@ -931,7 +975,7 @@ public async Task ModifyAppUserRolesAsync_WithoutOfferName_ThrowsException() "Buyer", "Supplier" }; - async Task Action() => await sut.ModifyAppUserRolesAsync(_offerWithoutNameId, _companyUserId, userRoles, _adminIdentity.CompanyId).ConfigureAwait(false); + async Task Action() => await sut.ModifyAppUserRolesAsync(_offerWithoutNameId, _companyUserId, userRoles).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -956,12 +1000,13 @@ public async Task TestDeleteOwnCompanyUsersAsyncSuccess() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds, _identity.CompanyId).ToListAsync().ConfigureAwait(false); + var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds).ToListAsync().ConfigureAwait(false); var expectedCount = companyUserIds.Count(); result.Should().HaveCount(expectedCount); @@ -988,12 +1033,13 @@ public async Task TestDeleteOwnCompanyUsersAsyncNoSharedIdpSuccess() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds, _identity.CompanyId).ToListAsync().ConfigureAwait(false); + var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds).ToListAsync().ConfigureAwait(false); var expectedCount = companyUserIds.Count(); result.Should().HaveCount(expectedCount); @@ -1046,12 +1092,13 @@ public async Task TestDeleteOwnCompanyUsersAsyncError() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds, _identity.CompanyId).ToListAsync().ConfigureAwait(false); + var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds).ToListAsync().ConfigureAwait(false); result.Should().HaveCount(companyUserIds.Length - 1); result.Should().Match(r => Enumerable.SequenceEqual(r, companyUserIds.Take(2).Concat(companyUserIds.Skip(3)))); @@ -1100,12 +1147,13 @@ public async Task TestDeleteOwnCompanyUsersAsyncNoSharedIdpError() null!, null!, _portalRepositories, + _identityService, null!, _logger, _options ); - var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds, _identity.CompanyId).ToListAsync().ConfigureAwait(false); + var result = await sut.DeleteOwnCompanyUsersAsync(companyUserIds).ToListAsync().ConfigureAwait(false); result.Should().HaveCount(companyUserIds.Length - 1); result.Should().Match(r => Enumerable.SequenceEqual(r, companyUserIds.Take(2).Concat(companyUserIds.Skip(3)))); @@ -1131,16 +1179,16 @@ 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(() => _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)))); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act var results = await sut.GetOwnCompanyAppUsersAsync( appId, - userId, 0, 10, new CompanyUserFilter(null, null, null, null, null)).ConfigureAwait(false); @@ -1157,16 +1205,16 @@ 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(() => _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)))); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act var results = await sut.GetOwnCompanyAppUsersAsync( appId, - userId, 1, 3, new CompanyUserFilter(null, null, null, null, null)).ConfigureAwait(false); @@ -1186,14 +1234,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithNonExistingCompanyUser_ThrowsNo // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - var adminUserId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) .Returns(((string?, bool, bool))default); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act - async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, (_adminIdentity.UserId, _adminIdentity.CompanyId)).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1206,14 +1254,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithUnassignedBusinessPartner_Throw // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - var adminUserId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) .Returns((string.Empty, false, false)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act - async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, (_adminIdentity.UserId, _adminIdentity.CompanyId)).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1226,14 +1274,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithoutUserForBpn_ThrowsArgumentExc // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - var adminUserId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) .Returns(((string?)null, true, false)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act - async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, (_adminIdentity.UserId, _adminIdentity.CompanyId)).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1246,14 +1294,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithInvalidUser_ThrowsForbiddenExce // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - var adminUserId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) .Returns((Guid.NewGuid().ToString(), true, false)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(null!, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act - async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, (_adminIdentity.UserId, _adminIdentity.CompanyId)).ConfigureAwait(false); + async Task Act() => await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -1266,14 +1314,14 @@ public async Task GetOwnCompanyAppUsersAsync_WithValidData_ThrowsForbiddenExcept // Arrange var companyUserId = _fixture.Create(); var businessPartnerNumber = _fixture.Create(); - var adminUserId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_adminIdentity); A.CallTo(() => _userBusinessPartnerRepository.GetOwnCompanyUserWithAssignedBusinessPartnerNumbersAsync(companyUserId, _adminIdentity.CompanyId, businessPartnerNumber)) .Returns((Guid.NewGuid().ToString(), true, true)); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userBusinessPartnerRepository); - var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, null!, null!, A.Fake>()); + var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, null!, A.Fake>()); // Act - await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber, (_adminIdentity.UserId, _adminIdentity.CompanyId)).ConfigureAwait(false); + await sut.DeleteOwnUserBusinessPartnerNumbersAsync(companyUserId, businessPartnerNumber).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.DeleteCentralUserBusinessPartnerNumberAsync(A._, A._)).MustHaveHappenedOnceExactly(); @@ -1291,15 +1339,16 @@ public async Task GetOwnUserDetails_ReturnsExpected() var companyOwnUserDetails = _fixture.Create(); var identity = _fixture.Create(); var userRoleIds = new[] { _fixture.Create(), _fixture.Create() }; + A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A>._)) .Returns(userRoleIds.ToAsyncEnumerable()); A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(A._, A>._)) .Returns(companyOwnUserDetails); - var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, null!, _logger, _options); + var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, _logger, _options); // Act - var result = await sut.GetOwnUserDetails(identity.UserId).ConfigureAwait(false); + var result = await sut.GetOwnUserDetails().ConfigureAwait(false); // Assert A.CallTo(() => _userRolesRepository.GetUserRoleIdsUntrackedAsync(A> @@ -1313,13 +1362,13 @@ public async Task GetOwnUserDetails_ThrowsNotFoundException() { // Arrange var identity = _fixture.Create(); - + A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _userRepository.GetUserDetailsUntrackedAsync(identity.UserId, A>._)) .Returns((CompanyOwnUserDetails)default!); - var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, null!, _logger, _options); + var sut = new UserBusinessLogic(_provisioningManager, null!, null!, _portalRepositories, _identityService, null!, _logger, _options); // Act - async Task Act() => await sut.GetOwnUserDetails(identity.UserId).ConfigureAwait(false); + async Task Act() => await sut.GetOwnUserDetails().ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); diff --git a/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs b/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs index 468e09b539..394d62d3df 100644 --- a/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs +++ b/tests/administration/Administration.Service.Tests/BusinessLogic/UserUploadBusinessLogicTests.cs @@ -39,8 +39,6 @@ public class UserUploadBusinessLogicTests private readonly IOptions _options; private readonly IFormFile _document; private readonly Guid _identityProviderId; - private readonly string _iamUserId; - private readonly string _clientId; private readonly IdentityData _identity; private readonly IMailingService _mailingService; private readonly UserSettings _settings; @@ -48,6 +46,7 @@ public class UserUploadBusinessLogicTests private readonly Func _processLine; private readonly Exception _error; private readonly Random _random; + private readonly IIdentityService _identityService; public UserUploadBusinessLogicTests() { @@ -64,11 +63,13 @@ public UserUploadBusinessLogicTests() _document = A.Fake(); _identityProviderId = _fixture.Create(); - _iamUserId = _fixture.Create(); - _clientId = _fixture.Create(); - _settings = _fixture.Build().With(x => x.Portal, _fixture.Build().With(x => x.KeycloakClientID, _clientId).Create()).Create(); + 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(_iamUserId, Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); _processLine = A.Fake>(); @@ -81,9 +82,9 @@ public async Task TestSetup() { SetupFakes(new[] { HeaderLine() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _userProvisioningService.GetCompanyNameIdpAliasData(A.That.IsEqualTo(_identityProviderId), _identity.UserId)).MustHaveHappened(); result.Should().NotBeNull(); @@ -106,9 +107,9 @@ public async Task TestUserCreationAllSuccess() NextLine() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); result.Should().NotBeNull(); result.Created.Should().Be(5); @@ -132,9 +133,9 @@ public async Task TestUserCreationHeaderParsingThrows() NextLine() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - async Task Act() => await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + async Task Act() => await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be($"invalid format: expected 'FirstName', got '{invalidHeader}' (Parameter 'document')"); @@ -162,9 +163,9 @@ public async Task TestUserCreationCreationError() .With(x => x.Error, _error) .Create()); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatches(info, creationInfo)))).MustHaveHappened(); @@ -193,9 +194,9 @@ public async Task TestUserCreationCreationNoRolesError() NextLine() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatches(info, creationInfo)))).MustNotHaveHappened(); A.CallTo(() => _processLine(A.That.Not.Matches(info => CreationInfoMatches(info, creationInfo)))).MustHaveHappened(4, Times.Exactly); @@ -226,9 +227,9 @@ public async Task TestUserCreationMailError() A.CallTo(() => _mailingService.SendMails(creationInfo.Email, A>._, A>._)) .ThrowsAsync(_error); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatches(info, creationInfo)))).MustHaveHappened(); @@ -253,9 +254,9 @@ public async Task TestUserCreationParsingError() NextLine() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); result.Should().NotBeNull(); result.Created.Should().Be(4); @@ -283,9 +284,9 @@ public async Task TestUserCreationCreationThrows() A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatches(info, creationInfo)))) .Throws(_error); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanyIdpUsersAsync(_identityProviderId, _document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatches(info, creationInfo)))).MustHaveHappened(); @@ -307,9 +308,9 @@ public async Task TestSetupSharedIdp() { SetupFakes(new[] { HeaderLineSharedIdp() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _userProvisioningService.GetCompanyNameSharedIdpAliasData(_identity.UserId, A._)).MustHaveHappened(); result.Should().NotBeNull(); @@ -331,9 +332,9 @@ public async Task TestUserCreationSharedIdpAllSuccess() NextLineSharedIdp() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Should().NotBeNull(); result.Created.Should().Be(5); @@ -357,9 +358,9 @@ public async Task TestUserCreationSharedIdpHeaderParsingThrows() NextLineSharedIdp() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - async Task Act() => await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + async Task Act() => await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be($"invalid format: expected 'FirstName', got '{invalidHeader}' (Parameter 'document')"); @@ -381,9 +382,9 @@ public async Task TestUserCreationSharedIdpNoRolesError() NextLineSharedIdp(), }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatchesSharedIdp(info, creationInfo)))).MustNotHaveHappened(); A.CallTo(() => _processLine(A.That.Not.Matches(info => CreationInfoMatchesSharedIdp(info, creationInfo)))).MustHaveHappened(4, Times.Exactly); @@ -418,9 +419,9 @@ public async Task TestUserCreationSharedIdpCreationError() .With(x => x.Error, _error) .Create()); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatchesSharedIdp(info, creationInfo)))).MustHaveHappened(); @@ -444,9 +445,9 @@ public async Task TestUserCreationSharedIdpParsingError() NextLineSharedIdp() }); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); result.Should().NotBeNull(); result.Created.Should().Be(4); @@ -473,9 +474,9 @@ public async Task TestUserCreationSharedIdpCreationThrows() A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatchesSharedIdp(info, creationInfo)))) .Throws(_error); - var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _options); + var sut = new UserUploadBusinessLogic(_userProvisioningService, _mailingService, _identityService, _options); - var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + var result = await sut.UploadOwnCompanySharedIdpUsersAsync(_document, CancellationToken.None).ConfigureAwait(false); A.CallTo(() => _processLine(A.That.Matches(info => CreationInfoMatchesSharedIdp(info, creationInfo)))).MustHaveHappened(); diff --git a/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs index 41fc8540fa..2429d18f09 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/DocumentsControllerTests.cs @@ -52,14 +52,14 @@ public async Task GetDocumentContentFileAsync_WithValidData_ReturnsOk() const string contentType = "application/pdf"; var id = Guid.NewGuid(); var content = Encoding.UTF8.GetBytes("This is just test content"); - A.CallTo(() => _logic.GetDocumentAsync(A._, A._)) + A.CallTo(() => _logic.GetDocumentAsync(A._)) .Returns((fileName, content, contentType)); //Act await this._controller.GetDocumentContentFileAsync(id).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.GetDocumentAsync(id, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetDocumentAsync(id)).MustHaveHappenedOnceExactly(); } [Fact] diff --git a/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs index 7575a1d485..74a1ddd582 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/ServiceAccountControllerTests.cs @@ -59,14 +59,14 @@ public async Task ExecuteCompanyUserCreation_CallsExpected() .With(x => x.ServiceAccountId, serviceAccountId) .Create(); var data = _fixture.Create(); - A.CallTo(() => _logic.CreateOwnCompanyServiceAccountAsync(A._, A._)) + A.CallTo(() => _logic.CreateOwnCompanyServiceAccountAsync(A._)) .Returns(responseData); // Act var result = await _controller.ExecuteCompanyUserCreation(data).ConfigureAwait(false); // Assert - A.CallTo(() => _logic.CreateOwnCompanyServiceAccountAsync(data, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.CreateOwnCompanyServiceAccountAsync(data)).MustHaveHappenedOnceExactly(); result.Should().NotBeNull(); result.Should().BeOfType(); @@ -80,14 +80,14 @@ public async Task GetServiceAccountRolesAsync_CallsExpected() { // Arrange var data = _fixture.CreateMany(5); - A.CallTo(() => _logic.GetServiceAccountRolesAsync(A._, A._)) + A.CallTo(() => _logic.GetServiceAccountRolesAsync(A._)) .Returns(data.ToAsyncEnumerable()); // Act var result = await _controller.GetServiceAccountRolesAsync().ToListAsync().ConfigureAwait(false); // Assert - A.CallTo(() => _logic.GetServiceAccountRolesAsync(_identity.CompanyId, null)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetServiceAccountRolesAsync(null)).MustHaveHappenedOnceExactly(); result.Should().NotBeNull(); result.Should().HaveCount(5); diff --git a/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs b/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs index 5a0a7008f6..76a87ae60a 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/SubscriptionConfigurationControllerTests.cs @@ -114,7 +114,7 @@ public async Task SetCompanyDetail_WithValidData_ReturnsNoContent() var result = await this._controller.SetProviderCompanyDetail(data).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.SetProviderCompanyDetailsAsync(data, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.SetProviderCompanyDetailsAsync(data)).MustHaveHappenedOnceExactly(); Assert.IsType(result); } @@ -124,14 +124,14 @@ public async Task GetProviderCompanyDetail_WithValidData_ReturnsOk() //Arrange var id = Guid.NewGuid(); var data = new ProviderDetailReturnData(id, CompanyId, "https://this-is-a-test.de"); - A.CallTo(() => _logic.GetProviderCompanyDetailsAsync(_identity.CompanyId)) + A.CallTo(() => _logic.GetProviderCompanyDetailsAsync()) .Returns(data); //Act var result = await this._controller.GetServiceProviderCompanyDetail().ConfigureAwait(false); //Assert - A.CallTo(() => _logic.GetProviderCompanyDetailsAsync(_identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetProviderCompanyDetailsAsync()).MustHaveHappenedOnceExactly(); result.Should().BeOfType(); result.Id.Should().Be(id); result.CompanyId.Should().Be(CompanyId); diff --git a/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs b/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs index 69876514b5..7d7cdc2146 100644 --- a/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs +++ b/tests/administration/Administration.Service.Tests/Controllers/UserControllerTest.cs @@ -54,14 +54,14 @@ public async Task ModifyUserRolesAsync_WithValidData_ReturnsExpectedResult() //Arrange var appId = new Guid("8d4bfde6-978f-4d82-86ce-8d90d52fbf3f"); var userRoleInfo = new UserRoleInfo(CompanyUserId, new[] { "Company Admin" }); - A.CallTo(() => _rolesLogic.ModifyUserRoleAsync(A._, A._, A._)) + A.CallTo(() => _rolesLogic.ModifyUserRoleAsync(A._, A._)) .Returns(Enumerable.Empty()); //Act var result = await this._controller.ModifyUserRolesAsync(appId, userRoleInfo).ConfigureAwait(false); //Assert - A.CallTo(() => _rolesLogic.ModifyUserRoleAsync(A.That.Matches(x => x == appId), A.That.Matches(x => x.CompanyUserId == CompanyUserId && x.Roles.Count() == 1), _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _rolesLogic.ModifyUserRoleAsync(A.That.Matches(x => x == appId), A.That.Matches(x => x.CompanyUserId == CompanyUserId && x.Roles.Count() == 1))).MustHaveHappenedOnceExactly(); result.Should().BeEmpty(); } @@ -70,14 +70,14 @@ public async Task GetOwnUserDetails_ReturnsExpectedResult() { // Arrange var data = _fixture.Create(); - A.CallTo(() => _logic.GetOwnUserDetails(_identity.UserId)) + A.CallTo(() => _logic.GetOwnUserDetails()) .Returns(data); // Act var result = await this._controller.GetOwnUserDetails().ConfigureAwait(false); // Assert - A.CallTo(() => _logic.GetOwnUserDetails(_identity.UserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetOwnUserDetails()).MustHaveHappenedOnceExactly(); result.Should().Be(data); } } diff --git a/tests/framework/Framework.Web.Tests/IdentityServiceTests.cs b/tests/framework/Framework.Web.Tests/IdentityServiceTests.cs new file mode 100644 index 0000000000..16c8efd86f --- /dev/null +++ b/tests/framework/Framework.Web.Tests/IdentityServiceTests.cs @@ -0,0 +1,217 @@ +/******************************************************************************** + * 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 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.Tests; + +public class IdentityServiceTests +{ + private readonly IFixture _fixture; + + private readonly IHttpContextAccessor _httpContextAccessor; + private readonly HttpContext _httpContext; + private readonly ClaimsPrincipal _user; + + public IdentityServiceTests() + { + _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 sub = _fixture.Create(); + var identityId = Guid.NewGuid(); + var identityType = _fixture.Create(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut(sub, identityId.ToString(), identityType.ToString(), companyId.ToString()); + + // Act + var first = sut.IdentityData; + var second = sut.IdentityData; + + // Assert + first.Should().NotBeNull() + .And.BeSameAs(second) + .And.Match(x => + x.UserEntityId == sub && + x.UserId == identityId && + x.IdentityType == identityType && + x.CompanyId == companyId); + + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + [Fact] + public void IdentityData_EmptySub_Throws() + { + // Arrange + var identityId = Guid.NewGuid(); + var identityType = _fixture.Create(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut("", identityId.ToString(), identityType.ToString(), companyId.ToString()); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // Assert + error.Message.Should().Be("Claim sub must not be null or empty (Parameter 'claims')"); + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + [Fact] + public void IdentityData_EmptyIdentityId_Throws() + { + // Arrange + var sub = _fixture.Create(); + var identityType = _fixture.Create(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut(sub, "", identityType.ToString(), companyId.ToString()); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // 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 sub = _fixture.Create(); + var identityType = _fixture.Create(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut(sub, "deadbeef", identityType.ToString(), companyId.ToString()); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // 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(); + } + + [Fact] + public void IdentityData_EmptyIdentityType_Throws() + { + // Arrange + var sub = _fixture.Create(); + var identityId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut(sub, identityId.ToString(), "", companyId.ToString()); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // Assert + error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/identity_type must not be null or empty (Parameter 'claims')"); + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + [Fact] + public void IdentityData_NonEnumIdentityType_Throws() + { + // Arrange + var sub = _fixture.Create(); + var identityId = Guid.NewGuid(); + var companyId = Guid.NewGuid(); + + var sut = CreateSut(sub, identityId.ToString(), "deadbeef", companyId.ToString()); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // Assert + error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/identity_type must contain a Org.Eclipse.TractusX.Portal.Backend.PortalBackend.PortalEntities.Enums.IdentityTypeId (Parameter 'claims')"); + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + [Fact] + public void IdentityData_EmptyCompanyId_Throws() + { + // Arrange + var sub = _fixture.Create(); + var identityId = Guid.NewGuid(); + var identityType = _fixture.Create(); + + var sut = CreateSut(sub, identityId.ToString(), identityType.ToString(), ""); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // Assert + error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/company_id must not be null or empty (Parameter 'claims')"); + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + [Fact] + public void IdentityData_NonGuidCompanyId_Throws() + { + // Arrange + var sub = _fixture.Create(); + var identityId = Guid.NewGuid(); + var identityType = _fixture.Create(); + + var sut = CreateSut(sub, identityId.ToString(), identityType.ToString(), "deadbeef"); + + // Act + var error = Assert.Throws(() => sut.IdentityData); + + // Assert + error.Message.Should().Be("Claim https://catena-x.net//schema/2023/05/identity/claims/company_id must contain a Guid (Parameter 'claims')"); + A.CallTo(() => _httpContext.User).MustHaveHappenedOnceExactly(); + } + + private IIdentityService CreateSut(string sub, string identityId, string identityType, string companyId) + { + var claims = new Claim[] { + new(PortalClaimTypes.Sub, sub), + new(PortalClaimTypes.IdentityId, identityId), + new(PortalClaimTypes.IdentityType, identityType), + new(PortalClaimTypes.CompanyId, companyId) + }; + + A.CallTo(() => _user.Claims).Returns(claims); + A.CallTo(() => _httpContext.User).Returns(_user); + + return new IdentityService(_httpContextAccessor); + } +} diff --git a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs index e09d7ff831..9cadbab93e 100644 --- a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs +++ b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppChangeBusinessLogicTest.cs @@ -83,6 +83,7 @@ public AppChangeBusinessLogicTest() _notificationService = A.Fake(); _offerService = A.Fake(); _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); var settings = new AppsSettings { @@ -111,7 +112,7 @@ public AppChangeBusinessLogicTest() A.CallTo(() => _portalRepositories.GetInstance()).Returns(_offerSubscriptionsRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_userRolesRepository); A.CallTo(() => _portalRepositories.GetInstance()).Returns(_documentRepository); - _sut = new AppChangeBusinessLogic(_portalRepositories, _notificationService, _provisioningManager, _offerService, Options.Create(settings), _identityService); + _sut = new AppChangeBusinessLogic(_portalRepositories, _notificationService, _provisioningManager, _offerService, _identityService, Options.Create(settings)); } #region AddActiveAppUserRole @@ -157,7 +158,7 @@ public async Task AddActiveAppUserRoleAsync_ExecutesSuccessfully() .Returns(_fixture.CreateMany(4).AsFakeIAsyncEnumerable(out var createNotificationsResultAsyncEnumerator)); //Act - var result = await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + var result = await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc).ConfigureAwait(false); //Assert A.CallTo(() => _offerRepository.GetInsertActiveAppUserRoleDataAsync(appId, OfferTypeId.APP)).MustHaveHappened(); @@ -223,7 +224,7 @@ public async Task AddActiveAppUserRoleAsync_WithCompanyUserIdNotSet_ThrowsForbid .Returns((true, appName, Guid.NewGuid(), clientIds)); var existingOffer = _fixture.Create(); //Act - async Task Act() => await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + async Task Act() => await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc).ConfigureAwait(false); //Assert var ex = await Assert.ThrowsAsync(Act); @@ -247,7 +248,7 @@ public async Task AddActiveAppUserRoleAsync_WithProviderCompanyNotSet_ThrowsConf .Returns((true, appName, null, clientIds)); //Act - async Task Act() => await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + async Task Act() => await _sut.AddActiveAppUserRoleAsync(appId, appAssignedRoleDesc).ConfigureAwait(false); //Assert var ex = await Assert.ThrowsAsync(Act); @@ -270,7 +271,7 @@ public async Task GetAppUpdateDescriptionByIdAsync_ReturnsExpected() .Returns(appDescriptionData); // Act - var result = await _sut.GetAppUpdateDescriptionByIdAsync(appId, _identity.CompanyId).ConfigureAwait(false); + var result = await _sut.GetAppUpdateDescriptionByIdAsync(appId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -287,7 +288,7 @@ public async Task GetAppUpdateDescriptionByIdAsync_ThrowsNotFoundException() .Returns(((bool IsStatusActive, bool IsProviderCompanyUser, IEnumerable OfferDescriptionDatas))default); // Act - async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -306,7 +307,7 @@ public async Task GetAppUpdateDescriptionByIdAsync_ThrowsConflictException() .Returns(appDescriptionData); // Act - async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -325,7 +326,7 @@ public async Task GetAppUpdateDescriptionByIdAsync_ThrowsForbiddenException() .Returns(appDescriptionData); // Act - async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.GetAppUpdateDescriptionByIdAsync(appId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -342,7 +343,7 @@ public async Task GetAppUpdateDescriptionByIdAsync_withNullDescriptionData_Throw .Returns(appDescriptionData); // Act - var Act = () => _sut.GetAppUpdateDescriptionByIdAsync(appId, _identity.CompanyId); + var Act = () => _sut.GetAppUpdateDescriptionByIdAsync(appId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -376,7 +377,7 @@ public async Task CreateOrUpdateAppDescriptionByIdAsync_withEmptyExistingDescrip setOptionalParameters(existingOffer); }); // Act - await _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, _identity.CompanyId, updateDescriptionData).ConfigureAwait(false); + await _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, updateDescriptionData).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.CreateUpdateDeleteOfferDescriptions(appId, A>._, A>.That.IsSameSequenceAs(updateDescriptionData.Select(x => new ValueTuple(x.LanguageCode, x.LongDescription, x.ShortDescription))))) @@ -399,7 +400,7 @@ public async Task CreateOrUpdateAppDescriptionByIdAsync_withNullDescriptionData_ .Returns(appDescriptionData); // Act - var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, _identity.CompanyId, updateDescriptionData); + var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, updateDescriptionData); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -422,7 +423,7 @@ public async Task CreateOrUpdateAppDescriptionByIdAsync_ThrowsForbiddenException .Returns(appDescriptionData); // Act - var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, _identity.CompanyId, updateDescriptionData); + var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, updateDescriptionData); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -445,7 +446,7 @@ public async Task CreateOrUpdateAppDescriptionByIdAsync_ThrowsConflictException( .Returns(appDescriptionData); // Act - var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, _identity.CompanyId, updateDescriptionData); + var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, updateDescriptionData); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -467,7 +468,7 @@ public async Task CreateOrUpdateAppDescriptionByIdAsync_ThrowsNotFoundException( .Returns(((bool IsStatusActive, bool IsProviderCompanyUser, IEnumerable OfferDescriptionDatas))default); // Act - var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, _identity.CompanyId, updateDescriptionData); + var Act = () => _sut.CreateOrUpdateAppDescriptionByIdAsync(appId, updateDescriptionData); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -517,7 +518,7 @@ public async Task UploadOfferAssignedAppLeadImageDocumentById_ExpectedCalls() setOptionalParameters(existingOffer); }); // Act - await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, (_identity.UserId, _identity.CompanyId), file, CancellationToken.None); + await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert A.CallTo(() => _offerRepository.GetOfferAssignedAppLeadImageDocumentsByIdAsync(appId, _identity.CompanyId, OfferTypeId.APP)).MustHaveHappenedOnceExactly(); @@ -537,11 +538,12 @@ 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"); // Act - var Act = () => _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, (identity.UserId, identity.CompanyId), file, CancellationToken.None); + var Act = () => _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -554,13 +556,14 @@ 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!)); // Act - var Act = () => _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, (identity.UserId, identity.CompanyId), file, CancellationToken.None); + var Act = () => _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -573,13 +576,14 @@ 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!)); // Act - async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, (identity.UserId, identity.CompanyId), file, CancellationToken.None); + async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -592,13 +596,14 @@ 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>()); // Act - async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, (identity.UserId, identity.CompanyId), file, CancellationToken.None); + async Task Act() => await _sut.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -667,7 +672,7 @@ public async Task UpdateTenantUrlAsync_WithValidData_CallsExpected() setOptionalParameters(existingOffer); }); // Act - await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.UpdateClient(clientClientId, data.Url, A._)).MustHaveHappenedOnceExactly(); @@ -721,7 +726,7 @@ public async Task UpdateTenantUrlAsync_WithoutRequesterButValidData_CallsExpecte setOptionalParameters(existingOffer); }); // Act - await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.UpdateClient(clientClientId, data.Url, A._)).MustHaveHappenedOnceExactly(); @@ -772,7 +777,7 @@ public async Task UpdateTenantUrlAsync_WithoutClientId_CallsExpected() setOptionalParameters(existingOffer); }); // Act - await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.UpdateClient(clientClientId, data.Url, A._)).MustNotHaveHappened(); @@ -796,7 +801,7 @@ public async Task UpdateTenantUrlAsync_WithSameUrl_CallsNothing() A.CallTo(() => _offerSubscriptionsRepository.GetUpdateUrlDataAsync(appId, subscriptionId, _identity.CompanyId)) .Returns(new OfferUpdateUrlData("testApp", false, true, Guid.Empty, subscribingCompany, OfferSubscriptionStatusId.ACTIVE, new OfferUpdateUrlSubscriptionDetailData(detailId, clientClientId, oldUrl))); // Act - await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert A.CallTo(() => _provisioningManager.UpdateClient(clientClientId, oldUrl, A._)).MustNotHaveHappened(); @@ -815,7 +820,7 @@ public async Task UpdateTenantUrlAsync_WithInvalidUrl_ThrowsControllerArgumentEx var subscriptionId = _fixture.Create(); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -839,7 +844,7 @@ public async Task UpdateTenantUrlAsync_WithoutApp_ThrowsNotFoundException() .Returns((OfferUpdateUrlData?)null); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -865,7 +870,7 @@ public async Task UpdateTenantUrlAsync_WithSingleInstanceApp_ThrowsConflictExcep .Returns(new OfferUpdateUrlData("testApp", true, true, Guid.Empty, subscribingCompany, OfferSubscriptionStatusId.ACTIVE, new OfferUpdateUrlSubscriptionDetailData(detailId, clientClientId, oldUrl))); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -891,7 +896,7 @@ public async Task UpdateTenantUrlAsync_WithUserNotFromProvidingCompany_ThrowsFor .Returns(new OfferUpdateUrlData("testApp", false, false, Guid.Empty, subscribingCompany, OfferSubscriptionStatusId.ACTIVE, new OfferUpdateUrlSubscriptionDetailData(detailId, clientClientId, oldUrl))); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -917,7 +922,7 @@ public async Task UpdateTenantUrlAsync_WithInActiveApp_ThrowsConflictException() .Returns(new OfferUpdateUrlData("testApp", false, true, Guid.Empty, subscribingCompany, OfferSubscriptionStatusId.PENDING, new OfferUpdateUrlSubscriptionDetailData(detailId, clientClientId, oldUrl))); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -941,7 +946,7 @@ public async Task UpdateTenantUrlAsync_WithoutSubscriptionDetails_ThrowsConflict .Returns(new OfferUpdateUrlData("testApp", false, true, Guid.Empty, subscribingCompany, OfferSubscriptionStatusId.ACTIVE, null)); // Act - async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateTenantUrlAsync(appId, subscriptionId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); diff --git a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs index b834c0543f..bd561d8319 100644 --- a/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs +++ b/tests/marketplace/Apps.Service.Tests/BusinessLogic/AppReleaseBusinessLogicTest.cs @@ -68,6 +68,7 @@ public class AppReleaseBusinessLogicTest private readonly IOfferSetupService _offerSetupService; private readonly AppReleaseBusinessLogic _sut; private readonly IOfferDocumentService _offerDocumentService; + private readonly IIdentityService _identityService; public AppReleaseBusinessLogicTest() { @@ -96,6 +97,9 @@ public AppReleaseBusinessLogicTest() .Create(); _identity = new(IamUserId, _companyUser.Id, IdentityTypeId.COMPANY_USER, Guid.NewGuid()); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + _settings = new AppsSettings { BasePortalAddress = "https://test.com/", @@ -131,7 +135,7 @@ public AppReleaseBusinessLogicTest() .With(x => x.Languages, _languageCodes.Select(x => (x, true))) .Create(); - _sut = new AppReleaseBusinessLogic(_portalRepositories, _options, _offerService, _offerDocumentService, _offerSetupService); + _sut = new AppReleaseBusinessLogic(_portalRepositories, _options, _offerService, _offerDocumentService, _offerSetupService, _identityService); } [Fact] @@ -169,7 +173,7 @@ public async Task CreateServiceOffering_WithValidDataAndEmptyDescriptions_Return setOptionalParameters(existingOffer); }); // Act - var result = await _sut.AddAppUserRoleAsync(appId, appUserRoles, _identity.CompanyId).ConfigureAwait(false); + var result = await _sut.AddAppUserRoleAsync(appId, appUserRoles).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.IsProviderCompanyUserAsync(A._, A._, A._)).MustHaveHappened(); @@ -224,7 +228,7 @@ public async Task AddAppAsync_WithoutEmptyLanguageCodes_ThrowsException() .Create(); // Act - async Task Act() => await _sut.AddAppAsync(data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.AddAppAsync(data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -240,7 +244,7 @@ public async Task AddAppAsync_WithEmptyUseCaseIds_ThrowsException() .Create(); // Act - async Task Act() => await _sut.AddAppAsync(data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.AddAppAsync(data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -275,7 +279,7 @@ public async Task AddAppAsync_WithSalesManagerValidData_ReturnsExpected() }); // Act - await _sut.AddAppAsync(data, _identity.CompanyId).ConfigureAwait(false); + await _sut.AddAppAsync(data).ConfigureAwait(false); // Assert A.CallTo(() => _offerService.ValidateSalesManager(_companyUser.Id, A>._)).MustHaveHappenedOnceExactly(); @@ -328,7 +332,7 @@ public async Task AddAppAsync_WithNullSalesMangerValidData_ReturnsExpected() }); // Act - await _sut.AddAppAsync(data, _identity.CompanyId).ConfigureAwait(false); + await _sut.AddAppAsync(data).ConfigureAwait(false); // Assert A.CallTo(() => _offerService.ValidateSalesManager(A._, A>._)).MustNotHaveHappened(); @@ -370,7 +374,7 @@ public async Task UpdateAppReleaseAsync_WithoutApp_ThrowsException() var data = _fixture.Create(); // Act - async Task Act() => await _sut.UpdateAppReleaseAsync(_notExistingAppId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateAppReleaseAsync(_notExistingAppId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -385,7 +389,7 @@ public async Task UpdateAppReleaseAsync_WithActiveApp_ThrowsException() var data = _fixture.Create(); // Act - async Task Act() => await _sut.UpdateAppReleaseAsync(_activeAppId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateAppReleaseAsync(_activeAppId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -400,7 +404,7 @@ public async Task UpdateAppReleaseAsync_WithInvalidUser_ThrowsException() var data = _fixture.Create(); // Act - async Task Act() => await _sut.UpdateAppReleaseAsync(_differentCompanyAppId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateAppReleaseAsync(_differentCompanyAppId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -417,7 +421,7 @@ public async Task UpdateAppReleaseAsync_WithInvalidLanguage_ThrowsException() .Create(); // Act - async Task Act() => await _sut.UpdateAppReleaseAsync(_existingAppId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateAppReleaseAsync(_existingAppId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -445,7 +449,7 @@ public async Task UpdateAppReleaseAsync_WithValidData_ReturnsExpected() }); // Act - await _sut.UpdateAppReleaseAsync(_existingAppId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.UpdateAppReleaseAsync(_existingAppId, data).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.AttachAndModifyOffer(A._, A>._, A>._)) @@ -497,10 +501,10 @@ public async Task CreateAppDocumentAsync_ExecutesSuccessfully() }; // Act - await _sut.CreateAppDocumentAsync(appId, DocumentTypeId.APP_CONTRACT, file, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + await _sut.CreateAppDocumentAsync(appId, DocumentTypeId.APP_CONTRACT, file, CancellationToken.None).ConfigureAwait(false); // Assert - A.CallTo(() => _offerDocumentService.UploadDocumentAsync(appId, DocumentTypeId.APP_CONTRACT, file, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), OfferTypeId.APP, _settings.UploadAppDocumentTypeIds, CancellationToken.None)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerDocumentService.UploadDocumentAsync(appId, DocumentTypeId.APP_CONTRACT, file, OfferTypeId.APP, _settings.UploadAppDocumentTypeIds, CancellationToken.None)).MustHaveHappenedOnceExactly(); } #endregion @@ -731,7 +735,7 @@ public async Task DeleteAppAsync_ReturnsExpectedResult() .Returns((true, true, true, true, appDeleteData)); //Act - await _sut.DeleteAppAsync(appId, _identity.CompanyId).ConfigureAwait(false); + await _sut.DeleteAppAsync(appId).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.GetAppDeleteDataAsync(appId, OfferTypeId.APP, _identity.CompanyId, OfferStatusId.CREATED)) @@ -766,7 +770,7 @@ public async Task DeleteAppAsync_WithNoProviderCompanyUser_ThrowsForbiddenExcept .Returns((true, true, true, false, appDeleteData)); //Act - async Task Act() => await _sut.DeleteAppAsync(appId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.DeleteAppAsync(appId).ConfigureAwait(false); // Assert // Assert @@ -785,7 +789,7 @@ public async Task DeleteAppAsync_WithInvalidOfferStatus_ThrowsConflictException( .Returns((true, true, false, true, appDeleteData)); //Act - async Task Act() => await _sut.DeleteAppAsync(appId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.DeleteAppAsync(appId).ConfigureAwait(false); // Assert // Assert @@ -828,7 +832,7 @@ public async Task SetInstanceType_WithSingleInstanceWithoutUrl_ThrowsControllerA var data = new AppInstanceSetupData(true, null); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -843,7 +847,7 @@ public async Task SetInstanceType_WithMultiInstanceWithUrl_ThrowsControllerArgum var data = new AppInstanceSetupData(false, "https://test.de"); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -860,7 +864,7 @@ public async Task SetInstanceType_WithNotExistingApp_NotFoundException() .ReturnsLazily(() => new ValueTuple>()); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -877,7 +881,7 @@ public async Task SetInstanceType_WithInvalidUser_ThrowsForbiddenException() .ReturnsLazily(() => new ValueTuple>(OfferStatusId.ACTIVE, false, null, new List<(Guid, Guid, string)>())); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -894,7 +898,7 @@ public async Task SetInstanceType_WithWrongOfferState_ThrowsConflictException() .ReturnsLazily(() => new ValueTuple>(OfferStatusId.ACTIVE, true, null, new List<(Guid, Guid, string)>())); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -913,7 +917,7 @@ public async Task SetInstanceType_FromSingleToMultiWithoutAppInstance_ThrowsConf .ReturnsLazily(() => new ValueTuple>(OfferStatusId.CREATED, true, instanceSetupTransferData, new List<(Guid, Guid, string)>())); //Act - async Task Act() => await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -939,7 +943,7 @@ public async Task SetInstanceType_WithNewEntry_CreatesEntry() }); //Act - await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert instanceSetupData.Should().NotBeNull(); @@ -974,7 +978,7 @@ public async Task SetInstanceType_WithUrlUpdate_CreatesEntry() }); //Act - await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert instanceSetupData.InstanceUrl.Should().Be("https://new-url.de"); @@ -1003,7 +1007,7 @@ public async Task SetInstanceType_WithExistingEntryButNoAppInstance_ThrowsConfli }); //Act - await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert instanceSetupData.InstanceUrl.Should().Be(data.InstanceUrl); @@ -1036,7 +1040,7 @@ public async Task SetInstanceType_WithExistingEntry_UpdatesEntry() }); //Act - await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert instanceSetupData.InstanceUrl.Should().Be(data.InstanceUrl); @@ -1069,7 +1073,7 @@ public async Task SetInstanceType_FromSingleToMulti_UpdatesEntry() }); //Act - await _sut.SetInstanceType(appId, data, _identity.CompanyId).ConfigureAwait(false); + await _sut.SetInstanceType(appId, data).ConfigureAwait(false); // Assert instanceSetupData.InstanceUrl.Should().BeNull(); @@ -1137,7 +1141,7 @@ public async Task UpdateTechnicalUserProfiles_ReturnsExpected() const string clientProfile = "cl"; var appId = Guid.NewGuid(); var data = _fixture.CreateMany(5); - var sut = new AppReleaseBusinessLogic(null!, Options.Create(new AppsSettings { TechnicalUserProfileClient = clientProfile }), _offerService, _offerDocumentService, null!); + var sut = new AppReleaseBusinessLogic(null!, Options.Create(new AppsSettings { TechnicalUserProfileClient = clientProfile }), _offerService, _offerDocumentService, null!, _identityService); // Act await sut @@ -1160,7 +1164,7 @@ public async Task GetTechnicalUserProfilesForOffer_ReturnsExpected() var appId = Guid.NewGuid(); A.CallTo(() => _offerService.GetTechnicalUserProfilesForOffer(appId, OfferTypeId.APP)) .Returns(_fixture.CreateMany(5)); - var sut = new AppReleaseBusinessLogic(null!, Options.Create(new AppsSettings()), _offerService, _offerDocumentService, null!); + var sut = new AppReleaseBusinessLogic(null!, Options.Create(new AppsSettings()), _offerService, _offerDocumentService, null!, _identityService); // Act var result = await sut.GetTechnicalUserProfilesForOffer(appId) diff --git a/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs b/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs index edee8c1288..20eff11019 100644 --- a/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs +++ b/tests/marketplace/Apps.Service.Tests/Controllers/AppChangeControllerTest.cs @@ -56,7 +56,7 @@ public async Task AddActiveAppUserRole_ReturnsExpectedCount() var appId = _fixture.Create(); var appUserRoles = _fixture.CreateMany(3); var appRoleData = _fixture.CreateMany(3); - A.CallTo(() => _logic.AddActiveAppUserRoleAsync(appId, appUserRoles, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId))) + A.CallTo(() => _logic.AddActiveAppUserRoleAsync(appId, appUserRoles)) .Returns(appRoleData); //Act @@ -64,7 +64,7 @@ public async Task AddActiveAppUserRole_ReturnsExpectedCount() foreach (var item in result) { //Assert - A.CallTo(() => _logic.AddActiveAppUserRoleAsync(appId, appUserRoles, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.AddActiveAppUserRoleAsync(appId, appUserRoles)).MustHaveHappenedOnceExactly(); Assert.NotNull(item); Assert.IsType(item); } @@ -77,14 +77,14 @@ public async Task GetAppUpdateDescriptionsAsync_ReturnsExpected() var appId = _fixture.Create(); var offerDescriptionData = _fixture.CreateMany(3); - A.CallTo(() => _logic.GetAppUpdateDescriptionByIdAsync(A._, A._)) + A.CallTo(() => _logic.GetAppUpdateDescriptionByIdAsync(A._)) .Returns(offerDescriptionData); //Act var result = await _controller.GetAppUpdateDescriptionsAsync(appId).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.GetAppUpdateDescriptionByIdAsync(A._, A._)).MustHaveHappened(); + A.CallTo(() => _logic.GetAppUpdateDescriptionByIdAsync(A._)).MustHaveHappened(); } [Fact] @@ -98,7 +98,7 @@ public async Task CreateOrUpdateAppDescriptionsAsync_ReturnsExpected() var result = await _controller.CreateOrUpdateAppDescriptionsByIdAsync(appId, offerDescriptionData).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.CreateOrUpdateAppDescriptionByIdAsync(A._, A._, A>._)).MustHaveHappened(); + A.CallTo(() => _logic.CreateOrUpdateAppDescriptionByIdAsync(A._, A>._)).MustHaveHappened(); result.Should().BeOfType(); } @@ -108,14 +108,14 @@ public async Task UploadOfferAssignedAppLeadImageDocumentByIdAsync_ReturnsExpect // Arrange var appId = _fixture.Create(); var file = FormFileHelper.GetFormFile("Test Image", "TestImage.jpeg", "image/jpeg"); - A.CallTo(() => _logic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(A._, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), A._, CancellationToken.None)) + A.CallTo(() => _logic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(A._, A._, CancellationToken.None)) .ReturnsLazily(() => Task.CompletedTask); // Act var result = await _controller.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None).ConfigureAwait(false); // Assert - A.CallTo(() => _logic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), file, CancellationToken.None)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.UploadOfferAssignedAppLeadImageDocumentByIdAsync(appId, file, CancellationToken.None)).MustHaveHappenedOnceExactly(); result.Should().BeOfType(); } @@ -144,7 +144,7 @@ public async Task UpdateTenantUrl_ReturnsExpected() var result = await _controller.UpdateTenantUrl(appId, subscriptionId, data).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.UpdateTenantUrlAsync(appId, subscriptionId, data, _identity.CompanyId)).MustHaveHappened(); + A.CallTo(() => _logic.UpdateTenantUrlAsync(appId, subscriptionId, data)).MustHaveHappened(); result.Should().BeOfType(); } diff --git a/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs b/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs index 3a0f2187bd..37f578a039 100644 --- a/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs +++ b/tests/marketplace/Apps.Service.Tests/Controllers/AppReleaseProcessControllerTest.cs @@ -63,7 +63,7 @@ public async Task UpdateAppDocument_ReturnsExpectedResult() await this._controller.UpdateAppDocumentAsync(appId, documentTypeId, file, CancellationToken.None).ConfigureAwait(false); // Assert - A.CallTo(() => _logic.CreateAppDocumentAsync(appId, documentTypeId, file, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), CancellationToken.None)) + A.CallTo(() => _logic.CreateAppDocumentAsync(appId, documentTypeId, file, CancellationToken.None)) .MustHaveHappenedOnceExactly(); } @@ -74,7 +74,7 @@ public async Task AddAppUserRole_AndUserRoleDescriptionWith201StatusCode() var appId = new Guid("5cf74ef8-e0b7-4984-a872-474828beb5d2"); var appUserRoles = _fixture.CreateMany(3); var appRoleData = _fixture.CreateMany(3); - A.CallTo(() => _logic.AddAppUserRoleAsync(appId, appUserRoles, _identity.CompanyId)) + A.CallTo(() => _logic.AddAppUserRoleAsync(appId, appUserRoles)) .Returns(appRoleData); //Act @@ -82,7 +82,7 @@ public async Task AddAppUserRole_AndUserRoleDescriptionWith201StatusCode() foreach (var item in result) { //Assert - A.CallTo(() => _logic.AddAppUserRoleAsync(appId, appUserRoles, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.AddAppUserRoleAsync(appId, appUserRoles)).MustHaveHappenedOnceExactly(); Assert.NotNull(item); Assert.IsType(item); } @@ -170,7 +170,7 @@ public async Task DeleteAppRoleAsync_ReturnsExpectedResult() // Assert Assert.IsType(result); - A.CallTo(() => _logic.DeleteAppRoleAsync(appId, roleId, _identity.CompanyId)) + A.CallTo(() => _logic.DeleteAppRoleAsync(appId, roleId)) .MustHaveHappenedOnceExactly(); } @@ -179,7 +179,7 @@ public async Task GetAppProviderSalesManagerAsync_ReturnsExpectedResult() { //Arrange var data = _fixture.CreateMany(5).ToAsyncEnumerable(); - A.CallTo(() => _logic.GetAppProviderSalesManagersAsync(A._)) + A.CallTo(() => _logic.GetAppProviderSalesManagersAsync()) .Returns(data); //Act @@ -187,7 +187,7 @@ public async Task GetAppProviderSalesManagerAsync_ReturnsExpectedResult() // Assert result.Should().HaveCount(5); - A.CallTo(() => _logic.GetAppProviderSalesManagersAsync(_identity.CompanyId)) + A.CallTo(() => _logic.GetAppProviderSalesManagersAsync()) .MustHaveHappenedOnceExactly(); } @@ -197,14 +197,14 @@ public async Task ExecuteAppCreation_ReturnsExpectedId() //Arrange var appId = _fixture.Create(); var data = _fixture.Create(); - A.CallTo(() => _logic.AddAppAsync(A._, _identity.CompanyId)) + A.CallTo(() => _logic.AddAppAsync(A._)) .Returns(appId); //Act var result = await this._controller.ExecuteAppCreation(data).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.AddAppAsync(data, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.AddAppAsync(data)).MustHaveHappenedOnceExactly(); Assert.IsType(result); result.Value.Should().Be(appId); } @@ -245,7 +245,7 @@ public async Task UpdateAppRelease_ReturnsNoContent() // Assert Assert.IsType(result); - A.CallTo(() => _logic.UpdateAppReleaseAsync(appId, data, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.UpdateAppReleaseAsync(appId, data)).MustHaveHappenedOnceExactly(); } [Fact] @@ -352,7 +352,7 @@ public async Task DeleteAppAsync_ReturnsExpectedResult() // Assert Assert.IsType(result); - A.CallTo(() => _logic.DeleteAppAsync(appId, _identity.CompanyId)) + A.CallTo(() => _logic.DeleteAppAsync(appId)) .MustHaveHappenedOnceExactly(); } @@ -365,7 +365,7 @@ public async Task SetInstanceType_ReturnsExpectedResult() var result = await _controller.SetInstanceType(appId, data).ConfigureAwait(false); Assert.IsType(result); - A.CallTo(() => _logic.SetInstanceType(appId, data, _identity.CompanyId)) + A.CallTo(() => _logic.SetInstanceType(appId, data)) .MustHaveHappenedOnceExactly(); } diff --git a/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs b/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs index 71ed7deae2..99abdf91b8 100644 --- a/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs +++ b/tests/marketplace/Offer.Library.Web.Tests/OfferDocumentServiceTests.cs @@ -41,6 +41,7 @@ public class OfferDocumentServiceTests private readonly IOfferRepository _offerRepository; private readonly IDocumentRepository _documentRepository; private readonly OfferDocumentService _sut; + private readonly IIdentityService _identityService; public OfferDocumentServiceTests() { @@ -49,12 +50,15 @@ public OfferDocumentServiceTests() .ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + _portalRepositories = A.Fake(); _offerRepository = A.Fake(); _documentRepository = A.Fake(); SetupCreateDocument(); - _sut = new OfferDocumentService(_portalRepositories); + _sut = new OfferDocumentService(_portalRepositories, _identityService); } #region UploadDocument @@ -94,7 +98,7 @@ public async Task UploadDocumentAsync_WithValidData_CallsExpected(OfferTypeId of setOptionalParameters(existingOffer); }); // Act - await _sut.UploadDocumentAsync(_validAppId, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + await _sut.UploadDocumentAsync(_validAppId, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.AttachAndModifyOffer(_validAppId, A>._, A?>._)).MustHaveHappenedOnceExactly(); @@ -118,7 +122,7 @@ public async Task UploadDocumentAsync_InValidData_ThrowsNotFoundException(OfferT .Returns(((bool, bool, bool))default); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -137,7 +141,7 @@ public async Task UploadDocumentAsync_EmptyId_ThrowsControllerArgumentException( var file = FormFileHelper.GetFormFile("this is just a test", "superFile.pdf", "application/pdf"); // Act - async Task Act() => await _sut.UploadDocumentAsync(Guid.Empty, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(Guid.Empty, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -157,7 +161,7 @@ public async Task UploadDocumentAsync_EmptyFileName_ThrowsControllerArgumentExce var file = FormFileHelper.GetFormFile("this is just a test", "", "application/pdf"); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -177,7 +181,7 @@ public async Task UploadDocumentAsync_contentType_ThrowsUnsupportedMediaTypeExce var file = FormFileHelper.GetFormFile("this is just a test", "TestFile.txt", "image/svg+xml"); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -197,7 +201,7 @@ public async Task UploadDocumentAsync_contentType_ThrowsUnsupportedMediaTypeExce var file = FormFileHelper.GetFormFile("this is just a test", "TestFile.txt", "foo/bar"); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -217,7 +221,7 @@ public async Task UploadDocumentAsync_documentType_ThrowsControllerArgumentExcep var file = FormFileHelper.GetFormFile("this is just a test", "superFile.pdf", "application/pdf"); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (_identity.UserId, _identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -232,6 +236,7 @@ public async Task UploadDocumentAsync_isStatusCreated_ThrowsConflictException(Of // Arrange var id = _fixture.Create(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); var uploadDocumentTypeIdSettings = offerTypeId == OfferTypeId.APP ? new UploadDocumentConfig[] { new(DocumentTypeId.APP_CONTRACT, new[] { MediaTypeId.PDF }) } : new UploadDocumentConfig[] { new(DocumentTypeId.ADDITIONAL_DETAILS, new[] { MediaTypeId.PDF }) }; @@ -240,7 +245,7 @@ public async Task UploadDocumentAsync_isStatusCreated_ThrowsConflictException(Of .Returns((true, false, true)); // Act - async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, (identity.UserId, identity.CompanyId), offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); + async Task Act() => await _sut.UploadDocumentAsync(id, documentTypeId, file, offerTypeId, uploadDocumentTypeIdSettings, CancellationToken.None).ConfigureAwait(false); // Arrange var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); diff --git a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs index 8284c4a5f0..99b9c56e38 100644 --- a/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs +++ b/tests/marketplace/Services.Service.Tests/BusinessLogic/ServiceReleaseBusinessLogicTest.cs @@ -63,6 +63,7 @@ public class ServiceReleaseBusinessLogicTest private readonly ServiceReleaseBusinessLogic _sut; private readonly IOptions _options; private readonly IOfferDocumentService _offerDocumentService; + private readonly IIdentityService _identityService; public ServiceReleaseBusinessLogicTest() { @@ -78,6 +79,9 @@ public ServiceReleaseBusinessLogicTest() _staticDataRepository = A.Fake(); _technicalUserProfileRepository = A.Fake(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + SetupRepositories(); var serviceSettings = new ServiceSettings { @@ -99,7 +103,7 @@ public ServiceReleaseBusinessLogicTest() }; _options = Options.Create(serviceSettings); _fixture.Inject(_options); - _sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _options); + _sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _identityService, _options); } [Fact] @@ -384,10 +388,9 @@ public async Task UpdateServiceAsync_WithoutService_ThrowsException() // Arrange SetupUpdateService(); var data = new ServiceUpdateRequestData("test", new List(), new List(), "123", "test@email.com", Guid.NewGuid(), null); - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, Options.Create(new ServiceSettings())); // Act - async Task Act() => await sut.UpdateServiceAsync(_notExistingServiceId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateServiceAsync(_notExistingServiceId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -400,10 +403,9 @@ public async Task UpdateServiceAsync_WithActiveService_ThrowsException() // Arrange SetupUpdateService(); var data = new ServiceUpdateRequestData("test", new List(), new List(), "123", "test@email.com", Guid.NewGuid(), null); - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, Options.Create(new ServiceSettings())); // Act - async Task Act() => await sut.UpdateServiceAsync(_activeServiceId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateServiceAsync(_activeServiceId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -416,10 +418,9 @@ public async Task UpdateServiceAsync_WithInvalidUser_ThrowsException() // Arrange SetupUpdateService(); var data = new ServiceUpdateRequestData("test", new List(), new List(), "123", "test@email.com", Guid.NewGuid(), null); - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, Options.Create(new ServiceSettings())); // Act - async Task Act() => await sut.UpdateServiceAsync(_differentCompanyServiceId, data, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await _sut.UpdateServiceAsync(_differentCompanyServiceId, data).ConfigureAwait(false); // Assert var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -459,10 +460,10 @@ public async Task UpdateServiceAsync_WithValidData_ReturnsExpected() initializeParameters?.Invoke(existingOffer); setOptionalParameters(existingOffer); }); - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, Options.Create(settings)); + var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _identityService, Options.Create(settings)); // Act - await sut.UpdateServiceAsync(_existingServiceId, data, _identity.CompanyId).ConfigureAwait(false); + await sut.UpdateServiceAsync(_existingServiceId, data).ConfigureAwait(false); // Assert A.CallTo(() => _offerRepository.AttachAndModifyOffer(A._, A>._, A>._)) @@ -487,10 +488,9 @@ public async Task UpdateServiceAsync_WithValidData_ReturnsExpected() public async Task SubmitServiceAsync_CallsOfferService() { // Arrange - var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, _options); // Act - await sut.SubmitServiceAsync(_existingServiceId).ConfigureAwait(false); + await _sut.SubmitServiceAsync(_existingServiceId).ConfigureAwait(false); // Assert A.CallTo(() => @@ -516,7 +516,7 @@ public async Task DeclineServiceRequestAsync_CallsExpected() ServiceManagerRoles = _fixture.CreateMany(), BasePortalAddress = "test" }; - var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, Options.Create(settings)); + var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, _identityService, Options.Create(settings)); // Act await sut.DeclineServiceRequestAsync(_existingServiceId, data).ConfigureAwait(false); @@ -544,13 +544,13 @@ public async Task CreateServiceDocument_ExecutesSuccessfully() new UploadDocumentConfig(DocumentTypeId.ADDITIONAL_DETAILS, new []{ MediaTypeId.PDF }) } }; - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, Options.Create(settings)); + var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _identityService, Options.Create(settings)); // Act - await sut.CreateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + await sut.CreateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None).ConfigureAwait(false); // Assert - A.CallTo(() => _offerDocumentService.UploadDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, A<(Guid, Guid)>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), OfferTypeId.SERVICE, settings.UploadServiceDocumentTypeIds, CancellationToken.None)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _offerDocumentService.UploadDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, OfferTypeId.SERVICE, settings.UploadServiceDocumentTypeIds, CancellationToken.None)).MustHaveHappenedOnceExactly(); } #endregion @@ -562,7 +562,7 @@ public async Task ApproveServiceRequestAsync_WithValid_CallsExpected() { // Arrange var appId = Guid.NewGuid(); - var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _options); + var sut = new ServiceReleaseBusinessLogic(_portalRepositories, _offerService, _offerDocumentService, _identityService, _options); // Act await sut.ApproveServiceRequestAsync(appId).ConfigureAwait(false); @@ -585,7 +585,7 @@ public async Task GetTechnicalUserProfilesForOffer_ReturnsExpected() // Arrange A.CallTo(() => _offerService.GetTechnicalUserProfilesForOffer(_existingServiceId, OfferTypeId.SERVICE)) .Returns(_fixture.CreateMany(5)); - var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, Options.Create(new ServiceSettings())); + var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, _identityService, Options.Create(new ServiceSettings())); // Act var result = await sut.GetTechnicalUserProfilesForOffer(_existingServiceId) @@ -604,7 +604,7 @@ public async Task UpdateTechnicalUserProfiles_ReturnsExpected() // Arrange const string clientProfile = "cl"; var data = _fixture.CreateMany(5); - var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, Options.Create(new ServiceSettings { TechnicalUserProfileClient = clientProfile })); + var sut = new ServiceReleaseBusinessLogic(null!, _offerService, _offerDocumentService, _identityService, Options.Create(new ServiceSettings { TechnicalUserProfileClient = clientProfile })); // Act await sut diff --git a/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs b/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs index 0d3c5bcbbe..c3125ca193 100644 --- a/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs +++ b/tests/marketplace/Services.Service.Tests/Controllers/ServiceReleaseControllerTest.cs @@ -212,14 +212,14 @@ public async Task UpdateService_ReturnsExpected() //Arrange var serviceId = _fixture.Create(); var data = _fixture.Create(); - A.CallTo(() => _logic.UpdateServiceAsync(A._, A._, _identity.CompanyId)) + A.CallTo(() => _logic.UpdateServiceAsync(A._, A._)) .Returns(Task.CompletedTask); //Act var result = await this._controller.UpdateService(serviceId, data).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.UpdateServiceAsync(serviceId, data, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.UpdateServiceAsync(serviceId, data)).MustHaveHappenedOnceExactly(); Assert.IsType(result); } @@ -273,8 +273,7 @@ public async Task UpdateServiceDocumentAsync_CallExpected() await this._controller.UpdateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None).ConfigureAwait(false); // Assert - A.CallTo(() => _logic.CreateServiceDocumentAsync(serviceId, - DocumentTypeId.ADDITIONAL_DETAILS, file, A>.That.Matches(x => x.Item1 == _identity.UserId && x.Item2 == _identity.CompanyId), CancellationToken.None)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.CreateServiceDocumentAsync(serviceId, DocumentTypeId.ADDITIONAL_DETAILS, file, CancellationToken.None)).MustHaveHappenedOnceExactly(); } [Fact] diff --git a/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs b/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs index 21f83bf999..eb621c4c12 100644 --- a/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs +++ b/tests/notifications/Notifications.Service.Tests/BusinessLogic/NotificationBusinessLogicTests.cs @@ -51,6 +51,7 @@ public class NotificationBusinessLogicTests private readonly IEnumerable _readNotificationDetails; private readonly IEnumerable _unreadNotificationDetails; private readonly IUserRepository _userRepository; + private readonly IIdentityService _identityService; public NotificationBusinessLogicTests() { @@ -65,6 +66,9 @@ public NotificationBusinessLogicTests() _notificationRepository = A.Fake(); _userRepository = A.Fake(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + _readNotificationDetails = _fixture.Build() .CreateMany(1); _unreadNotificationDetails = _fixture.Build() @@ -81,13 +85,13 @@ public NotificationBusinessLogicTests() public async Task GetNotifications_WithStatus_ReturnsList(bool status) { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var result = await sut.GetNotificationsAsync(0, 15, _identity.UserId, new NotificationFilters(status, null, null, false, null, null, Enumerable.Empty(), null)).ConfigureAwait(false); + var result = await sut.GetNotificationsAsync(0, 15, new NotificationFilters(status, null, null, false, null, null, Enumerable.Empty(), null)).ConfigureAwait(false); // Assert var expectedCount = status ? @@ -104,13 +108,13 @@ public async Task GetNotifications_WithStatus_ReturnsList(bool status) public async Task GetNotifications_WithoutStatus_ReturnsList(NotificationSorting sorting) { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var result = await sut.GetNotificationsAsync(0, 15, _identity.UserId, new NotificationFilters(null, null, null, false, sorting, null, Enumerable.Empty(), null)).ConfigureAwait(false); + var result = await sut.GetNotificationsAsync(0, 15, new NotificationFilters(null, null, null, false, sorting, null, Enumerable.Empty(), null)).ConfigureAwait(false); // Assert result.Meta.NumberOfElements.Should().Be(_notificationDetails.Count()); @@ -124,13 +128,13 @@ public async Task GetNotifications_WithoutStatus_ReturnsList(NotificationSorting public async Task GetNotifications_SecondPage_ReturnsExpectedNotificationDetailData() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var results = await sut.GetNotificationsAsync(1, 3, _identity.UserId, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)).ConfigureAwait(false); + var results = await sut.GetNotificationsAsync(1, 3, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)).ConfigureAwait(false); // Assert results.Should().NotBeNull(); @@ -145,12 +149,12 @@ public async Task GetNotifications_SecondPage_ReturnsExpectedNotificationDetailD public async Task GetNotifications_ExceedMaxPageSize_Throws() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); - var Act = () => sut.GetNotificationsAsync(0, 20, _identity.UserId, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)); + var Act = () => sut.GetNotificationsAsync(0, 20, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)); // Act & Assert await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -160,12 +164,12 @@ public async Task GetNotifications_ExceedMaxPageSize_Throws() public async Task GetNotifications_NegativePage_Throws() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); - var Act = () => sut.GetNotificationsAsync(-1, 15, _identity.UserId, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)); + var Act = () => sut.GetNotificationsAsync(-1, 15, new NotificationFilters(null, null, null, false, null, null, Enumerable.Empty(), null)); // Act & Assert await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -175,16 +179,17 @@ public async Task GetNotifications_NegativePage_Throws() public async Task GetNotifications_WithFilters_CallsExpected() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 20 })); var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var filter = _fixture.Create(); // Act - var result = await sut.GetNotificationsAsync(0, 20, userId, filter).ConfigureAwait(false); + var result = await sut.GetNotificationsAsync(0, 20, filter).ConfigureAwait(false); // Assert A.CallTo(() => _notificationRepository.GetAllNotificationDetailsByReceiver(userId, filter.IsRead, filter.TypeId, filter.TopicId, filter.OnlyDueDate, filter.Sorting, filter.DoneState, A>.That.Matches(x => x.Count() == filter.SearchTypeIds.Count()), filter.SearchQuery)) @@ -199,13 +204,13 @@ public async Task GetNotifications_WithFilters_CallsExpected() public async Task GetNotificationDetailDataAsync_WithIdAndUser_ReturnsCorrectResult() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var result = await sut.GetNotificationDetailDataAsync(_identity.UserId, _notificationDetail.Id).ConfigureAwait(false); + var result = await sut.GetNotificationDetailDataAsync(_notificationDetail.Id).ConfigureAwait(false); // Assert var notificationDetailData = _unreadNotificationDetails.First(); @@ -217,13 +222,14 @@ public async Task GetNotificationDetailDataAsync_WithNotMatchingUser_ThrowsForbi { // Arrange var identity = _fixture.Create(); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + A.CallTo(() => _identityService.IdentityData).Returns(identity); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - async Task Act() => await sut.GetNotificationDetailDataAsync(identity.UserId, _notificationDetail.Id).ConfigureAwait(false); + async Task Act() => await sut.GetNotificationDetailDataAsync(_notificationDetail.Id).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -234,14 +240,14 @@ public async Task GetNotificationDetailDataAsync_WithNotMatchingUser_ThrowsForbi public async Task GetNotificationDetailDataAsync_WithNotMatchingNotificationId_ThrowsNotFoundException() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act var notificationId = Guid.NewGuid(); - async Task Act() => await sut.GetNotificationDetailDataAsync(_identity.UserId, notificationId).ConfigureAwait(false); + async Task Act() => await sut.GetNotificationDetailDataAsync(notificationId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -256,13 +262,13 @@ public async Task GetNotificationDetailDataAsync_WithNotMatchingNotificationId_T public async Task GetNotificationCountAsync_WithIdAndUser_ReturnsCorrectResult() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var result = await sut.GetNotificationCountAsync(_identity.UserId, false).ConfigureAwait(false); + var result = await sut.GetNotificationCountAsync(false).ConfigureAwait(false); // Assert result.Should().Be(5); @@ -288,13 +294,13 @@ public async Task GetNotificationCountDetailsAsync() new (false, false, NotificationTopicId.ACTION, 2), }); A.CallTo(() => _notificationRepository.GetCountDetailsForUserAsync(_identity.UserId)).Returns(data.AsAsyncEnumerable()); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - var result = await sut.GetNotificationCountDetailsAsync(_identity.UserId).ConfigureAwait(false); + var result = await sut.GetNotificationCountDetailsAsync().ConfigureAwait(false); // Assert result.Read.Should().Be(9); @@ -322,13 +328,13 @@ public async Task SetNotificationStatus_WithMatchingId_ReturnsDetailData(bool is initializers.Invoke(notification); dbupdatedfield.Invoke(notification); }); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - await sut.SetNotificationStatusAsync(_identity.UserId, _notificationDetail.Id, isRead).ConfigureAwait(false); + await sut.SetNotificationStatusAsync(_notificationDetail.Id, isRead).ConfigureAwait(false); // Assert A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); @@ -340,14 +346,15 @@ public async Task SetNotificationToRead_WithNotMatchingNotification_NotFoundExce { // Arrange var randomNotificationId = Guid.NewGuid(); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); // Act - async Task Act() => await sut.SetNotificationStatusAsync(identity.UserId, randomNotificationId, true).ConfigureAwait(false); + async Task Act() => await sut.SetNotificationStatusAsync(randomNotificationId, true).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -359,13 +366,14 @@ public async Task SetNotificationToRead_WithNotExistingCompanyUser_ThrowsForbidd { // Arrange var identity = _fixture.Create(); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + A.CallTo(() => _identityService.IdentityData).Returns(identity); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - async Task Act() => await sut.SetNotificationStatusAsync(identity.UserId, _notificationDetail.Id, true).ConfigureAwait(false); + async Task Act() => await sut.SetNotificationStatusAsync(_notificationDetail.Id, true).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -380,13 +388,13 @@ public async Task SetNotificationToRead_WithNotExistingCompanyUser_ThrowsForbidd public async Task DeleteNotification_WithValidData_ExecutesSuccessfully() { // Arrange - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - await sut.DeleteNotificationAsync(_identity.UserId, _notificationDetail.Id).ConfigureAwait(false); + await sut.DeleteNotificationAsync(_notificationDetail.Id).ConfigureAwait(false); // Assert A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); @@ -397,13 +405,14 @@ public async Task DeleteNotification_WithNotExistingCompanyUser_ThrowsForbiddenE { // Arrange var identity = _fixture.Create(); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + A.CallTo(() => _identityService.IdentityData).Returns(identity); + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - async Task Act() => await sut.DeleteNotificationAsync(identity.UserId, _notificationDetail.Id).ConfigureAwait(false); + async Task Act() => await sut.DeleteNotificationAsync(_notificationDetail.Id).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -415,13 +424,13 @@ public async Task DeleteNotification_WithNotExistingNotification_ThrowsNotFoundE { // Arrange var randomNotificationId = Guid.NewGuid(); - var sut = new NotificationBusinessLogic(_portalRepositories, Options.Create(new NotificationSettings + var sut = new NotificationBusinessLogic(_portalRepositories, _identityService, Options.Create(new NotificationSettings { MaxPageSize = 15 })); // Act - async Task Act() => await sut.DeleteNotificationAsync(_identity.UserId, randomNotificationId); + async Task Act() => await sut.DeleteNotificationAsync(randomNotificationId); // Assert var ex = await Assert.ThrowsAsync(Act); diff --git a/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs b/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs index ad3fea4acb..ee140a014b 100644 --- a/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs +++ b/tests/notifications/Notifications.Service.Tests/Controllers/NotificationControllerTest.cs @@ -60,14 +60,14 @@ public async Task GetNotifications_ReturnsExpectedCount() var sorting = _fixture.Create(); var doneState = _fixture.Create(); var paginationResponse = new Pagination.Response(new Pagination.Metadata(15, 1, 1, 15), _fixture.CreateMany(5)); - A.CallTo(() => _logic.GetNotificationsAsync(A._, A._, A._, A._)) + A.CallTo(() => _logic.GetNotificationsAsync(A._, A._, A._)) .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); //Assert - A.CallTo(() => _logic.GetNotificationsAsync(0, 15, A._, A.That.Matches(x => x.IsRead == isRead && x.TypeId == typeId && x.TopicId == topicId && x.OnlyDueDate == onlyDueDate && x.Sorting == sorting && x.DoneState == doneState))).MustHaveHappenedOnceExactly(); + 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(); Assert.IsType>(result); result.Content.Should().HaveCount(5); } @@ -78,14 +78,14 @@ public async Task GetNotification_ReturnsExpectedData() //Arrange var data = _fixture.Create(); var notificationId = _fixture.Create(); - A.CallTo(() => _logic.GetNotificationDetailDataAsync(_identity.UserId, A._)) + A.CallTo(() => _logic.GetNotificationDetailDataAsync(A._)) .ReturnsLazily(() => data); //Act var result = await this._controller.GetNotification(notificationId).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.GetNotificationDetailDataAsync(_identity.UserId, notificationId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetNotificationDetailDataAsync(notificationId)).MustHaveHappenedOnceExactly(); result.Should().Be(data); } @@ -94,14 +94,14 @@ public async Task NotificationCountDetails_ReturnsExpectedData() { //Arrange var data = _fixture.Create(); - A.CallTo(() => _logic.GetNotificationCountDetailsAsync(_identity.UserId)) + A.CallTo(() => _logic.GetNotificationCountDetailsAsync()) .ReturnsLazily(() => data); //Act var result = await this._controller.NotificationCountDetails().ConfigureAwait(false); //Assert - A.CallTo(() => _logic.GetNotificationCountDetailsAsync(_identity.UserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.GetNotificationCountDetailsAsync()).MustHaveHappenedOnceExactly(); Assert.IsType(result); result.Should().Be(data); } @@ -111,14 +111,14 @@ public async Task SetNotificationToRead_ReturnsNoContent() { //Arrange var notificationId = Guid.NewGuid(); - A.CallTo(() => _logic.SetNotificationStatusAsync(_identity.UserId, notificationId, A._)) + A.CallTo(() => _logic.SetNotificationStatusAsync(notificationId, A._)) .ReturnsLazily(() => Task.CompletedTask); //Act var result = await this._controller.SetNotificationToRead(notificationId).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.SetNotificationStatusAsync(_identity.UserId, notificationId, true)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.SetNotificationStatusAsync(notificationId, true)).MustHaveHappenedOnceExactly(); Assert.IsType(result); } @@ -127,14 +127,14 @@ public async Task DeleteNotification_ReturnsNoContent() { //Arrange var notificationId = Guid.NewGuid(); - A.CallTo(() => _logic.DeleteNotificationAsync(_identity.UserId, notificationId)) + A.CallTo(() => _logic.DeleteNotificationAsync(notificationId)) .ReturnsLazily(() => Task.CompletedTask); //Act var result = await this._controller.DeleteNotification(notificationId).ConfigureAwait(false); //Assert - A.CallTo(() => _logic.DeleteNotificationAsync(_identity.UserId, notificationId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _logic.DeleteNotificationAsync(notificationId)).MustHaveHappenedOnceExactly(); Assert.IsType(result); } } diff --git a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs index 4e4aea51f6..8d7a0f8da9 100644 --- a/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs +++ b/tests/registration/Registration.Service.Tests/BusinessLogic/RegistrationBusinessLogicTest.cs @@ -66,9 +66,7 @@ public class RegistrationBusinessLogicTest private readonly IConsentRepository _consentRepository; private readonly IProcessStepRepository _processStepRepository; private readonly IApplicationChecklistCreationService _checklistService; - private readonly string _iamUserId; - private readonly IdentityData _identity; - private readonly Guid _companyUserId; + private readonly IdentityData _identity = new(Guid.NewGuid().ToString(), Guid.NewGuid(), IdentityTypeId.COMPANY_USER, Guid.NewGuid()); private readonly Guid _existingApplicationId; private readonly string _displayName; private readonly string _alpha2code; @@ -77,6 +75,7 @@ public class RegistrationBusinessLogicTest private readonly IMailingService _mailingService; private readonly IStaticDataRepository _staticDataRepository; private readonly Func _processLine; + private readonly IIdentityService _identityService; public RegistrationBusinessLogicTest() { @@ -102,6 +101,9 @@ public RegistrationBusinessLogicTest() _staticDataRepository = A.Fake(); _processStepRepository = A.Fake(); + _identityService = A.Fake(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity); + var options = Options.Create(new RegistrationSettings { BasePortalAddress = "just a test", @@ -114,15 +116,9 @@ public RegistrationBusinessLogicTest() _options = _fixture.Create>(); - _iamUserId = _fixture.Create(); - _companyUserId = _fixture.Create(); _existingApplicationId = _fixture.Create(); _displayName = _fixture.Create(); _alpha2code = "XY"; - _identity = _fixture.Build() - .With(x => x.UserEntityId, _iamUserId) - .With(x => x.UserId, _companyUserId) - .Create(); _error = _fixture.Create(); _processLine = A.Fake>(); @@ -148,7 +144,8 @@ public async Task GetClientRolesCompositeAsync_GetsAllRoles() null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act var result = sut.GetClientRolesCompositeAsync(); @@ -219,7 +216,8 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_R null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act var result = await sut.GetCompanyBpdmDetailDataByBusinessPartnerNumber(businessPartnerNumber, token, CancellationToken.None).ConfigureAwait(false); @@ -258,7 +256,8 @@ public async Task GetCompanyBpdmDetailDataByBusinessPartnerNumber_WithValidBpn_T null!, null!, null!, - null!); + null!, + _identityService); // Act async Task Act() => await sut.GetCompanyBpdmDetailDataByBusinessPartnerNumber("NotLongEnough", "justatoken", CancellationToken.None).ConfigureAwait(false); @@ -277,9 +276,7 @@ public async Task GetAllApplicationsForUserWithStatus_WithValidUser_GetsAllRoles { //Arrange var userCompanyId = _fixture.Create(); - var identity = _fixture.Build() - .With(x => x.CompanyId, userCompanyId) - .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = userCompanyId }); var sut = new RegistrationBusinessLogic( _options, null!, @@ -288,7 +285,9 @@ public async Task GetAllApplicationsForUserWithStatus_WithValidUser_GetsAllRoles null!, null!, _portalRepositories, - null!); + null!, + _identityService); + var resultList = new[]{ new CompanyApplicationWithStatus( _fixture.Create(), @@ -306,7 +305,7 @@ public async Task GetAllApplicationsForUserWithStatus_WithValidUser_GetsAllRoles .Returns(resultList.ToAsyncEnumerable()); // Act - var result = await sut.GetAllApplicationsForUserWithStatus(identity.CompanyId).ToListAsync().ConfigureAwait(false); + var result = await sut.GetAllApplicationsForUserWithStatus().ToListAsync().ConfigureAwait(false); result.Should().ContainSingle(); result.Single().ApplicationStatus.Should().Be(CompanyApplicationStatusId.VERIFY); result.Single().ApplicationChecklist.Should().NotBeNull().And.HaveCount(6).And.Satisfy( @@ -340,13 +339,14 @@ public async Task GetCompanyWithAddressAsync_WithValidApplication_GetsData() null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, _identity.CompanyId, null)) .Returns(data); // Act - var result = await sut.GetCompanyDetailData(applicationId, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.GetCompanyDetailData(applicationId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -367,13 +367,14 @@ public async Task GetCompanyWithAddressAsync_WithInvalidApplication_ThrowsNotFou null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, _identity.CompanyId, null)) .Returns((CompanyApplicationDetailData?)null); // Act - async Task Act() => await sut.GetCompanyDetailData(applicationId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.GetCompanyDetailData(applicationId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -393,13 +394,14 @@ public async Task GetCompanyWithAddressAsync_WithInvalidUser_ThrowsForbiddenExce null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, _identity.CompanyId, null)) .Returns(_fixture.Build().With(x => x.IsUserOfCompany, false).Create()); // Act - async Task Act() => await sut.GetCompanyDetailData(applicationId, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.GetCompanyDetailData(applicationId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -420,6 +422,7 @@ 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 sut = new RegistrationBusinessLogic( _options, null!, @@ -428,13 +431,14 @@ public async Task SetCompanyWithAddressAsync_WithMissingData_ThrowsArgumentExcep null!, null!, null!, - null!); + null!, + _identityService); var uniqueIdData = uniqueIdentifierIds.Zip(values, (id, value) => new CompanyUniqueIdData(id, value)); var companyData = new CompanyDetailData(Guid.NewGuid(), name!, city!, streetName!, countryCode!, null, null, null, null, null, null, uniqueIdData); // Act - async Task Act() => await sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData, Guid.NewGuid()).ConfigureAwait(false); + async Task Act() => await sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -455,7 +459,8 @@ public async Task SetCompanyWithAddressAsync_WithInvalidApplicationId_ThrowsNotF null!, null!, _portalRepositories, - null!); + null!, + _identityService); var companyData = new CompanyDetailData(companyId, "name", "munich", "main street", "de", null, null, null, null, null, null, Enumerable.Empty()); @@ -463,7 +468,7 @@ public async Task SetCompanyWithAddressAsync_WithInvalidApplicationId_ThrowsNotF .ReturnsLazily(() => (CompanyApplicationDetailData?)null); // Act - async Task Act() => await sut.SetCompanyDetailDataAsync(applicationId, companyData, _identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -476,9 +481,7 @@ public async Task SetCompanyWithAddressAsync_WithoutCompanyUserId_ThrowsForbidde //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - var identity = _fixture.Build() - .With(x => x.CompanyId, companyId) - .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); var companyData = new CompanyDetailData(companyId, "name", "munich", "main street", "de", null, null, null, null, null, null, Enumerable.Empty()); var sut = new RegistrationBusinessLogic( @@ -489,13 +492,14 @@ public async Task SetCompanyWithAddressAsync_WithoutCompanyUserId_ThrowsForbidde null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, companyId)) .ReturnsLazily(() => _fixture.Build().With(x => x.IsUserOfCompany, false).Create()); // Act - async Task Act() => await sut.SetCompanyDetailDataAsync(applicationId, companyData, identity.CompanyId).ConfigureAwait(false); + async Task Act() => await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -508,9 +512,7 @@ public async Task SetCompanyWithAddressAsync_ModifyCompany() //Arrange var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - var identity = _fixture.Build() - .With(x => x.CompanyId, companyId) - .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); var companyData = _fixture.Build() .With(x => x.CompanyId, companyId) .With(x => x.CountryAlpha2Code, _alpha2code) @@ -530,9 +532,10 @@ public async Task SetCompanyWithAddressAsync_ModifyCompany() null!, null!, _portalRepositories, - null!); + null!, + _identityService); - A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, identity.CompanyId)) + A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, companyId)) .Returns(existingData); A.CallTo(() => _companyRepository.AttachAndModifyCompany(A._, A>._, A>._)) @@ -544,7 +547,7 @@ public async Task SetCompanyWithAddressAsync_ModifyCompany() }); // Act - await sut.SetCompanyDetailDataAsync(applicationId, companyData, identity.CompanyId).ConfigureAwait(false); + await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert A.CallTo(() => _companyRepository.AttachAndModifyCompany(A._, A>._, A>._)) @@ -567,9 +570,7 @@ public async Task SetCompanyWithAddressAsync_WithoutInitialCompanyAddress_Create var companyId = Guid.NewGuid(); var addressId = Guid.NewGuid(); - var identity = _fixture.Build() - .With(x => x.CompanyId, companyId) - .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); var companyData = _fixture.Build() .With(x => x.CompanyId, companyId) .With(x => x.CountryAlpha2Code, _alpha2code) @@ -599,7 +600,8 @@ public async Task SetCompanyWithAddressAsync_WithoutInitialCompanyAddress_Create null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, companyId)) .Returns(existingData); @@ -621,7 +623,7 @@ public async Task SetCompanyWithAddressAsync_WithoutInitialCompanyAddress_Create }); // Act - await sut.SetCompanyDetailDataAsync(applicationId, companyData, identity.CompanyId).ConfigureAwait(false); + await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert A.CallTo(() => _companyRepository.CreateAddress(A._, A._, A._, A>._)) @@ -659,10 +661,8 @@ 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 identity = _fixture.Build() - .With(x => x.CompanyId, companyId) - .Create(); var companyData = _fixture.Build() .With(x => x.CompanyId, companyId) .With(x => x.CountryAlpha2Code, _alpha2code) @@ -684,9 +684,10 @@ public async Task SetCompanyWithAddressAsync_WithInitialCompanyAddress_ModifyAdd null!, null!, _portalRepositories, - null!); + null!, + _identityService); - A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, identity.CompanyId)) + A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, companyId)) .Returns(existingData); A.CallTo(() => _companyRepository.AttachAndModifyCompany(A._, A>._, A>._)) @@ -706,7 +707,7 @@ public async Task SetCompanyWithAddressAsync_WithInitialCompanyAddress_ModifyAdd }); // Act - await sut.SetCompanyDetailDataAsync(applicationId, companyData, identity.CompanyId).ConfigureAwait(false); + await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert A.CallTo(() => _companyRepository.CreateAddress(A._, A._, A._, A?>._)) @@ -741,9 +742,7 @@ public async Task SetCompanyWithAddressAsync_WithUniqueIdentifiers_CreateModifyD var applicationId = Guid.NewGuid(); var companyId = Guid.NewGuid(); - var identity = _fixture.Build() - .With(x => x.CompanyId, companyId) - .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = companyId }); var uniqueIdentifiers = _fixture.CreateMany(4); var firstIdData = _fixture.Build().With(x => x.UniqueIdentifierId, uniqueIdentifiers.First()).Create(); // shall not modify @@ -775,7 +774,8 @@ public async Task SetCompanyWithAddressAsync_WithUniqueIdentifiers_CreateModifyD null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _applicationRepository.GetCompanyApplicationDetailDataAsync(applicationId, A._, companyId)) .Returns(existingData); @@ -788,7 +788,7 @@ public async Task SetCompanyWithAddressAsync_WithUniqueIdentifiers_CreateModifyD }); // Act - await sut.SetCompanyDetailDataAsync(applicationId, companyData, identity.CompanyId).ConfigureAwait(false); + await sut.SetCompanyDetailDataAsync(applicationId, companyData).ConfigureAwait(false); // Assert A.CallTo(() => _companyRepository.CreateUpdateDeleteIdentifiers(companyId, A>._, A>._)).MustHaveHappenedOnceExactly(); @@ -808,6 +808,7 @@ public async Task SetCompanyWithAddressAsync_WithInvalidCountryCode_Throws() var companyData = _fixture.Build() .With(x => x.CountryAlpha2Code, _alpha2code) .Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var sut = new RegistrationBusinessLogic( _options, @@ -817,13 +818,14 @@ public async Task SetCompanyWithAddressAsync_WithInvalidCountryCode_Throws() null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _countryRepository.GetCountryAssignedIdentifiers(A._, A>._)) .Returns((false, null!)); // Act - var Act = () => sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData, Guid.NewGuid()); + var Act = () => sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData); //Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -835,6 +837,7 @@ public async Task SetCompanyWithAddressAsync_WithInvalidUniqueIdentifiers_Throws { //Arrange var identifiers = _fixture.CreateMany(2); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var companyData = _fixture.Build() .With(x => x.CountryAlpha2Code, _alpha2code) @@ -849,13 +852,14 @@ public async Task SetCompanyWithAddressAsync_WithInvalidUniqueIdentifiers_Throws null!, null!, _portalRepositories, - null!); + null!, + _identityService); A.CallTo(() => _countryRepository.GetCountryAssignedIdentifiers(_alpha2code, A>._)) .Returns((true, new[] { identifiers.First() })); // Act - var Act = () => sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData, Guid.NewGuid()); + var Act = () => sut.SetCompanyDetailDataAsync(Guid.NewGuid(), companyData); //Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -871,6 +875,7 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsCo { //Arrange var applicationId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var sut = new RegistrationBusinessLogic( _options, null!, @@ -879,10 +884,11 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsCo null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act - async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, 0, Guid.NewGuid()).ConfigureAwait(false); + async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, 0).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -894,6 +900,7 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidApplication_Thr { //Arrange var applicationId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var sut = new RegistrationBusinessLogic( _options, null!, @@ -902,12 +909,14 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidApplication_Thr null!, null!, _portalRepositories, - null!); + null!, + _identityService); + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserDataAsync(A._, A._)) .ReturnsLazily(() => new ValueTuple()); // Act - async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.VERIFY, Guid.NewGuid()).ConfigureAwait(false); + async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.VERIFY).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -919,6 +928,7 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsAr { //Arrange var applicationId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var sut = new RegistrationBusinessLogic( _options, null!, @@ -927,12 +937,14 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithInvalidStatus_ThrowsAr null!, null!, _portalRepositories, - null!); + null!, + _identityService); + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserDataAsync(A._, A._)) .ReturnsLazily(() => new ValueTuple(true, CompanyApplicationStatusId.CREATED)); // Act - async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.VERIFY, Guid.NewGuid()).ConfigureAwait(false); + async Task Act() => await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.VERIFY).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -944,6 +956,7 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithValidData_SavesChanges { //Arrange var applicationId = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { CompanyId = Guid.NewGuid() }); var sut = new RegistrationBusinessLogic( _options, null!, @@ -952,12 +965,14 @@ public async Task SetOwnCompanyApplicationStatusAsync_WithValidData_SavesChanges null!, null!, _portalRepositories, - null!); + null!, + _identityService); + A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserDataAsync(A._, A._)) .ReturnsLazily(() => new ValueTuple(true, CompanyApplicationStatusId.VERIFY)); // Act - await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.SUBMITTED, Guid.NewGuid()).ConfigureAwait(false); + await sut.SetOwnCompanyApplicationStatusAsync(applicationId, CompanyApplicationStatusId.SUBMITTED).ConfigureAwait(false); // Assert A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); @@ -984,7 +999,9 @@ public async Task GetCompanyRolesAsync_() null!, null!, _portalRepositories, - null!); + null!, + _identityService); + // Act var result = await sut.GetCompanyRoles().ToListAsync().ConfigureAwait(false); @@ -1062,10 +1079,11 @@ public async Task UploadDocumentAsync_WithValidData_CreatesDocument() null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act - await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.CX_FRAME_CONTRACT, (_identity.UserId, _identity.CompanyId), CancellationToken.None); + await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.CX_FRAME_CONTRACT, CancellationToken.None); // Assert A.CallTo(() => _portalRepositories.SaveAsync()).MustHaveHappenedOnceExactly(); @@ -1080,7 +1098,7 @@ public async Task UploadDocumentAsync_WithJsonDocument_ThrowsException() var sut = _fixture.Create(); // Act - async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, (_identity.UserId, _identity.CompanyId), CancellationToken.None).ConfigureAwait(false); + async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, CancellationToken.None).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -1095,7 +1113,7 @@ public async Task UploadDocumentAsync_WithEmptyTitle_ThrowsException() var sut = _fixture.Create(); // Act - async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, (_identity.UserId, _identity.CompanyId), CancellationToken.None); + async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, CancellationToken.None); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -1122,11 +1140,12 @@ public async Task UploadDocumentAsync_WithNotExistingApplicationId_ThrowsExcepti null!, null!, _portalRepositories, - null!); + null!, + _identityService); var notExistingId = Guid.NewGuid(); // Act - async Task Action() => await sut.UploadDocumentAsync(notExistingId, file, DocumentTypeId.CX_FRAME_CONTRACT, (_identity.UserId, _identity.CompanyId), CancellationToken.None); + async Task Action() => await sut.UploadDocumentAsync(notExistingId, file, DocumentTypeId.CX_FRAME_CONTRACT, CancellationToken.None); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -1156,11 +1175,12 @@ public async Task UploadDocumentAsync_WithNotExistingIamUser_ThrowsException() null!, null!, _portalRepositories, - null!); + null!, + _identityService); var identity = _fixture.Create(); // Act - async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.CX_FRAME_CONTRACT, (_identity.UserId, _identity.CompanyId), CancellationToken.None); + async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.CX_FRAME_CONTRACT, CancellationToken.None); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -1189,9 +1209,10 @@ public async Task UploadDocumentAsync_WithInvalidDocumentTypeId_ThrowsException( null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act - async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, (_identity.UserId, _identity.CompanyId), CancellationToken.None); + async Task Action() => await sut.UploadDocumentAsync(_existingApplicationId, file, DocumentTypeId.ADDITIONAL_DETAILS, CancellationToken.None); // Assert var ex = await Assert.ThrowsAsync(Action); @@ -1217,9 +1238,10 @@ public async Task TestInviteNewUserAsyncSuccess() _userProvisioningService, null!, _portalRepositories, - null!); + null!, + _identityService); - await sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo, (_identity.UserId, _identity.CompanyId)).ConfigureAwait(false); + await sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo).ConfigureAwait(false); A.CallTo(() => _userProvisioningService.CreateOwnCompanyIdpUsersAsync(A._, A>._, A._)).MustHaveHappened(); A.CallTo(() => _applicationRepository.CreateInvitation(A.That.IsEqualTo(_existingApplicationId), A._)).MustHaveHappened(); @@ -1246,9 +1268,10 @@ public async Task TestInviteNewUserEmptyEmailThrows() _userProvisioningService, null!, _portalRepositories, - null!); + null!, + _identityService); - Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be("email must not be empty"); @@ -1274,9 +1297,10 @@ public async Task TestInviteNewUserUserAlreadyExistsThrows() _userProvisioningService, null!, _portalRepositories, - null!); + null!, + _identityService); - Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be($"user with email {userCreationInfo.eMail} does already exist"); @@ -1307,9 +1331,10 @@ public async Task TestInviteNewUserAsyncCreationErrorThrows() _userProvisioningService, null!, _portalRepositories, - null!); + null!, + _identityService); - Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo, (_identity.UserId, _identity.CompanyId)); + Task Act() => sut.InviteNewUserAsync(_existingApplicationId, userCreationInfo); var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); error.Message.Should().Be(_error.Message); @@ -1330,6 +1355,7 @@ public async Task GetUploadedDocumentsAsync_ReturnsExpectedOutput() // Arrange var applicationId = _fixture.Create(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); var uploadDocuments = _fixture.CreateMany(3); A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) @@ -1343,9 +1369,10 @@ public async Task GetUploadedDocumentsAsync_ReturnsExpectedOutput() null!, null!, _portalRepositories, - null!); + null!, + _identityService); // Act - var result = await sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId).ConfigureAwait(false); + var result = await sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -1359,6 +1386,7 @@ public async Task GetUploadedDocumentsAsync_InvalidApplication_ThrowsNotFound() // Arrange var applicationId = _fixture.Create(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) .Returns(((bool, IEnumerable))default); @@ -1371,9 +1399,10 @@ public async Task GetUploadedDocumentsAsync_InvalidApplication_ThrowsNotFound() null!, null!, _portalRepositories, - null!); + null!, + _identityService); - Task Act() => sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId); + Task Act() => sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT); // Act var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -1388,6 +1417,7 @@ public async Task GetUploadedDocumentsAsync_InvalidUser_ThrowsForbidden() // Arrange var applicationId = _fixture.Create(); var identity = _fixture.Create(); + A.CallTo(() => _identityService.IdentityData).Returns(identity); A.CallTo(() => _documentRepository.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId)) .Returns((false, Enumerable.Empty())); @@ -1400,9 +1430,10 @@ public async Task GetUploadedDocumentsAsync_InvalidUser_ThrowsForbidden() null!, null!, _portalRepositories, - null!); + null!, + _identityService); - Task Act() => sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, identity.UserId); + Task Act() => sut.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT); // Act var error = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -1422,10 +1453,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRoleConsentAsync(notExistingId, _fixture.Create(), _identity.UserId, _identity.CompanyId) + async Task Act() => await sut.SubmitRoleConsentAsync(notExistingId, _fixture.Create()) .ConfigureAwait(false); // Arrange @@ -1442,10 +1473,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create(), _identity.UserId, _identity.CompanyId) + async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create()) .ConfigureAwait(false); // Arrange @@ -1472,10 +1503,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create(), _identity.UserId, _identity.CompanyId) + async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, _fixture.Create()) .ConfigureAwait(false); // Arrange @@ -1513,10 +1544,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, consents, _identity.UserId, _identity.CompanyId) + async Task Act() => await sut.SubmitRoleConsentAsync(applicationId, consents) .ConfigureAwait(false); // Arrange @@ -1590,10 +1621,10 @@ public async Task SubmitRoleConsentsAsync_WithValidData_CallsExpected() removedCompanyRoleIds = companyRoleIds; }); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - await sut.SubmitRoleConsentAsync(applicationId, consents, _identity.UserId, _identity.CompanyId).ConfigureAwait(false); + await sut.SubmitRoleConsentAsync(applicationId, consents).ConfigureAwait(false); // Arrange A.CallTo(() => _consentRepository.AttachAndModifiesConsents(A>._, A>._)).MustHaveHappened(2, Times.Exactly); @@ -1625,10 +1656,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(notExistingId, _identity.UserId) + async Task Act() => await sut.SubmitRegistrationAsync(notExistingId) .ConfigureAwait(false); // Assert @@ -1714,10 +1745,10 @@ public async Task SubmitRegistrationAsync_WithDocumentId_Success() DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT } }; - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService, _identityService); // Act - await sut.SubmitRegistrationAsync(applicationId, _identity.UserId); + await sut.SubmitRegistrationAsync(applicationId); // Assert A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(applicationId, _identity.UserId, A>.That.IsSameSequenceAs(new[] { DocumentTypeId.COMMERCIAL_REGISTER_EXTRACT }))) @@ -1779,6 +1810,7 @@ public async Task SubmitRegistrationAsync_InvalidStatus_ThrowsForbiddenException { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1799,10 +1831,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1820,6 +1852,7 @@ public async Task SubmitRegistrationAsync_AlreadyClosed_ThrowsForbiddenException { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1840,10 +1873,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1858,6 +1891,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyUser_ThrowsForbi { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1874,10 +1908,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1892,6 +1926,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingStreetName_ThrowsConfli { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1908,10 +1943,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1924,6 +1959,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingAddressId_ThrowsConflic { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1934,10 +1970,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1950,6 +1986,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyName_ThrowsConfl { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -1960,10 +1997,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -1976,6 +2013,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingUniqueId_ThrowsConflict { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); var agreementConsents = new List<(Guid AgreementId, ConsentStatusId ConsentStatusId)> @@ -1986,10 +2024,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2002,6 +2040,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCompanyRoleId_ThrowsCon { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var agreementConsents = new List<(Guid AgreementId, ConsentStatusId ConsentStatusId)> @@ -2012,10 +2051,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2028,6 +2067,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingAgreementandConsent_Thr { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2035,10 +2075,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2051,6 +2091,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCity_ThrowsConflictExce { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2061,10 +2102,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2077,6 +2118,7 @@ public async Task SubmitRegistrationAsync_WithNotExistingCountry_ThrowsConflictE { // Arrange var userId = Guid.NewGuid(); + A.CallTo(() => _identityService.IdentityData).Returns(_identity with { UserId = userId }); var applicationId = _fixture.Create(); var uniqueIds = _fixture.CreateMany(3).ToImmutableArray(); var companyRoleIds = _fixture.CreateMany(3).ToImmutableArray(); @@ -2088,10 +2130,10 @@ 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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), _mailingService, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.SubmitRegistrationAsync(applicationId, userId) + async Task Act() => await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2123,10 +2165,10 @@ public async Task SubmitRegistrationAsync_WithUserEmail_SendsMail() }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns(new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, "test@mail.de", documents, companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, null!, _portalRepositories, _checklistService, _identityService); // Act - var result = await sut.SubmitRegistrationAsync(applicationId, _identity.UserId) + var result = await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2161,10 +2203,10 @@ public async Task SubmitRegistrationAsync_WithoutUserEmail_DoesntSendMail() }; A.CallTo(() => _applicationRepository.GetOwnCompanyApplicationUserEmailDataAsync(A._, A._, A>._)) .Returns(new CompanyApplicationUserEmailData(CompanyApplicationStatusId.VERIFY, true, null, documents, companyData, agreementConsents)); - var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, A.Fake>(), _portalRepositories, _checklistService); + var sut = new RegistrationBusinessLogic(Options.Create(settings), _mailingService, null!, null!, null!, A.Fake>(), _portalRepositories, _checklistService, _identityService); // Act - var result = await sut.SubmitRegistrationAsync(applicationId, _identity.UserId) + var result = await sut.SubmitRegistrationAsync(applicationId) .ConfigureAwait(false); // Assert @@ -2196,7 +2238,9 @@ public async Task GetCompanyIdentifiers_ReturnsExpectedOutput() null!, null!, _portalRepositories, - null!); + null!, + _identityService); + // Act var result = await sut.GetCompanyIdentifiers(_fixture.Create()).ConfigureAwait(false); @@ -2225,7 +2269,8 @@ public async Task GetCompanyIdentifiers_InvalidCountry_Throws() null!, null!, _portalRepositories, - null!); + null!, + _identityService); var countryCode = _fixture.Create(); @@ -2249,10 +2294,10 @@ 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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - var result = await sut.GetRegistrationDataAsync(_existingApplicationId, _identity.CompanyId).ConfigureAwait(false); + var result = await sut.GetRegistrationDataAsync(_existingApplicationId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -2294,10 +2339,10 @@ 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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - var Act = () => sut.GetRegistrationDataAsync(applicationId, _identity.CompanyId); + var Act = () => sut.GetRegistrationDataAsync(applicationId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -2313,10 +2358,10 @@ 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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - var Act = () => sut.GetRegistrationDataAsync(applicationId, _identity.CompanyId); + var Act = () => sut.GetRegistrationDataAsync(applicationId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -2332,10 +2377,10 @@ 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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - var Act = () => sut.GetRegistrationDataAsync(applicationId, _identity.CompanyId); + var Act = () => sut.GetRegistrationDataAsync(applicationId); // Assert var result = await Assert.ThrowsAsync(Act).ConfigureAwait(false); @@ -2352,7 +2397,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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); //Act var result = await sut.GetRegistrationDocumentAsync(documentId).ConfigureAwait(false); @@ -2371,7 +2416,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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); //Act var Act = () => sut.GetRegistrationDocumentAsync(documentId); @@ -2389,7 +2434,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!); + var sut = new RegistrationBusinessLogic(_options, null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); //Act var Act = () => sut.GetRegistrationDocumentAsync(documentId); @@ -2411,10 +2456,10 @@ public async Task GetDocumentAsync_WithValidData_ReturnsExpected() .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!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - var result = await sut.GetDocumentContentAsync(documentId, _identity.UserId).ConfigureAwait(false); + var result = await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); // Assert result.Should().NotBeNull(); @@ -2430,10 +2475,10 @@ public async Task GetDocumentAsync_WithoutDocument_ThrowsNotFoundException() var content = new byte[7]; A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.UserId)) .ReturnsLazily(() => new ValueTuple(Guid.Empty, false)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.GetDocumentContentAsync(documentId, _identity.UserId).ConfigureAwait(false); + async Task Act() => await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); @@ -2447,10 +2492,10 @@ public async Task GetDocumentAsync_WithWrongUser_ThrowsForbiddenException() var documentId = Guid.NewGuid(); A.CallTo(() => _documentRepository.GetDocumentIdWithCompanyUserCheckAsync(documentId, _identity.UserId)) .ReturnsLazily(() => new ValueTuple(documentId, false)); - var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!); + var sut = new RegistrationBusinessLogic(Options.Create(new RegistrationSettings()), null!, null!, null!, null!, null!, _portalRepositories, null!, _identityService); // Act - async Task Act() => await sut.GetDocumentContentAsync(documentId, _identity.UserId).ConfigureAwait(false); + async Task Act() => await sut.GetDocumentContentAsync(documentId).ConfigureAwait(false); // Assert var ex = await Assert.ThrowsAsync(Act); diff --git a/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs b/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs index 49636663fc..384b1c7d36 100644 --- a/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs +++ b/tests/registration/Registration.Service.Tests/Controller/RegistrationControllerTest.cs @@ -96,14 +96,14 @@ public async Task GetUploadedDocumentsAsync_ReturnsExpectedResult() var applicationId = _fixture.Create(); var uploadDocuments = _fixture.CreateMany(3); - A.CallTo(() => _registrationBusinessLogicFake.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, _identity.UserId)) + A.CallTo(() => _registrationBusinessLogicFake.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT)) .Returns(uploadDocuments); //Act var result = await _controller.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT).ConfigureAwait(false); //Assert - A.CallTo(() => _registrationBusinessLogicFake.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT, _identity.UserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _registrationBusinessLogicFake.GetUploadedDocumentsAsync(applicationId, DocumentTypeId.APP_CONTRACT)).MustHaveHappenedOnceExactly(); result.Should().HaveSameCount(uploadDocuments); result.Should().ContainInOrder(uploadDocuments); @@ -115,14 +115,14 @@ public async Task SubmitCompanyRoleConsentToAgreementsAsync_WithValidData_Return // Arrange var applicationId = _fixture.Create(); var data = _fixture.Create(); - A.CallTo(() => _registrationBusinessLogicFake.SubmitRoleConsentAsync(applicationId, data, _identity.UserId, _identity.CompanyId)) + A.CallTo(() => _registrationBusinessLogicFake.SubmitRoleConsentAsync(applicationId, data)) .Returns(1); //Act var result = await this._controller.SubmitCompanyRoleConsentToAgreementsAsync(applicationId, data).ConfigureAwait(false); // Assert - A.CallTo(() => _registrationBusinessLogicFake.SubmitRoleConsentAsync(applicationId, data, _identity.UserId, _identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _registrationBusinessLogicFake.SubmitRoleConsentAsync(applicationId, data)).MustHaveHappenedOnceExactly(); result.Should().Be(1); } @@ -155,14 +155,14 @@ public async Task GetDocumentContentFileAsync_WithValidData_ReturnsOk() const string contentType = "application/pdf"; var id = Guid.NewGuid(); var content = Encoding.UTF8.GetBytes("This is just test content"); - A.CallTo(() => _registrationBusinessLogicFake.GetDocumentContentAsync(id, _identity.UserId)) + A.CallTo(() => _registrationBusinessLogicFake.GetDocumentContentAsync(id)) .Returns((fileName, content, contentType)); //Act var result = await this._controller.GetDocumentContentFileAsync(id).ConfigureAwait(false); //Assert - A.CallTo(() => _registrationBusinessLogicFake.GetDocumentContentAsync(id, _identity.UserId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _registrationBusinessLogicFake.GetDocumentContentAsync(id)).MustHaveHappenedOnceExactly(); result.Should().BeOfType(); ((FileContentResult)result).ContentType.Should().Be(contentType); } @@ -191,14 +191,14 @@ public async Task InviteNewUserAsync_WithValidData_ReturnsExpected() var applicationId = _fixture.Create(); var creationInfo = _fixture.Create(); - A.CallTo(() => _registrationBusinessLogicFake.InviteNewUserAsync(A._, A._, A<(Guid, Guid)>._)) + A.CallTo(() => _registrationBusinessLogicFake.InviteNewUserAsync(A._, A._)) .Returns(1); //Act var result = await this._controller.InviteNewUserAsync(applicationId, creationInfo).ConfigureAwait(false); // Assert - A.CallTo(() => _registrationBusinessLogicFake.InviteNewUserAsync(applicationId, creationInfo, new(_identity.UserId, _identity.CompanyId))).MustHaveHappenedOnceExactly(); + A.CallTo(() => _registrationBusinessLogicFake.InviteNewUserAsync(applicationId, creationInfo)).MustHaveHappenedOnceExactly(); result.Should().Be(1); } @@ -207,14 +207,14 @@ public async Task GetApplicationsWithStatusAsync_WithValidData_ReturnsExpected() { // Arrange var companyApplicationWithStatus = _fixture.CreateMany(2); - A.CallTo(() => _registrationBusinessLogicFake.GetAllApplicationsForUserWithStatus(_identity.CompanyId)) + A.CallTo(() => _registrationBusinessLogicFake.GetAllApplicationsForUserWithStatus()) .Returns(companyApplicationWithStatus.ToAsyncEnumerable()); //Act var result = await this._controller.GetApplicationsWithStatusAsync().ToListAsync().ConfigureAwait(false); // Assert - A.CallTo(() => _registrationBusinessLogicFake.GetAllApplicationsForUserWithStatus(_identity.CompanyId)).MustHaveHappenedOnceExactly(); + A.CallTo(() => _registrationBusinessLogicFake.GetAllApplicationsForUserWithStatus()).MustHaveHappenedOnceExactly(); result.Should().HaveCount(2); } }