reeplace cerberos by talos
This commit is contained in:
		
							
								
								
									
										256
									
								
								Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										256
									
								
								Core.Thalos.Provider/Providers/Onboarding/ModuleService.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,256 @@ | ||||
| // *********************************************************************** | ||||
| // <copyright file="ModuleService.cs"> | ||||
| //     AgileWebs | ||||
| // </copyright> | ||||
| // *********************************************************************** | ||||
| 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 | ||||
| { | ||||
|     /// <summary> | ||||
|     /// Handles all services and business rules related to <see cref="ModuleAdapter"/>. | ||||
|     /// </summary> | ||||
|     public class ModuleService(ILogger<ModuleService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, | ||||
|         IOptions<CacheSettings> cacheSettings, IMongoDatabase database) : IModuleService | ||||
|     { | ||||
|         private readonly CacheSettings _cacheSettings = cacheSettings.Value; | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Creates a new Module. | ||||
|         /// </summary> | ||||
|         /// <param name="entity">The Module to be created.</param> | ||||
|         /// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<ModuleAdapter> CreateModuleService(ModuleRequest newModule) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var entity = newModule.ToAdapter(httpContextAccessor); | ||||
|                 entity.Order = (entity.Order is not null) ? entity.Order : await GetLastOrderModule(newModule); | ||||
|                 await database.GetCollection<ModuleAdapter>(CollectionNames.Module).InsertOneAsync(entity); | ||||
|                 entity.Id = (entity as dynamic ?? "").Id.ToString(); | ||||
|  | ||||
|                 return entity; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"CreateModuleService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets an Module by identifier. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The Module identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns>0 | ||||
|         public async Task<ModuleAdapter> GetModuleByIdService(string id) | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetModuleByIdService", id); | ||||
|             var cachedData = await cacheService.GetAsync<ModuleAdapter>(cacheKey); | ||||
|  | ||||
|             if (cachedData is not null) { return cachedData; } | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<ModuleAdapter>.Filter.And( | ||||
|                     Builders<ModuleAdapter>.Filter.Eq("_id", ObjectId.Parse(id)), | ||||
|                     Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()) | ||||
|                 ); | ||||
|  | ||||
|                 var module = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); | ||||
|  | ||||
|                 await cacheService.SetAsync(cacheKey, module, cacheDuration); | ||||
|  | ||||
|                 return module; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetModuleByIdService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets all the modules. | ||||
|         /// </summary> | ||||
|         /// <returns>A <see cref="{Task{IEnumerbale{ModuleAdapter}}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<IEnumerable<ModuleAdapter>> GetAllModulesService() | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesService"); | ||||
|             var cachedData = await cacheService.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey) ?? []; | ||||
|  | ||||
|             if (cachedData.Any()) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()); | ||||
|  | ||||
|                 var roles = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                     .Find(filter) | ||||
|                                     .SortBy(m => m.Application) | ||||
|                                     .ThenBy(m => m.Order) | ||||
|                                     .ToListAsync(); | ||||
|  | ||||
|                 var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); | ||||
|  | ||||
|                 await cacheService.SetAsync(cacheKey, roles, cacheDuration); | ||||
|  | ||||
|                 return roles; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetAllModulesService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets all the modules by modules identifier list. | ||||
|         /// </summary> | ||||
|         /// <param name="modules">The list of modules identifiers.</param> | ||||
|         /// <returns>A <see cref="Task{IEnumerable{ModuleAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<IEnumerable<ModuleAdapter>> GetAllModulesByListService(string[] modules) | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllModulesByListService", modules); | ||||
|  | ||||
|             var cachedData = await cacheService.GetAsync<IEnumerable<ModuleAdapter>>(cacheKey); | ||||
|  | ||||
|             if (cachedData != null && cachedData.Any()) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var objectIds = modules.Select(id => ObjectId.Parse(id)).ToArray(); | ||||
|  | ||||
|                 var filter = Builders<ModuleAdapter>.Filter.In("_id", objectIds) | ||||
|                                 & Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()); | ||||
|  | ||||
|                 var roles = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                           .Find(filter) | ||||
|                                           .SortBy(m => m.Application) | ||||
|                                           .ThenBy(m => m.Order) | ||||
|                                           .ToListAsync(); | ||||
|  | ||||
|                 var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); | ||||
|  | ||||
|                 await cacheService.SetAsync(cacheKey, roles, cacheDuration); | ||||
|  | ||||
|                 return roles; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetAllModulesByListService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Changes the status of the module. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The module identifier.</param> | ||||
|         /// <param name="newStatus">The new status of the module.</param> | ||||
|         /// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<ModuleAdapter> ChangeModuleStatusService(string id, StatusEnum newStatus) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<ModuleAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<ModuleAdapter>.Update | ||||
|                             .Set(v => v.Status, newStatus) | ||||
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) | ||||
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<ModuleAdapter>(CollectionNames.Module).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 return updatedModule; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"ChangeModuleStatusService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Updates a Module by id. | ||||
|         /// </summary> | ||||
|         /// <param name="entity">The Module to be updated.</param> | ||||
|         /// <param name="id">The Module identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{ModuleAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<ModuleAdapter> UpdateModuleService(ModuleAdapter entity, string id) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<ModuleAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<ModuleAdapter>.Update | ||||
|                             .Set(v => v.Name, entity.Name) | ||||
|                             .Set(v => v.Description, entity.Description) | ||||
|                             .Set(v => v.Icon, entity.Icon) | ||||
|                             .Set(v => v.Route, entity.Route) | ||||
|                             .Set(v => v.Order, entity.Order) | ||||
|                             .Set(v => v.Application, entity.Application) | ||||
|                             .Set(v => v.Status, entity.Status) | ||||
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) | ||||
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<ModuleAdapter>(CollectionNames.Module).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                             .Find(filter) | ||||
|                                             .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 return updatedModule; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"UpdateModuleService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         private async Task<int?> GetLastOrderModule(ModuleRequest newModule) | ||||
|         { | ||||
|             var filter = Builders<ModuleAdapter>.Filter.And( | ||||
|                 Builders<ModuleAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()), | ||||
|                 Builders<ModuleAdapter>.Filter.Eq("application", newModule.Application.ToString())); | ||||
|  | ||||
|             var maxOrderModule = await database.GetCollection<ModuleAdapter>(CollectionNames.Module) | ||||
|                                                .Find(filter) | ||||
|                                                .SortByDescending(m => m.Order) | ||||
|                                                .FirstOrDefaultAsync(); | ||||
|  | ||||
|             return (maxOrderModule is not null && maxOrderModule.Order is not null) ? maxOrderModule.Order : 0; | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										234
									
								
								Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										234
									
								
								Core.Thalos.Provider/Providers/Onboarding/PermissionService.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,234 @@ | ||||
| // *********************************************************************** | ||||
| // <copyright file="PermissionService.cs"> | ||||
| //     AgileWebs | ||||
| // </copyright> | ||||
| // *********************************************************************** | ||||
| 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 | ||||
| { | ||||
|     /// <summary> | ||||
|     /// Handles all services and business rules related to <see cref="PermissionAdapter"/>. | ||||
|     /// </summary> | ||||
|     public class PermissionService(ILogger<PermissionService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, | ||||
|         IOptions<CacheSettings> cacheSettings, IMongoDatabase database) : IPermissionService | ||||
|     { | ||||
|         private readonly CacheSettings _cacheSettings = cacheSettings.Value; | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Creates a new Permission. | ||||
|         /// </summary> | ||||
|         /// <param name="entity">The Permission to be created.</param> | ||||
|         /// <returns>A <see cref="{Task{PermissionAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<PermissionAdapter> CreatePermissionService(PermissionRequest newPermission) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var entity = newPermission.ToAdapter(httpContextAccessor); | ||||
|                 await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets an Permission by identifier. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The Permission identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{PermissionAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns>0 | ||||
|         public async Task<PermissionAdapter> GetPermissionByIdService(string id) | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetPermissionByIdService", id); | ||||
|             var cachedData = await cacheService.GetAsync<PermissionAdapter>(cacheKey); | ||||
|  | ||||
|             if (cachedData is not null) { return cachedData; } | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<PermissionAdapter>.Filter.And( | ||||
|                     Builders<PermissionAdapter>.Filter.Eq("_id", ObjectId.Parse(id)), | ||||
|                     Builders<PermissionAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()) | ||||
|                 ); | ||||
|  | ||||
|                 var permission = await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets all the permissions. | ||||
|         /// </summary> | ||||
|         /// <returns>A <see cref="{Task{IEnumerbale{PermissionAdapter}}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<IEnumerable<PermissionAdapter>> GetAllPermissionsService() | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsService"); | ||||
|             var cachedData = await cacheService.GetAsync<IEnumerable<PermissionAdapter>>(cacheKey) ?? []; | ||||
|  | ||||
|             if (cachedData.Any()) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<PermissionAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()); | ||||
|  | ||||
|                 var roles = await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets all the permissions by permissions identifier list. | ||||
|         /// </summary> | ||||
|         /// <param name="permissions">The list of permissions identifiers.</param> | ||||
|         /// <returns>A <see cref="Task{IEnumerable{PermissionAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<IEnumerable<PermissionAdapter>> GetAllPermissionsByListService(string[] permissions) | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllPermissionsByListService", permissions); | ||||
|  | ||||
|             var cachedData = await cacheService.GetAsync<IEnumerable<PermissionAdapter>>(cacheKey); | ||||
|  | ||||
|             if (cachedData != null && cachedData.Any()) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var objectIds = permissions.Select(id => ObjectId.Parse(id)).ToArray(); | ||||
|  | ||||
|                 var filter = Builders<PermissionAdapter>.Filter.In("_id", objectIds) | ||||
|                                 & Builders<PermissionAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()); | ||||
|  | ||||
|                 var roles = await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Changes the status of the permission. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The permission identifier.</param> | ||||
|         /// <param name="newStatus">The new status of the permission.</param> | ||||
|         /// <returns>A <see cref="{Task{PermissionAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<PermissionAdapter> ChangePermissionStatusService(string id, StatusEnum newStatus) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<PermissionAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<PermissionAdapter>.Update | ||||
|                             .Set(v => v.Status, newStatus) | ||||
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) | ||||
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<PermissionAdapter>(CollectionNames.Permission).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedPermission = await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Updates a Permission by id. | ||||
|         /// </summary> | ||||
|         /// <param name="entity">The Permission to be updated.</param> | ||||
|         /// <param name="id">The Permission identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{PermissionAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<PermissionAdapter> UpdatePermissionService(PermissionAdapter entity, string id) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<PermissionAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<PermissionAdapter>.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<PermissionAdapter>(CollectionNames.Permission).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedPermission = await database.GetCollection<PermissionAdapter>(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); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										251
									
								
								Core.Thalos.Provider/Providers/Onboarding/RoleService.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										251
									
								
								Core.Thalos.Provider/Providers/Onboarding/RoleService.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,251 @@ | ||||
| // *********************************************************************** | ||||
| // <copyright file="RoleService.cs"> | ||||
| //     AgileWebs | ||||
| // </copyright> | ||||
| // *********************************************************************** | ||||
| 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 | ||||
| { | ||||
|     /// <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); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
							
								
								
									
										627
									
								
								Core.Thalos.Provider/Providers/Onboarding/UserService.cs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										627
									
								
								Core.Thalos.Provider/Providers/Onboarding/UserService.cs
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,627 @@ | ||||
| // *********************************************************************** | ||||
| // <copyright file="UserService.cs"> | ||||
| //     AgileWebs | ||||
| // </copyright> | ||||
| // *********************************************************************** | ||||
|  | ||||
| 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.Bson.Serialization; | ||||
| using MongoDB.Driver; | ||||
| using System.Text.RegularExpressions; | ||||
| using Core.Blueprint.Storage.Contracts; | ||||
| using Core.Blueprint.Storage.Adapters; | ||||
|  | ||||
| namespace Core.Thalos.Provider.Providers.Onboarding | ||||
| { | ||||
|     /// <summary> | ||||
|     /// Handles all services and business rules related to <see cref="UserAdapter"/>. | ||||
|     /// </summary> | ||||
|     public class UserService(ILogger<UserService> logger, IHttpContextAccessor httpContextAccessor, ICacheService cacheService, | ||||
|         IOptions<CacheSettings> cacheSettings, IMongoDatabase database, IBlobStorageProvider blobStorageProvider) : IUserService | ||||
|     { | ||||
|         private readonly CacheSettings _cacheSettings = cacheSettings.Value; | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Creates a new User. | ||||
|         /// </summary> | ||||
|         /// <param name="newUser">The User to be created.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> CreateUserService(UserRequest newUser) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var entity = newUser.ToAdapter(httpContextAccessor); | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).InsertOneAsync(entity); | ||||
|                 entity.Id = (entity as dynamic ?? "").Id.ToString(); | ||||
|  | ||||
|                 return entity; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"CreateUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets an User by identifier. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The User identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> GetUserByIdService(string id) | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetUserByIdService", id); | ||||
|             var cachedData = await cacheService.GetAsync<UserAdapter>(cacheKey); | ||||
|  | ||||
|             if (cachedData is not null) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.And( | ||||
|                     Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(id)), | ||||
|                     Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()) | ||||
|                 ); | ||||
|  | ||||
|                 var user = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                             .Find(filter) | ||||
|                             .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); | ||||
|  | ||||
|                 await cacheService.SetAsync(cacheKey, user, cacheDuration); | ||||
|  | ||||
|                 return user; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetUserByIdService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets all the users. | ||||
|         /// </summary> | ||||
|         /// <returns>A <see cref="{Task{IEnumerable{UserAdapter}}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<IEnumerable<UserAdapter>> GetAllUsersService() | ||||
|         { | ||||
|             var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllUsersService"); | ||||
|             var cachedData = await cacheService.GetAsync<IEnumerable<UserAdapter>>(cacheKey) ?? []; | ||||
|  | ||||
|             if (cachedData.Any()) return cachedData; | ||||
|  | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()); | ||||
|  | ||||
|                 var users = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                             .Find(filter) | ||||
|                             .ToListAsync(); | ||||
|  | ||||
|                 var cacheDuration = CacheHelper.GetCacheDuration(_cacheSettings); | ||||
|                 await cacheService.SetAsync(cacheKey, users, cacheDuration); | ||||
|  | ||||
|                 return users; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetAllUsersService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets an User by email. | ||||
|         /// </summary> | ||||
|         /// <param name="email">The User email.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> GetUserByEmailService(string? email) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.And( | ||||
|                     Builders<UserAdapter>.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")), | ||||
|                     Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()) | ||||
|                 ); | ||||
|  | ||||
|                 var user = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                             .Find(filter) | ||||
|                             .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 return user; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetUserByEmailService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Validates if a users exists by email.. | ||||
|         /// </summary> | ||||
|         /// <param name="email">The User email.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> ValidateUserExistenceService(string? email) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.And( | ||||
|                     Builders<UserAdapter>.Filter.Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")), | ||||
|                     Builders<UserAdapter>.Filter.Eq("status", StatusEnum.Active.ToString()) | ||||
|                 ); | ||||
|  | ||||
|                 var user = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                             .Find(filter) | ||||
|                             .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 return user; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"ValidateUserExistenceService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Deletes an User by id. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The User identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> DeleteUserService(string id) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<UserAdapter>.Update | ||||
|                             .Set(v => v.Status, StatusEnum.Inactive); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var deletedUser = await database.GetCollection<UserAdapter>(CollectionNames.User).Find(filter).FirstAsync(); | ||||
|  | ||||
|                 return deletedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"DeleteUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Changes the status of the user. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The user identifier.</param> | ||||
|         /// <param name="newStatus">The new status of the user.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> ChangeUserStatusService(string id, StatusEnum newStatus) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<UserAdapter>.Update | ||||
|                             .Set(v => v.Status, newStatus) | ||||
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) | ||||
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"ChangeUserStatusService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Updates a User by id. | ||||
|         /// </summary> | ||||
|         /// <param name="entity">The User to be updated.</param> | ||||
|         /// <param name="id">The User identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> UpdateUserService(UserAdapter entity, string id) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter | ||||
|                     .Eq("_id", ObjectId.Parse(id)); | ||||
|  | ||||
|                 var update = Builders<UserAdapter>.Update | ||||
|                             .Set(v => v.Email, entity.Email) | ||||
|                             .Set(v => v.Name, entity.Name) | ||||
|                             .Set(v => v.MiddleName, entity.MiddleName) | ||||
|                             .Set(v => v.LastName, entity.LastName) | ||||
|                             .Set(v => v.DisplayName, $"{entity.Name} {entity.MiddleName} {entity.LastName}") | ||||
|                             .Set(v => v.RoleId, entity.RoleId) | ||||
|                             .Set(v => v.Companies, entity.Companies) | ||||
|                             .Set(v => v.Projects, entity.Projects) | ||||
|                             .Set(v => v.Status, entity.Status) | ||||
|                             .Set(v => v.UpdatedBy, Helper.GetEmail(httpContextAccessor)) | ||||
|                             .Set(v => v.UpdatedAt, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await GetUserByIdService(id); | ||||
|  | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"UpdateUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Logs in the user. | ||||
|         /// </summary> | ||||
|         /// <param name="id">The User identifier.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter?> LogInUserService(string email) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter | ||||
|                     .Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")); | ||||
|  | ||||
|                 var update = Builders<UserAdapter>.Update | ||||
|                             .Set(v => v.LastLogIn, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var user = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstAsync(); | ||||
|  | ||||
|                 return user; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"LogInUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Logs out the user's session. | ||||
|         /// </summary> | ||||
|         /// <param name="email">The User email.</param> | ||||
|         /// <returns>A <see cref="{Task{UserAdapter}}"/> representing | ||||
|         /// the asynchronous execution of the service.</returns> | ||||
|         public async Task<UserAdapter> LogOutUserSessionService(string email) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter | ||||
|                     .Regex("email", new BsonRegularExpression($"^{Regex.Escape(email ?? "")}$", "i")); | ||||
|  | ||||
|  | ||||
|                 var update = Builders<UserAdapter>.Update | ||||
|                             .Set(v => v.LastLogOut, DateTime.UtcNow); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var user = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstAsync(); | ||||
|  | ||||
|                 return user; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"LogOutUserSessionService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Adds a company to the user's list of companies. | ||||
|         /// </summary> | ||||
|         /// <param name="userId">The identifier of the user to whom the company will be added.</param> | ||||
|         /// <param name="companyId">The identifier of the company to add.</param> | ||||
|         /// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns> | ||||
|         public async Task<UserAdapter> AddCompanyToUserService(string userId, string companyId) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId)); | ||||
|                 var update = Builders<UserAdapter>.Update.AddToSet(v => v.Companies, companyId); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"AddCompanyToUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Removes a company from the user's list of companies. | ||||
|         /// </summary> | ||||
|         /// <param name="userId">The identifier of the user from whom the company will be removed.</param> | ||||
|         /// <param name="companyId">The identifier of the company to remove.</param> | ||||
|         /// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns> | ||||
|         public async Task<UserAdapter> RemoveCompanyFromUserService(string userId, string companyId) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId)); | ||||
|                 var update = Builders<UserAdapter>.Update.Pull(v => v.Companies, companyId); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"RemoveCompanyFromUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Adds a project to the user's list of projects. | ||||
|         /// </summary> | ||||
|         /// <param name="userId">The identifier of the user to whom the project will be added.</param> | ||||
|         /// <param name="projectId">The identifier of the project to add.</param> | ||||
|         /// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns> | ||||
|         public async Task<UserAdapter> AddProjectToUserService(string userId, string projectId) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId)); | ||||
|                 var update = Builders<UserAdapter>.Update.AddToSet(v => v.Projects, projectId); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                      .Find(filter) | ||||
|                                      .FirstOrDefaultAsync(); | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"AddProjectToUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Removes a project from the user's list of projects. | ||||
|         /// </summary> | ||||
|         /// <param name="userId">The identifier of the user from whom the project will be removed.</param> | ||||
|         /// <param name="projectId">The identifier of the project to remove.</param> | ||||
|         /// <returns>A <see cref="Task{UserAdapter}"/> representing the asynchronous operation, with the updated user object.</returns> | ||||
|         public async Task<UserAdapter> RemoveProjectFromUserService(string userId, string projectId) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var filter = Builders<UserAdapter>.Filter.Eq("_id", ObjectId.Parse(userId)); | ||||
|                 var update = Builders<UserAdapter>.Update.Pull(v => v.Projects, projectId); | ||||
|  | ||||
|                 await database.GetCollection<UserAdapter>(CollectionNames.User).UpdateOneAsync(filter, update); | ||||
|  | ||||
|                 var updatedUser = await database.GetCollection<UserAdapter>(CollectionNames.User) | ||||
|                                     .Find(filter) | ||||
|                                     .FirstOrDefaultAsync(); | ||||
|                 return updatedUser; | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"RemoveProjectFromUserService: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         /// <summary> | ||||
|         /// Gets the token adapter for a user. | ||||
|         /// </summary> | ||||
|         /// <param name="email">The user's email.</param> | ||||
|         /// <returns>A <see cref="{Task{TokenAdapter}}"/> representing the asynchronous execution of the service.</returns> | ||||
|         public async Task<TokenAdapter?> GetTokenAdapter(string email) | ||||
|         { | ||||
|             try | ||||
|             { | ||||
|                 var pipeline = new[] | ||||
|                 { | ||||
|                     new BsonDocument("$match", new BsonDocument | ||||
|                     { | ||||
|                         { "email", new BsonDocument | ||||
|                             { | ||||
|                                 { "$regex", $"^{Regex.Escape(email)}$" }, | ||||
|                                 { "$options", "i" } | ||||
|                             } | ||||
|                         }, | ||||
|                         { "status", StatusEnum.Active.ToString() } | ||||
|                     }), | ||||
|  | ||||
|                     new BsonDocument("$lookup", new BsonDocument | ||||
|                     { | ||||
|                         { "from", "Roles" }, | ||||
|                         { "localField", "roleId" }, | ||||
|                         { "foreignField", "_id" }, | ||||
|                         { "as", "role" } | ||||
|                     }), | ||||
|  | ||||
|                     new BsonDocument("$unwind", "$role"), | ||||
|                     new BsonDocument("$match", new BsonDocument("role.status", StatusEnum.Active.ToString())), | ||||
|  | ||||
|                     new BsonDocument("$addFields", new BsonDocument | ||||
|                     { | ||||
|                         { "role.permissions", new BsonDocument("$map", new BsonDocument | ||||
|                             { | ||||
|                                 { "input", "$role.permissions" }, | ||||
|                                 { "as", "perm" }, | ||||
|                                 { "in", new BsonDocument("$toObjectId", "$$perm") } | ||||
|                             }) | ||||
|                         }, | ||||
|                         { "role.modules", new BsonDocument("$map", new BsonDocument | ||||
|                             { | ||||
|                                 { "input", "$role.modules" }, | ||||
|                                 { "as", "mod" }, | ||||
|                                 { "in", new BsonDocument("$toObjectId", "$$mod") } | ||||
|                             }) | ||||
|                         } | ||||
|                     }), | ||||
|  | ||||
|                     new BsonDocument("$lookup", new BsonDocument | ||||
|                     { | ||||
|                         { "from", "Permissions" }, | ||||
|                         { "localField", "role.permissions" }, | ||||
|                         { "foreignField", "_id" }, | ||||
|                         { "as", "permissions" } | ||||
|                     }), | ||||
|                     new BsonDocument("$lookup", new BsonDocument | ||||
|                     { | ||||
|                         { "from", "Modules" }, | ||||
|                         { "localField", "role.modules" }, | ||||
|                         { "foreignField", "_id" }, | ||||
|                         { "as", "modules" } | ||||
|                     }), | ||||
|                     new BsonDocument("$project", new BsonDocument | ||||
|                     { | ||||
|                         { "_id", 1 }, | ||||
|                         { "guid", 1 }, | ||||
|                         { "email", 1 }, | ||||
|                         { "name", 1 }, | ||||
|                         { "middleName", 1 }, | ||||
|                         { "lastName", 1 }, | ||||
|                         { "displayName", 1 }, | ||||
|                         { "roleId", 1 }, | ||||
|                         { "companies", 1 }, | ||||
|                         { "projects", 1 }, | ||||
|                         { "lastLogIn", 1 }, | ||||
|                         { "lastLogOut", 1 }, | ||||
|                         { "createdBy", 1 }, | ||||
|                         { "updatedBy", 1 }, | ||||
|                         { "status", 1 }, | ||||
|                         { "createdAt", 1 }, | ||||
|                         { "updatedAt", 1 }, | ||||
|                         { "role._id", 1 }, | ||||
|                         { "role.name", 1 }, | ||||
|                         { "role.description", 1 }, | ||||
|                         { "role.applications", 1 }, | ||||
|                         { "role.permissions", 1 }, | ||||
|                         { "role.modules", 1 }, | ||||
|                         { "role.status", 1 }, | ||||
|                         { "role.createdAt", 1 }, | ||||
|                         { "role.updatedAt", 1 }, | ||||
|                         { "role.createdBy", 1 }, | ||||
|                         { "role.updatedBy", 1 }, | ||||
|                         { "permissions", 1 }, | ||||
|                         { "modules", 1 } | ||||
|                     }) | ||||
|                 }; | ||||
|  | ||||
|  | ||||
|                 var result = await database.GetCollection<BsonDocument>(CollectionNames.User) | ||||
|                     .Aggregate<BsonDocument>(pipeline) | ||||
|                     .FirstOrDefaultAsync(); | ||||
|  | ||||
|                 if (result is null) return null; | ||||
|  | ||||
|                 var tokenAdapter = new TokenAdapter | ||||
|                 { | ||||
|                     User = new UserAdapter | ||||
|                     { | ||||
|                         Id = result["_id"]?.ToString() ?? "", | ||||
|                         Guid = result["guid"].AsString, | ||||
|                         Email = result["email"].AsString, | ||||
|                         Name = result["name"].AsString, | ||||
|                         MiddleName = result["middleName"].AsString, | ||||
|                         LastName = result["lastName"].AsString, | ||||
|                         DisplayName = result["displayName"].AsString, | ||||
|                         RoleId = result["roleId"]?.ToString() ?? "", | ||||
|                         Companies = result["companies"].AsBsonArray | ||||
|                             .Select(c => c.AsString) | ||||
|                             .ToArray(), | ||||
|                         Projects = result["projects"].AsBsonArray | ||||
|                             .Select(c => c.AsString) | ||||
|                             .ToArray(), | ||||
|                         LastLogIn = result["lastLogIn"].ToUniversalTime(), | ||||
|                         LastLogOut = result["lastLogOut"].ToUniversalTime(), | ||||
|                         CreatedAt = result["createdAt"].ToUniversalTime(), | ||||
|                         CreatedBy = result["createdBy"].AsString, | ||||
|                         UpdatedAt = result["updatedAt"].ToUniversalTime(), | ||||
|                         UpdatedBy = result["updatedBy"].AsString, | ||||
|                         Status = (StatusEnum)Enum.Parse(typeof(StatusEnum), result["status"].AsString), | ||||
|                     }, | ||||
|                     Role = new RoleAdapter | ||||
|                     { | ||||
|                         Id = result["role"]["_id"]?.ToString() ?? "", | ||||
|                         Name = result["role"]["name"].AsString, | ||||
|                         Description = result["role"]["description"].AsString, | ||||
|                         Applications = result["role"]["applications"].AsBsonArray | ||||
|                             .Select(c => (ApplicationsEnum)c.AsInt32) | ||||
|                             .ToArray(), | ||||
|                         Modules = result["role"]["modules"].AsBsonArray | ||||
|                             .Select(c => c.ToString() ?? "") | ||||
|                             .ToArray(), | ||||
|                         Permissions = result["role"]["permissions"].AsBsonArray | ||||
|                             .Select(c => c.ToString() ?? "") | ||||
|                             .ToArray(), | ||||
|                         Status = (StatusEnum)Enum.Parse(typeof(StatusEnum), result["role"]["status"].AsString), | ||||
|                         CreatedAt = result["role"]["createdAt"].ToUniversalTime(), | ||||
|                         UpdatedAt = result["role"]["updatedAt"].ToUniversalTime(), | ||||
|                         CreatedBy = result["role"]["createdBy"].AsString, | ||||
|                         UpdatedBy = result["role"]["updatedBy"].AsString | ||||
|                     }, | ||||
|                     Permissions = result["permissions"].AsBsonArray | ||||
|                         .Select(permission => BsonSerializer.Deserialize<PermissionAdapter>(permission.AsBsonDocument)) | ||||
|                         .Where(permission => permission.Status == StatusEnum.Active) | ||||
|                         .ToList() | ||||
|                 }; | ||||
|  | ||||
|                 return tokenAdapter; | ||||
|  | ||||
|             } | ||||
|             catch (Exception ex) | ||||
|             { | ||||
|                 logger.LogError(ex, $"GetTokenAdapter: Error in getting data - {ex.Message}"); | ||||
|                 throw new Exception(ex.Message, ex); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
		Reference in New Issue
	
	Block a user
	 Sergio Matias Urquin
					Sergio Matias Urquin