252 lines
		
	
	
		
			11 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			252 lines
		
	
	
		
			11 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| // ***********************************************************************
 | |
| // <copyright file="RoleService.cs">
 | |
| //     AgileWebs
 | |
| // </copyright>
 | |
| // ***********************************************************************
 | |
| using Core.Cerberos.Adapters;
 | |
| using Core.Cerberos.Adapters.Common.Constants;
 | |
| using Core.Cerberos.Adapters.Common.Enums;
 | |
| using Core.Cerberos.Domain.Contexts.Onboarding.Mappers;
 | |
| using Core.Cerberos.Domain.Contexts.Onboarding.Request;
 | |
| using Core.Cerberos.Infraestructure.Caching.Configs;
 | |
| using Core.Cerberos.Infraestructure.Caching.Contracts;
 | |
| using Core.Cerberos.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.Cerberos.Provider.Providers.Onboarding
 | |
| {
 | |
|     /// <summary>
 | |
|     /// Handles all services and business rules related to <see cref="RoleAdapter"/>.
 | |
|     /// </summary>
 | |
|     public class RoleService(ILogger<RoleService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService,
 | |
|         IOptions<CacheSettings> cacheSettings, IMongoDatabase database) : IRoleService
 | |
|     {
 | |
|         private readonly CacheSettings _cacheSettings = cacheSettings.Value;
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Creates a new Role.
 | |
|         /// </summary>
 | |
|         /// <param name="entity">The Role to be created.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing
 | |
|         /// the asynchronous execution of the service.</returns>
 | |
|         public async Task<RoleAdapter> CreateRoleService(RoleRequest newRole)
 | |
|         {
 | |
|             try
 | |
|             {
 | |
|                 var entity = newRole.ToAdapter(httpContextAccessor);
 | |
|                 await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Gets an Role by identifier.
 | |
|         /// </summary>
 | |
|         /// <param name="id">The Role identifier.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing
 | |
|         /// the asynchronous execution of the service.</returns>
 | |
|         public async Task<RoleAdapter> GetRoleByIdService(string id)
 | |
|         {
 | |
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetRoleByIdService", id);
 | |
|             var cachedData = await cacheService.GetAsync<RoleAdapter>(cacheKey);
 | |
| 
 | |
|             if (cachedData is not null) { return cachedData; }
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter.And(
 | |
|                         Builders<RoleAdapter>.Filter.Eq("_id", ObjectId.Parse(id)),
 | |
|                         Builders<RoleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString())
 | |
|                     );
 | |
| 
 | |
|                 var role = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Gets all the roles.
 | |
|         /// </summary>
 | |
|         /// <returns>A <see cref="{Task{IEnumerbale{RoleAdapter}}}"/> representing
 | |
|         /// the asynchronous execution of the service.</returns>
 | |
|         public async Task<IEnumerable<RoleAdapter>> GetAllRolesService()
 | |
|         {
 | |
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllRolesService");
 | |
|             var cachedData = await cacheService.GetAsync<IEnumerable<RoleAdapter>>(cacheKey) ?? [];
 | |
| 
 | |
|             if (cachedData.Any()) return cachedData;
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString());
 | |
| 
 | |
|                 var roles = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Changes the status of the role.
 | |
|         /// </summary>
 | |
|         /// <param name="id">The role identifier.</param>
 | |
|         /// <param name="newStatus">The new status of the role.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing
 | |
|         /// the asynchronous execution of the service.</returns>
 | |
|         public async Task<RoleAdapter> ChangeRoleStatusService(string id, StatusEnum newStatus)
 | |
|         {
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter
 | |
|                     .Eq("_id", ObjectId.Parse(id));
 | |
| 
 | |
|                 var update = Builders<RoleAdapter>.Update
 | |
|                             .Set(v => v.Status, newStatus)
 | |
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor))
 | |
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow);
 | |
| 
 | |
|                 await database.GetCollection<RoleAdapter>(CollectionNames.Role).UpdateOneAsync(filter, update);
 | |
| 
 | |
|                 var updatedRole = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Updates a Role by id.
 | |
|         /// </summary>
 | |
|         /// <param name="entity">The Role to be updated.</param>
 | |
|         /// <param name="id">The Role identifier.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing
 | |
|         /// the asynchronous execution of the service.</returns>
 | |
|         public async Task<RoleAdapter> UpdateRoleService(RoleAdapter entity, string id)
 | |
|         {
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter
 | |
|                     .Eq("_id", ObjectId.Parse(id));
 | |
| 
 | |
|                 var update = Builders<RoleAdapter>.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<RoleAdapter>(CollectionNames.Role).UpdateOneAsync(filter, update);
 | |
| 
 | |
|                 var updatedRole = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
| 
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Adds an application to the role's list of applications.
 | |
|         /// </summary>
 | |
|         /// <param name="roleId">The identifier of the role to which the application will be added.</param>
 | |
|         /// <param name="application">The application enum value to add.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing the asynchronous operation, with the updated role object.</returns>
 | |
|         public async Task<RoleAdapter> AddApplicationToRoleService(string roleId, ApplicationsEnum application)
 | |
|         {
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter.Eq("_id", ObjectId.Parse(roleId));
 | |
|                 var update = Builders<RoleAdapter>.Update.AddToSet(r => r.Applications, application);
 | |
| 
 | |
|                 await database.GetCollection<RoleAdapter>(CollectionNames.Role).UpdateOneAsync(filter, update);
 | |
| 
 | |
|                 var updatedRole = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
| 
 | |
|         }
 | |
| 
 | |
|         /// <summary>
 | |
|         /// Removes an application from the role's list of applications.
 | |
|         /// </summary>
 | |
|         /// <param name="roleId">The identifier of the role from which the application will be removed.</param>
 | |
|         /// <param name="application">The application enum value to remove.</param>
 | |
|         /// <returns>A <see cref="{Task{RoleAdapter}}"/> representing the asynchronous operation, with the updated role object.</returns>
 | |
|         public async Task<RoleAdapter> RemoveApplicationFromRoleService(string roleId, ApplicationsEnum application)
 | |
|         {
 | |
|             try
 | |
|             {
 | |
|                 var filter = Builders<RoleAdapter>.Filter.Eq("_id", ObjectId.Parse(roleId));
 | |
|                 var update = Builders<RoleAdapter>.Update.Pull(r => r.Applications, application);
 | |
| 
 | |
|                 await database.GetCollection<RoleAdapter>(CollectionNames.Role).UpdateOneAsync(filter, update);
 | |
| 
 | |
|                 var updatedRole = await database.GetCollection<RoleAdapter>(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);
 | |
|             }
 | |
|         }
 | |
|     }
 | |
| }
 | 
