using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Authentication.Interfaces;
using adas_core.Domain.Models.MongoModels;
using Microsoft.AspNetCore.Http;
using MongoDB.Bson;
using Serilog;
namespace adas_core.Authentication;
public class AuthorityService(
IAuthorityRepository authorityRepository,
IHttpContextAccessor httpContextAccessor,
ILocalAuditService auditService)
: IAuthorityService
{
///
/// Creates a new authority for the specified user with the given role name by delegating to the authority repository.
///
/// The name of the role to associate with the authority.
/// The unique identifier of the user for whom the authority is being created.
public void CreateNew(string roleName, ObjectId userId)
{
authorityRepository.CreateNewAuthority(roleName, userId);
}
///
/// Inserts a new into the authority repository and records an audit log entry for the operation using the current HTTP context user.
///
/// The authorization entity to be inserted and tracked in the audit log.
public async Task InsertOne(Authorization authorization)
{
await authorityRepository.InsertOneAsync(authorization);
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, null, authorization);
}
///
/// Updates an existing authorization record in the repository and records an audit log entry capturing the previous and updated states for the current user.
///
/// The authorization entity containing the identifier of the record to update and its new values.
public async Task updateOne(Authorization authorization)
{
var oldAuth = await authorityRepository.GetById(authorization.Id);
await authorityRepository.UpdateOneAsync(authorization.Id, authorization);
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, oldAuth, authorization);
}
///
/// Retrieves the authorities of the specified user.
///
///
/// A list of the user's authorities.
public Task> GetUserAuthorities(ObjectId userId)
{
return authorityRepository.GetUserAuthorities(userId);
}
///
/// Retrieves all available authorities from the underlying repository.
///
/// A task that represents the asynchronous operation, containing a list of all records.
public Task> GetAllAuthorities()
{
return authorityRepository.GetAllAuthorities();
}
///
/// Deletes all authorities associated with the specified user and records an audit log entry for each removed authority. Returns false if no authorities were deleted or if an exception is encountered during processing.
///
/// The unique identifier of the user whose authorities should be deleted.
/// true if the authorities were successfully deleted; otherwise, false.
public async Task DeleteAuthoritiesForUser(ObjectId id)
{
try
{
var list = await authorityRepository.GetUserAuthorities(id);
var result = await authorityRepository.DeleteAllAuthoritiesByUser(id);
if (!result) return result;
foreach (var auth in list)
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, auth, null);
return result;
}
catch (Exception e)
{
Log.Error("Exception deleting authorities for user {id}. Exception: {e}", id, e.Message);
return false;
}
}
///
/// Creates a new user authority by persisting the provided authorization record and writing an audit log entry for the operation.
///
/// The authorization entity to be created and stored.
/// The created entity.
public async Task CreateNewUserAuthority(Authorization authorization)
{
await authorityRepository.InsertOneAsync(authorization);
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, null, authorization);
return authorization;
}
///
/// Deletes a user authority by its parsed identifier and records an audit log entry when the deletion succeeds.
/// Returns true if the authority was found and removed, and false when the entity is not found or an exception occurs during processing.
///
/// The parsed identifier of the user authority to delete.
/// true if the user authority was successfully deleted; otherwise, false.
public async Task DeleteUserAuthority(ObjectId userAuthorityIdParsed)
{
try
{
var result = await authorityRepository.DeleteAsync(userAuthorityIdParsed);
if (result != null)
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, result, null);
return result != null;
}
catch (Exception e)
{
Log.Error("Exception deleting user authority {userAuthorityIdParsed}. Exception: {e}",
userAuthorityIdParsed, e.Message);
return false;
}
}
///
/// Edits an existing user authority, records the change in an audit log, and returns the updated authorization.
/// Returns null if the update operation fails due to an exception.
///
/// The authorization entity containing the updated information to persist.
/// The updated on success, or null if an error occurs during the operation.
public async Task EditUserAuthority(Authorization authorization)
{
try
{
var oldAuth = await authorityRepository.GetById(authorization.Id);
await authorityRepository.UpdateOneAsync(authorization.Id, authorization);
await auditService.CreateAuditLogAsync(httpContextAccessor.HttpContext?.User!, oldAuth, authorization);
return authorization;
}
catch (Exception e)
{
Log.Error("Exception editing user authority {authorization}. Exception: {e}", authorization, e.Message);
return null;
}
}
}