From 1c38008e970e48b4b9a2bcc0283fc27ea1f9e606 Mon Sep 17 00:00:00 2001 From: Oscar Morales Date: Wed, 21 May 2025 12:45:21 -0600 Subject: [PATCH] Use Blueprint.Mongo package in Role and Permission services --- .../Controllers/ModuleController.cs | 2 +- .../Controllers/PermissionController.cs | 107 +++----- .../Controllers/RoleController.cs | 114 +++----- ...ssionService.cs => IPermissionProvider.cs} | 16 +- .../{IRoleService.cs => IRoleProvider.cs} | 16 +- .../Onboarding/PermissionProvider.cs | 153 +++++++++++ .../Providers/Onboarding/PermissionService.cs | 234 ---------------- .../Providers/Onboarding/RoleProvider.cs | 170 ++++++++++++ .../Providers/Onboarding/RoleService.cs | 251 ------------------ .../ServiceCollectionExtensions.cs | 6 +- 10 files changed, 403 insertions(+), 666 deletions(-) rename Core.Thalos.Provider/Contracts/{IPermissionService.cs => IPermissionProvider.cs} (75%) rename Core.Thalos.Provider/Contracts/{IRoleService.cs => IRoleProvider.cs} (77%) create mode 100644 Core.Thalos.Provider/Providers/Onboarding/PermissionProvider.cs delete mode 100644 Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs create mode 100644 Core.Thalos.Provider/Providers/Onboarding/RoleProvider.cs delete mode 100644 Core.Thalos.Provider/Providers/Onboarding/RoleService.cs diff --git a/Core.Thalos.DAL.API/Controllers/ModuleController.cs b/Core.Thalos.DAL.API/Controllers/ModuleController.cs index fb0966e..05193ad 100644 --- a/Core.Thalos.DAL.API/Controllers/ModuleController.cs +++ b/Core.Thalos.DAL.API/Controllers/ModuleController.cs @@ -139,7 +139,7 @@ namespace LSA.Core.Kerberos.API.Controllers { if (_id != entity._Id?.ToString()) { - return BadRequest("User ID mismatch"); + return BadRequest("Module ID mismatch"); } var result = await service.UpdateModule(entity, cancellationToken).ConfigureAwait(false); diff --git a/Core.Thalos.DAL.API/Controllers/PermissionController.cs b/Core.Thalos.DAL.API/Controllers/PermissionController.cs index 2caec4c..e2c86e7 100644 --- a/Core.Thalos.DAL.API/Controllers/PermissionController.cs +++ b/Core.Thalos.DAL.API/Controllers/PermissionController.cs @@ -5,14 +5,15 @@ // *********************************************************************** using Asp.Versioning; +using Core.Blueprint.Mongo; using Core.Thalos.Adapters; using Core.Thalos.Adapters.Attributes; using Core.Thalos.Adapters.Common.Constants; -using Core.Thalos.Adapters.Common.Enums; -using Core.Thalos.Domain.Contexts.Onboarding.Request; using Core.Thalos.Provider.Contracts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Microsoft.Graph; +using PermissionRequest = Core.Thalos.Domain.Contexts.Onboarding.Request.PermissionRequest; namespace LSA.Core.Kerberos.API.Controllers { @@ -24,7 +25,7 @@ namespace LSA.Core.Kerberos.API.Controllers [Produces(MimeTypes.ApplicationJson)] [Consumes(MimeTypes.ApplicationJson)] [ApiController] - public class PermissionController(IPermissionService service, ILogger logger) : ControllerBase + public class PermissionController(IPermissionProvider service) : ControllerBase { /// /// Gets all the permissions. @@ -39,19 +40,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Read, RoleManagement.Read")] - public async Task GetAllPermissionsAsync() + public async Task GetAllPermissionsAsync(CancellationToken cancellationToken) { - try - { - var result = await service.GetAllPermissionsService(); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in GetAllPermissionsAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.GetAllPermissions(cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -69,29 +61,15 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Read")] - public async Task GetAllPermissionsByList([FromBody] string[] permissions) + public async Task GetAllPermissionsByList([FromBody] string[] permissions, CancellationToken cancellationToken) { if (permissions == null || !permissions.Any()) { - return BadRequest("Permission identifiers are required."); + return BadRequest("Module identifiers are required."); } - try - { - var result = await service.GetAllPermissionsByListService(permissions); - - if (result == null || !result.Any()) - { - return NotFound("No permissions found for the given identifiers."); - } - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in GetAllPermissionsByList"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.GetAllPermissionsByList(permissions, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -109,21 +87,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Read")] - public async Task GetPermissionByIdAsync([FromRoute] string id) + public async Task GetPermissionByIdAsync([FromRoute] string _id, CancellationToken cancellationToken) { - try - { - var result = await service.GetPermissionByIdService(id); + var result = await service.GetPermissionById(_id, cancellationToken).ConfigureAwait(false); - if (result is null) return NotFound($"permission with id: '{id}' not found"); - - return Ok(result); - } - catch (Exception ex) + if (result == null) { - logger.LogError(ex, "Error in GetPermissionByIdAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); + return NotFound("Entity not found"); } + + return Ok(result); } /// @@ -138,18 +111,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status201Created)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Write")] - public async Task CreatePermissionAsync([FromBody] PermissionRequest newPermission) + public async Task CreatePermissionAsync([FromBody] PermissionRequest newPermission, CancellationToken cancellationToken) { - try - { - var result = await service.CreatePermissionService(newPermission).ConfigureAwait(false); - return Created("CreatedWithIdService", result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in CreatePermissionAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.CreatePermission(newPermission, cancellationToken).ConfigureAwait(false); + return Created("CreatedWithIdAsync", result); } /// @@ -169,19 +134,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Write")] - public async Task UpdatePermissionAsync(PermissionAdapter entity, string id) + public async Task UpdatePermissionAsync([FromRoute] string _id, PermissionAdapter entity, CancellationToken cancellationToken) { - try + if (_id != entity._Id?.ToString()) { - var result = await service.UpdatePermissionService(entity, id); + return BadRequest("Permission ID mismatch"); + } - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in UpdatePermissionAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.UpdatePermission(entity, cancellationToken).ConfigureAwait(false); + + return Ok(result); } /// @@ -201,19 +163,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(PermissionAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("PermissionManagement.Write")] - public async Task ChangePermissionStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus) + public async Task ChangePermissionStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken) { - try - { - var result = await service.ChangePermissionStatusService(id, newStatus); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in ChangePermissionStatus"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.ChangePermissionStatus(id, newStatus, cancellationToken).ConfigureAwait(false); + return Ok(result); } } } diff --git a/Core.Thalos.DAL.API/Controllers/RoleController.cs b/Core.Thalos.DAL.API/Controllers/RoleController.cs index f816c49..63f3930 100644 --- a/Core.Thalos.DAL.API/Controllers/RoleController.cs +++ b/Core.Thalos.DAL.API/Controllers/RoleController.cs @@ -12,6 +12,7 @@ using Core.Thalos.Domain.Contexts.Onboarding.Request; using Core.Thalos.Provider.Contracts; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using StatusEnum = Core.Blueprint.Mongo.StatusEnum; namespace LSA.Core.Kerberos.API.Controllers { @@ -23,7 +24,7 @@ namespace LSA.Core.Kerberos.API.Controllers [Produces(MimeTypes.ApplicationJson)] [Consumes(MimeTypes.ApplicationJson)] [ApiController] - public class RoleController(IRoleService service, ILogger logger) : ControllerBase + public class RoleController(IRoleProvider service) : ControllerBase { /// /// Gets all the roles. @@ -36,19 +37,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Read")] - public async Task GetAllRolesAsync() + public async Task GetAllRolesAsync(CancellationToken cancellationToken) { - try - { - var result = await service.GetAllRolesService(); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in GetAllRolesAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.GetAllRoles(cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -64,21 +56,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Read")] - public async Task GetRoleByIdAsync([FromRoute] string id) + public async Task GetRoleByIdAsync([FromRoute] string _id, CancellationToken cancellationToken) { - try - { - var result = await service.GetRoleByIdService(id); + var result = await service.GetRoleById(_id, cancellationToken).ConfigureAwait(false); - if (result is null) return NotFound($"role with id: '{id}' not found"); - - return Ok(result); - } - catch (Exception ex) + if (result == null) { - logger.LogError(ex, "Error in GetRoleByIdAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); + return NotFound("Entity not found"); } + + return Ok(result); } /// @@ -93,19 +80,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status201Created)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Write")] - public async Task CreateRoleAsync([FromBody] RoleRequest newRole) + public async Task CreateRoleAsync([FromBody] RoleRequest newRole, CancellationToken cancellationToken) { - try - { - var result = await service.CreateRoleService(newRole).ConfigureAwait(false); - - return Created("CreatedWithIdService", result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in CreateRoleAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.CreateRole(newRole, cancellationToken).ConfigureAwait(false); + return Created("CreatedWithIdAsync", result); } /// @@ -123,19 +101,16 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Write")] - public async Task UpdateRoleAsync([FromBody] RoleAdapter entity, [FromRoute] string id) + public async Task UpdateRoleAsync([FromRoute] string _id, [FromBody] RoleAdapter entity, CancellationToken cancellationToken) { - try + if (_id != entity._Id?.ToString()) { - var result = await service.UpdateRoleService(entity, id); + return BadRequest("Role ID mismatch"); + } - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in UpdateRoleAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.UpdateRole(entity, cancellationToken).ConfigureAwait(false); + + return Ok(result); } /// @@ -153,20 +128,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Write")] - public async Task ChangeRoleStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus) + public async Task ChangeRoleStatus([FromRoute] string id, [FromRoute] StatusEnum newStatus, CancellationToken cancellationToken) { - try - { - var result = await service.ChangeRoleStatusService(id, newStatus); - - return Ok(result); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in ChangeRoleStatus"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } - + var result = await service.ChangeRoleStatus(id, newStatus, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -183,20 +148,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Write")] - public async Task AddApplicationToRoleAsync([FromRoute] string roleId, - [FromRoute] ApplicationsEnum application) + public async Task AddApplicationToRoleAsync([FromRoute] string roleId, [FromRoute] ApplicationsEnum application, CancellationToken cancellationToken) { - try - { - var updatedRole = await service.AddApplicationToRoleService(roleId, application); - - return Ok(updatedRole); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in AddApplicationToRoleAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.AddApplicationToRole(roleId, application, cancellationToken).ConfigureAwait(false); + return Ok(result); } /// @@ -213,19 +168,10 @@ namespace LSA.Core.Kerberos.API.Controllers [ProducesResponseType(typeof(RoleAdapter), StatusCodes.Status200OK)] [Authorize(AuthenticationSchemes = Schemes.DefaultScheme)] [Permission("RoleManagement.Write")] - public async Task RemoveApplicationFromRoleAsync([FromRoute] string roleId, - [FromRoute] ApplicationsEnum application) + public async Task RemoveApplicationFromRoleAsync([FromRoute] string roleId, [FromRoute] ApplicationsEnum application, CancellationToken cancellationToken) { - try - { - var updatedRole = await service.RemoveApplicationFromRoleService(roleId, application); - return Ok(updatedRole); - } - catch (Exception ex) - { - logger.LogError(ex, "Error in RemoveApplicationFromRoleAsync"); - return StatusCode(500, $"Internal server error, ErrorMessage: {ex.Message}"); - } + var result = await service.RemoveApplicationFromRole(roleId, application, cancellationToken).ConfigureAwait(false); + return Ok(result); } } } diff --git a/Core.Thalos.Provider/Contracts/IPermissionService.cs b/Core.Thalos.Provider/Contracts/IPermissionProvider.cs similarity index 75% rename from Core.Thalos.Provider/Contracts/IPermissionService.cs rename to Core.Thalos.Provider/Contracts/IPermissionProvider.cs index b0d6381..dd34895 100644 --- a/Core.Thalos.Provider/Contracts/IPermissionService.cs +++ b/Core.Thalos.Provider/Contracts/IPermissionProvider.cs @@ -3,13 +3,13 @@ // AgileWebs // // *********************************************************************** +using Core.Blueprint.Mongo; using Core.Thalos.Adapters; -using Core.Thalos.Adapters.Common.Enums; using Core.Thalos.Domain.Contexts.Onboarding.Request; namespace Core.Thalos.Provider.Contracts { - public interface IPermissionService + public interface IPermissionProvider { /// /// Creates a new Permission. @@ -17,7 +17,7 @@ namespace Core.Thalos.Provider.Contracts /// The Permission to be created. /// A representing /// the asynchronous execution of the service. - Task CreatePermissionService(PermissionRequest newPermission); + ValueTask CreatePermission(PermissionRequest newPermission, CancellationToken cancellationToken); /// /// Gets an Permission by identifier. @@ -25,14 +25,14 @@ namespace Core.Thalos.Provider.Contracts /// The Permission identifier. /// A representing /// the asynchronous execution of the service. - Task GetPermissionByIdService(string id); + ValueTask GetPermissionById(string _id, CancellationToken cancellationToken); /// /// Gets all the roles. /// /// A representing /// the asynchronous execution of the service. - Task> GetAllPermissionsService(); + ValueTask> GetAllPermissions(CancellationToken cancellationToken); /// /// Gets all the permissions by permissions identifier list. @@ -40,7 +40,7 @@ namespace Core.Thalos.Provider.Contracts /// The list of permissions identifiers. /// A representing /// the asynchronous execution of the service. - Task> GetAllPermissionsByListService(string[] permissions); + ValueTask> GetAllPermissionsByList(string[] permissions, CancellationToken cancellationToken); /// /// Changes the status of the permission. @@ -50,7 +50,7 @@ namespace Core.Thalos.Provider.Contracts /// The updated entity. /// A representing /// the asynchronous execution of the service. - Task ChangePermissionStatusService(string id, StatusEnum newStatus); + ValueTask ChangePermissionStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken); /// /// Updates a Permission by id. @@ -59,6 +59,6 @@ namespace Core.Thalos.Provider.Contracts /// The Permission identifier. /// A representing /// the asynchronous execution of the service. - Task UpdatePermissionService(PermissionAdapter entity, string id); + ValueTask UpdatePermission(PermissionAdapter entity, CancellationToken cancellationToken); } } diff --git a/Core.Thalos.Provider/Contracts/IRoleService.cs b/Core.Thalos.Provider/Contracts/IRoleProvider.cs similarity index 77% rename from Core.Thalos.Provider/Contracts/IRoleService.cs rename to Core.Thalos.Provider/Contracts/IRoleProvider.cs index 2bb20c8..3d516d7 100644 --- a/Core.Thalos.Provider/Contracts/IRoleService.cs +++ b/Core.Thalos.Provider/Contracts/IRoleProvider.cs @@ -9,7 +9,7 @@ using Core.Thalos.Domain.Contexts.Onboarding.Request; namespace Core.Thalos.Provider.Contracts { - public interface IRoleService + public interface IRoleProvider { /// /// Creates a new Role. @@ -17,7 +17,7 @@ namespace Core.Thalos.Provider.Contracts /// The Role to be created. /// A representing /// the asynchronous execution of the service. - Task CreateRoleService(RoleRequest newRole); + ValueTask CreateRole(RoleRequest newRole, CancellationToken cancellationToken); /// /// Gets an Role by identifier. @@ -25,14 +25,14 @@ namespace Core.Thalos.Provider.Contracts /// The Role identifier. /// A representing /// the asynchronous execution of the service. - Task GetRoleByIdService(string id); + ValueTask GetRoleById(string _id, CancellationToken cancellationToken); /// /// Gets all the roles. /// /// A representing /// the asynchronous execution of the service. - Task> GetAllRolesService(); + ValueTask> GetAllRoles(CancellationToken cancellationToken); /// /// Changes the status of the role. @@ -42,7 +42,7 @@ namespace Core.Thalos.Provider.Contracts /// The updated entity. /// A representing /// the asynchronous execution of the service. - Task ChangeRoleStatusService(string id, StatusEnum newStatus); + ValueTask ChangeRoleStatus(string id, Core.Blueprint.Mongo.StatusEnum newStatus, CancellationToken cancellationToken); /// /// Updates a Role by id. @@ -51,7 +51,7 @@ namespace Core.Thalos.Provider.Contracts /// The Role identifier. /// A representing /// the asynchronous execution of the service. - Task UpdateRoleService(RoleAdapter entity, string id); + ValueTask UpdateRole(RoleAdapter entity, CancellationToken cancellationToken); /// /// Adds an application to the role's list of applications. @@ -59,7 +59,7 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the role to which the application will be added. /// The application enum value to add. /// A representing the asynchronous operation, with the updated role object. - Task AddApplicationToRoleService(string roleId, ApplicationsEnum application); + ValueTask AddApplicationToRole(string roleId, ApplicationsEnum application, CancellationToken cancellationToken); /// /// Removes an application from the role's list of applications. @@ -67,6 +67,6 @@ namespace Core.Thalos.Provider.Contracts /// The identifier of the role from which the application will be removed. /// The application enum value to remove. /// A representing the asynchronous operation, with the updated role object. - Task RemoveApplicationFromRoleService(string roleId, ApplicationsEnum application); + ValueTask RemoveApplicationFromRole(string roleId, ApplicationsEnum application, CancellationToken cancellationToken); } } diff --git a/Core.Thalos.Provider/Providers/Onboarding/PermissionProvider.cs b/Core.Thalos.Provider/Providers/Onboarding/PermissionProvider.cs new file mode 100644 index 0000000..77a2768 --- /dev/null +++ b/Core.Thalos.Provider/Providers/Onboarding/PermissionProvider.cs @@ -0,0 +1,153 @@ +// *********************************************************************** +// +// AgileWebs +// +// *********************************************************************** +using Core.Thalos.Adapters; +using Core.Blueprint.Mongo; +using Core.Blueprint.Redis; +using Core.Blueprint.Redis.Helpers; +using Mapster; +using Microsoft.Extensions.Options; +using MongoDB.Driver; +using Core.Thalos.Provider.Contracts; +using Core.Thalos.Domain.Contexts.Onboarding.Request; + +namespace Core.Thalos.Provider.Providers.Onboarding +{ + /// + /// Handles all services and business rules related to . + /// + public class PermissionProvider : IPermissionProvider + { + private readonly CollectionRepository repository; + private readonly CacheSettings cacheSettings; + private readonly IRedisCacheProvider cacheProvider; + + public PermissionProvider(CollectionRepository repository, + IRedisCacheProvider cacheProvider, IOptions cacheSettings) + { + this.repository = repository; + this.repository.CollectionInitialization(); + this.cacheSettings = cacheSettings.Value; + this.cacheProvider = cacheProvider; + } + + /// + /// Creates a new Permission. + /// + /// The Permission to be created. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask CreatePermission(PermissionRequest newPermission, CancellationToken cancellationToken) + { + var permissionCollection = newPermission.Adapt(); + + await repository.InsertOneAsync(permissionCollection); + + return permissionCollection; + } + + /// + /// Gets an Permission by identifier. + /// + /// The Permission identifier. + /// A representing + /// the asynchronous execution of the service.0 + public async ValueTask GetPermissionById(string _id, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetPermissionById", _id); + var cachedData = await cacheProvider.GetAsync(cacheKey); + + if (cachedData is not null) { return cachedData; } + + var permission = await repository.FindByIdAsync(_id); + + await cacheProvider.SetAsync(cacheKey, permission); + + return permission; + } + + /// + /// Gets all the permissions. + /// + /// A representing + /// the asynchronous execution of the service. + public async ValueTask> GetAllPermissions(CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissions"); + var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; + + if (cachedData.Any()) return cachedData; + + var permissions = await repository.AsQueryable(); + + await cacheProvider.SetAsync(cacheKey, permissions); + + return permissions; + } + + /// + /// Gets all the permissions by permissions identifier list. + /// + /// The list of permissions identifiers. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask> GetAllPermissionsByList(string[] permissions, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsByList", permissions); + + var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; + + if (cachedData.Any()) return cachedData; + + var builder = Builders.Filter; + var filters = new List>(); + + if (permissions == null || !permissions.Any()) + { + filters.Add(builder.In(x => x.Id, permissions)); + } + + var finalFilter = filters.Any() ? builder.And(filters) : builder.Empty; + + var permissionsList = await repository.FilterByMongoFilterAsync(finalFilter); + + await cacheProvider.SetAsync(cacheKey, permissionsList); + + return permissionsList; + } + + + /// + /// Changes the status of the permission. + /// + /// The permission identifier. + /// The new status of the permission. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask ChangePermissionStatus(string id, StatusEnum newStatus, CancellationToken cancellationToken) + { + var entity = await repository.FindByIdAsync(id); + entity.Status = newStatus; + + await repository.ReplaceOneAsync(entity); + + return entity; + } + + /// + /// Updates a Permission by id. + /// + /// The Permission to be updated. + /// The Permission identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask UpdatePermission(PermissionAdapter entity, CancellationToken cancellationToken) + { + await repository.ReplaceOneAsync(entity); + + return entity; + } + } +} diff --git a/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs b/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs deleted file mode 100644 index e2abf74..0000000 --- a/Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs +++ /dev/null @@ -1,234 +0,0 @@ -// *********************************************************************** -// -// AgileWebs -// -// *********************************************************************** -using Core.Thalos.Adapters; -using Core.Thalos.Adapters.Common.Constants; -using Core.Thalos.Adapters.Common.Enums; -using Core.Thalos.Domain.Contexts.Onboarding.Mappers; -using Core.Thalos.Domain.Contexts.Onboarding.Request; -using Core.Thalos.Infraestructure.Caching.Configs; -using Core.Thalos.Infraestructure.Caching.Contracts; -using Core.Thalos.Provider.Contracts; -using LSA.Core.Dapper.Service.Caching; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using MongoDB.Bson; -using MongoDB.Driver; - -namespace Core.Thalos.Provider.Providers.Onboarding -{ - /// - /// Handles all services and business rules related to . - /// - public class PermissionService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, - IOptions cacheSettings, IMongoDatabase database) : IPermissionService - { - private readonly CacheSettings _cacheSettings = cacheSettings.Value; - - /// - /// Creates a new Permission. - /// - /// The Permission to be created. - /// A representing - /// the asynchronous execution of the service. - public async Task CreatePermissionService(PermissionRequest newPermission) - { - try - { - var entity = newPermission.ToAdapter(httpContextAccessor); - await database.GetCollection(CollectionNames.Permission).InsertOneAsync(entity); - entity.Id = (entity as dynamic ?? "").Id.ToString(); - - return entity; - } - catch (Exception ex) - { - logger.LogError(ex, $"CreatePermissionService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets an Permission by identifier. - /// - /// The Permission identifier. - /// A representing - /// the asynchronous execution of the service.0 - public async Task GetPermissionByIdService(string id) - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetPermissionByIdService", id); - var cachedData = await cacheService.GetAsync(cacheKey); - - if (cachedData is not null) { return cachedData; } - - try - { - var filter = Builders.Filter.And( - Builders.Filter.Eq("_id", ObjectId.Parse(id)), - Builders.Filter.Eq("status", StatusEnum.Active.ToString()) - ); - - var permission = await database.GetCollection(CollectionNames.Permission) - .Find(filter) - .FirstOrDefaultAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, permission, cacheDuration); - - return permission; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetPermissionByIdService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets all the permissions. - /// - /// A representing - /// the asynchronous execution of the service. - public async Task> GetAllPermissionsService() - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsService"); - var cachedData = await cacheService.GetAsync>(cacheKey) ?? []; - - if (cachedData.Any()) return cachedData; - - try - { - var filter = Builders.Filter.Eq("status", StatusEnum.Active.ToString()); - - var roles = await database.GetCollection(CollectionNames.Permission) - .Find(filter) - .ToListAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, roles, cacheDuration); - - return roles; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetAllPermissionsService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets all the permissions by permissions identifier list. - /// - /// The list of permissions identifiers. - /// A representing - /// the asynchronous execution of the service. - public async Task> GetAllPermissionsByListService(string[] permissions) - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsByListService", permissions); - - var cachedData = await cacheService.GetAsync>(cacheKey); - - if (cachedData != null && cachedData.Any()) return cachedData; - - try - { - var objectIds = permissions.Select(id => ObjectId.Parse(id)).ToArray(); - - var filter = Builders.Filter.In("_id", objectIds) - & Builders.Filter.Eq("status", StatusEnum.Active.ToString()); - - var roles = await database.GetCollection(CollectionNames.Permission) - .Find(filter) - .ToListAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, roles, cacheDuration); - - return roles; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetAllPermissionsByListService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - - /// - /// Changes the status of the permission. - /// - /// The permission identifier. - /// The new status of the permission. - /// A representing - /// the asynchronous execution of the service. - public async Task ChangePermissionStatusService(string id, StatusEnum newStatus) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - //.Set(v => v.Status, newStatus) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.Permission).UpdateOneAsync(filter, update); - - var updatedPermission = await database.GetCollection(CollectionNames.Permission) - .Find(filter) - .FirstOrDefaultAsync(); - - return updatedPermission; - } - catch (Exception ex) - { - logger.LogError(ex, $"ChangePermissionStatusService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Updates a Permission by id. - /// - /// The Permission to be updated. - /// The Permission identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task UpdatePermissionService(PermissionAdapter entity, string id) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - .Set(v => v.Name, entity.Name) - .Set(v => v.Description, entity.Description) - .Set(v => v.AccessLevel, entity.AccessLevel) - .Set(v => v.Status, entity.Status) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.Permission).UpdateOneAsync(filter, update); - - var updatedPermission = await database.GetCollection(CollectionNames.Permission) - .Find(filter) - .FirstOrDefaultAsync(); - - return updatedPermission; - } - catch (Exception ex) - { - logger.LogError(ex, $"UpdatePermissionService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - } -} diff --git a/Core.Thalos.Provider/Providers/Onboarding/RoleProvider.cs b/Core.Thalos.Provider/Providers/Onboarding/RoleProvider.cs new file mode 100644 index 0000000..70b009d --- /dev/null +++ b/Core.Thalos.Provider/Providers/Onboarding/RoleProvider.cs @@ -0,0 +1,170 @@ +// *********************************************************************** +// +// AgileWebs +// +// *********************************************************************** +using Core.Thalos.Adapters; +using Core.Thalos.Adapters.Common.Enums; +using Core.Blueprint.Mongo; +using Core.Blueprint.Redis; +using Core.Blueprint.Redis.Helpers; +using Mapster; +using Microsoft.Extensions.Options; +using MongoDB.Driver; +using Core.Thalos.Provider.Contracts; +using MongoDB.Bson; +using System.Text.RegularExpressions; +using MongoDB.Bson.Serialization; +using Core.Thalos.Domain.Contexts.Onboarding.Request; +using Microsoft.Graph; +using System.ComponentModel.Design; + +namespace Core.Thalos.Provider.Providers.Onboarding +{ + /// + /// Handles all services and business rules related to . + /// + public class RoleProvider : IRoleProvider + { + private readonly CollectionRepository repository; + private readonly CacheSettings cacheSettings; + private readonly IRedisCacheProvider cacheProvider; + + public RoleProvider(CollectionRepository repository, + IRedisCacheProvider cacheProvider, IOptions cacheSettings) + { + this.repository = repository; + this.repository.CollectionInitialization(); + this.cacheSettings = cacheSettings.Value; + this.cacheProvider = cacheProvider; + } + + /// + /// Creates a new Role. + /// + /// The Role to be created. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask CreateRole(RoleRequest newRole, CancellationToken cancellationToken) + { + var roleCollection = newRole.Adapt(); + + await repository.InsertOneAsync(roleCollection); + + return roleCollection; + } + + /// + /// Gets an Role by identifier. + /// + /// The Role identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask GetRoleById(string _id, CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetRoleById", _id); + var cachedData = await cacheProvider.GetAsync(cacheKey); + + if (cachedData is not null) { return cachedData; } + + var role = await repository.FindByIdAsync(_id); + + await cacheProvider.SetAsync(cacheKey, role); + + return role; + } + + /// + /// Gets all the roles. + /// + /// A representing + /// the asynchronous execution of the service. + public async ValueTask> GetAllRoles(CancellationToken cancellationToken) + { + var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllRoles"); + var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; + + if (cachedData.Any()) return cachedData; + + var roles = await repository.AsQueryable(); + + await cacheProvider.SetAsync(cacheKey, roles); + + return roles; + } + + /// + /// Changes the status of the role. + /// + /// The role identifier. + /// The new status of the role. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask ChangeRoleStatus(string id, Core.Blueprint.Mongo.StatusEnum newStatus, CancellationToken cancellationToken) + { + var entity = await repository.FindByIdAsync(id); + entity.Status = newStatus; + + await repository.ReplaceOneAsync(entity); + + return entity; + } + + /// + /// Updates a Role by id. + /// + /// The Role to be updated. + /// The Role identifier. + /// A representing + /// the asynchronous execution of the service. + public async ValueTask UpdateRole(RoleAdapter entity, CancellationToken cancellationToken) + { + await repository.ReplaceOneAsync(entity); + + return entity; + } + + /// + /// Adds an application to the role's list of applications. + /// + /// The identifier of the role to which the application will be added. + /// The application enum value to add. + /// A representing the asynchronous operation, with the updated role object. + public async ValueTask AddApplicationToRole(string roleId, ApplicationsEnum application, CancellationToken cancellationToken) + { + var role = await repository.FindOneAsync( + u => u.Id == roleId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedApplications = role.Applications.Append(application).Distinct().ToArray(); + role.Applications = updatedApplications; + + await repository.ReplaceOneAsync(role); + + return role; + } + + /// + /// Removes an application from the role's list of applications. + /// + /// The identifier of the role from which the application will be removed. + /// The application enum value to remove. + /// A representing the asynchronous operation, with the updated role object. + public async ValueTask RemoveApplicationFromRole(string roleId, ApplicationsEnum application, CancellationToken cancellationToken) + { + var role = await repository.FindOneAsync( + u => u.Id == roleId && + u.Status == Core.Blueprint.Mongo.StatusEnum.Active); + + var updatedApplications = role.Applications + ?.Where(c => c != application) + .ToArray(); + + role.Applications = updatedApplications; + + await repository.ReplaceOneAsync(role); + + return role; + } + } +} diff --git a/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs b/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs deleted file mode 100644 index bd4e0ed..0000000 --- a/Core.Thalos.Provider/Providers/Onboarding/RoleService.cs +++ /dev/null @@ -1,251 +0,0 @@ -// *********************************************************************** -// -// AgileWebs -// -// *********************************************************************** -using Core.Thalos.Adapters; -using Core.Thalos.Adapters.Common.Constants; -using Core.Thalos.Adapters.Common.Enums; -using Core.Thalos.Domain.Contexts.Onboarding.Mappers; -using Core.Thalos.Domain.Contexts.Onboarding.Request; -using Core.Thalos.Infraestructure.Caching.Configs; -using Core.Thalos.Infraestructure.Caching.Contracts; -using Core.Thalos.Provider.Contracts; -using LSA.Core.Dapper.Service.Caching; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using MongoDB.Bson; -using MongoDB.Driver; - -namespace Core.Thalos.Provider.Providers.Onboarding -{ - /// - /// Handles all services and business rules related to . - /// - public class RoleService(ILogger logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, - IOptions cacheSettings, IMongoDatabase database) : IRoleService - { - private readonly CacheSettings _cacheSettings = cacheSettings.Value; - - /// - /// Creates a new Role. - /// - /// The Role to be created. - /// A representing - /// the asynchronous execution of the service. - public async Task CreateRoleService(RoleRequest newRole) - { - try - { - var entity = newRole.ToAdapter(httpContextAccessor); - await database.GetCollection(CollectionNames.Role).InsertOneAsync(entity); - entity.Id = (entity as dynamic ?? "").Id.ToString(); - - return entity; - } - catch (Exception ex) - { - logger.LogError(ex, $"CreateRoleService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets an Role by identifier. - /// - /// The Role identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task GetRoleByIdService(string id) - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetRoleByIdService", id); - var cachedData = await cacheService.GetAsync(cacheKey); - - if (cachedData is not null) { return cachedData; } - try - { - var filter = Builders.Filter.And( - Builders.Filter.Eq("_id", ObjectId.Parse(id)), - Builders.Filter.Eq("status", StatusEnum.Active.ToString()) - ); - - var role = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .FirstOrDefaultAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, role, cacheDuration); - - return role; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetRoleByIdService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Gets all the roles. - /// - /// A representing - /// the asynchronous execution of the service. - public async Task> GetAllRolesService() - { - var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllRolesService"); - var cachedData = await cacheService.GetAsync>(cacheKey) ?? []; - - if (cachedData.Any()) return cachedData; - try - { - var filter = Builders.Filter.Eq("status", StatusEnum.Active.ToString()); - - var roles = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .ToListAsync(); - - var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); - - await cacheService.SetAsync(cacheKey, roles, cacheDuration); - - return roles; - } - catch (Exception ex) - { - logger.LogError(ex, $"GetAllRolesService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Changes the status of the role. - /// - /// The role identifier. - /// The new status of the role. - /// A representing - /// the asynchronous execution of the service. - public async Task ChangeRoleStatusService(string id, StatusEnum newStatus) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - //.Set(v => v.Status, newStatus) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update); - - var updatedRole = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .FirstOrDefaultAsync(); - - return updatedRole; - } - catch (Exception ex) - { - logger.LogError(ex, $"ChangeRoleStatusService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - - /// - /// Updates a Role by id. - /// - /// The Role to be updated. - /// The Role identifier. - /// A representing - /// the asynchronous execution of the service. - public async Task UpdateRoleService(RoleAdapter entity, string id) - { - try - { - var filter = Builders.Filter - .Eq("_id", ObjectId.Parse(id)); - - var update = Builders.Update - .Set(v => v.Name, entity.Name) - .Set(v => v.Description, entity.Description) - .Set(v => v.Applications, entity.Applications) - .Set(v => v.Modules, entity.Modules) - .Set(v => v.Permissions, entity.Permissions) - .Set(v => v.Status, entity.Status) - .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) - .Set(v => v.UpdatedAt, DateTime.UtcNow); - - await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update); - - var updatedRole = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .FirstOrDefaultAsync(); - - return updatedRole; - } - catch (Exception ex) - { - logger.LogError(ex, $"UpdateRoleService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - - } - - /// - /// Adds an application to the role's list of applications. - /// - /// The identifier of the role to which the application will be added. - /// The application enum value to add. - /// A representing the asynchronous operation, with the updated role object. - public async Task AddApplicationToRoleService(string roleId, ApplicationsEnum application) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(roleId)); - var update = Builders.Update.AddToSet(r => r.Applications, application); - - await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update); - - var updatedRole = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedRole; - } - catch (Exception ex) - { - logger.LogError(ex, $"AddApplicationToRoleService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - - } - - /// - /// Removes an application from the role's list of applications. - /// - /// The identifier of the role from which the application will be removed. - /// The application enum value to remove. - /// A representing the asynchronous operation, with the updated role object. - public async Task RemoveApplicationFromRoleService(string roleId, ApplicationsEnum application) - { - try - { - var filter = Builders.Filter.Eq("_id", ObjectId.Parse(roleId)); - var update = Builders.Update.Pull(r => r.Applications, application); - - await database.GetCollection(CollectionNames.Role).UpdateOneAsync(filter, update); - - var updatedRole = await database.GetCollection(CollectionNames.Role) - .Find(filter) - .FirstOrDefaultAsync(); - return updatedRole; - } - catch (Exception ex) - { - logger.LogError(ex, $"RemoveApplicationFromRoleService: Error in getting data - {ex.Message}"); - throw new Exception(ex.Message, ex); - } - } - } -} diff --git a/Core.Thalos.Provider/ServiceCollectionExtensions.cs b/Core.Thalos.Provider/ServiceCollectionExtensions.cs index a34a73a..4305164 100644 --- a/Core.Thalos.Provider/ServiceCollectionExtensions.cs +++ b/Core.Thalos.Provider/ServiceCollectionExtensions.cs @@ -64,9 +64,9 @@ namespace Core.Thalos.Provider services.AddHttpContextAccessor(); services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); return services; }