Files
Core.Thalos.DAL.API/Core.Cerberos.Provider/Providers/Onboarding/PermissionService.cs
Sergio Matias Urquin c34987797a Add project files.
2025-04-29 18:55:44 -06:00

235 lines
10 KiB
C#

// ***********************************************************************
// <copyright file="PermissionService.cs">
// Heath
// </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="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);
}
}
}
}