mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 12:11:10 +00:00
Adds authorization roles administrator dashboard
This commit is contained in:
1 parent
290af03c83
commit
1df31515fb
191 files changed
+6189
-806
No files matched your search
+13
@@ -0,0 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Query for retrieving the list of authorization permissions.
|
||||
/// </summary>
|
||||
public record GetPermissionsQuery : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Permissions.Queries.GetPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization permissions.
|
||||
/// </summary>
|
||||
public class GetPermissionsQueryHandler : IRequestHandler<GetPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IPermissionRepository _permissionRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPermissionsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public GetPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_permissionRepository = unitOfWork.GetRepository<IPermissionRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the list of authorization permissions.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="PermissionResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<PermissionResponse>>> Handle(GetPermissionsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can see the list of authorization permissions
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
ErrorOr<IEnumerable<PermissionEntity>> getPermissionsResult = await _permissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
return getPermissionsResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
|
||||
|
||||
/// <summary>
|
||||
/// Command for adding an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="RoleName">The name of the role.</param>
|
||||
/// <param name="Permissions">The collection or permissions of the role.</param>
|
||||
[DebuggerDisplay("RoleName: {RoleName}")]
|
||||
public record AddRoleCommand(
|
||||
string RoleName,
|
||||
List<Guid> Permissions
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to add an authorization role.
|
||||
/// </summary>
|
||||
public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public AddRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to add an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully created <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can create authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
||||
|
||||
// create the new role, with its permissions
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
RoleName = request.RoleName,
|
||||
RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
{
|
||||
PermissionId = permissionId,
|
||||
Permission = null!,
|
||||
Role = null!,
|
||||
RoleId = default
|
||||
}).ToList()
|
||||
};
|
||||
// save the new role in the repository
|
||||
ErrorOr<Created> insertRoleResult = await roleRepository.InsertAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||
if (insertRoleResult.IsError)
|
||||
return insertRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the newly saved authorization role from the persistence medium and return it
|
||||
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByNameAsync(request.RoleName, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError)
|
||||
return getRoleResult.Errors;
|
||||
if (getRoleResult.Value is null)
|
||||
return Errors.Persistence.ErrorPersistingAuthorizationRole;
|
||||
return getRoleResult.Value.ToRolePermissionsResponse();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.AddRole;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="AddRoleCommand"/>.
|
||||
/// </summary>
|
||||
public class AddRoleCommandValidator : AbstractValidator<AddRoleCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AddRoleCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public AddRoleCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleName)
|
||||
.NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.Permissions)
|
||||
.NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
|
||||
RuleForEach(x => x.Permissions)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
|
||||
|
||||
/// <summary>
|
||||
/// Command for deleting an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="RoleId">The Id of the role.</param>
|
||||
[DebuggerDisplay("RoleId: {RoleId}")]
|
||||
public record DeleteRoleCommand(
|
||||
Guid RoleId
|
||||
) : IRequest<ErrorOr<Deleted>>;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to delete an authorization role.
|
||||
/// </summary>
|
||||
public class DeleteRoleCommandHandler : IRequestHandler<DeleteRoleCommand, ErrorOr<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public DeleteRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully deleted <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<Deleted>> Handle(DeleteRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can delete authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
// check if a role with the requested Id exists
|
||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
||||
ErrorOr<RoleEntity?> getExistingRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (getExistingRoleResult.IsError)
|
||||
return getExistingRoleResult.Errors;
|
||||
else if (getExistingRoleResult.Value is null)
|
||||
return Errors.Authorization.RoleNotFound;
|
||||
|
||||
// delete the role and its permissions
|
||||
ErrorOr<Deleted> deleteRoleResult = await roleRepository.DeleteByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteRoleResult.IsError)
|
||||
return deleteRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return deleteRoleResult.Value;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.DeleteRole;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="DeleteRoleCommand"/>.
|
||||
/// </summary>
|
||||
public class DeleteRoleCommandValidator : AbstractValidator<DeleteRoleCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteRoleCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public DeleteRoleCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleId)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="RoleId">The Id of the role.</param>
|
||||
/// <param name="RoleName">The name of the role.</param>
|
||||
/// <param name="Permissions">The collection or permissions of the role.</param>
|
||||
[DebuggerDisplay("RoleName: {RoleName}")]
|
||||
public record UpdateRoleCommand(
|
||||
Guid RoleId,
|
||||
string RoleName,
|
||||
List<Guid> Permissions
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update an authorization role.
|
||||
/// </summary>
|
||||
public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public UpdateRoleCommandHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to update an authorization role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a successfully updated <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can update authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
|
||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
||||
|
||||
// update the role and its permissions
|
||||
RoleEntity newRole = new()
|
||||
{
|
||||
Id = request.RoleId,
|
||||
RoleName = request.RoleName,
|
||||
RolePermissions = request.Permissions.Select(permissionId => new RolePermissionEntity()
|
||||
{
|
||||
PermissionId = permissionId,
|
||||
Permission = null!,
|
||||
Role = null!,
|
||||
RoleId = default
|
||||
}).ToList()
|
||||
};
|
||||
// save the updated role in the repository
|
||||
ErrorOr<Updated> updateRoleResult = await roleRepository.UpdateAsync(newRole, cancellationToken).ConfigureAwait(false);
|
||||
if (updateRoleResult.IsError)
|
||||
return updateRoleResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the updated authorization role from the persistence medium and return it
|
||||
ErrorOr<RoleEntity?> getRoleResult = await roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError)
|
||||
return getRoleResult.Errors;
|
||||
if (getRoleResult.Value is null)
|
||||
return Errors.Persistence.ErrorPersistingAuthorizationRole;
|
||||
return getRoleResult.Value.ToRolePermissionsResponse();
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdateRoleCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdateRoleCommandValidator : AbstractValidator<UpdateRoleCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateRoleCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdateRoleCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleId)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.RoleName)
|
||||
.NotNull().WithMessage(Errors.Authorization.RoleNameCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleNameCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.Permissions)
|
||||
.NotNull().WithMessage(Errors.Authorization.PermissionsListCannotBeNull.Description)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionsListCannotBeEmpty.Description);
|
||||
RuleForEach(x => x.Permissions)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.PermissionIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the authorization permissions of a role identified by <paramref name="RoleId"/>.
|
||||
/// </summary>
|
||||
/// <param name="RoleId">The Id of the authorization role for which to get the list of permissions.</param>
|
||||
[DebuggerDisplay("RoleId: {RoleId}")]
|
||||
public record GetRolePermissionsQuery(
|
||||
Guid RoleId
|
||||
) : IRequest<ErrorOr<RolePermissionsResponse>>;
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization permissions for a role.
|
||||
/// </summary>
|
||||
public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissionsQuery, ErrorOr<RolePermissionsResponse>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IRoleRepository _roleRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolePermissionsQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public GetRolePermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the list of authorization permissions for a role.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RolePermissionsResponse>> Handle(GetRolePermissionsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can see the list of authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
ErrorOr<RoleEntity?> getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError)
|
||||
return getRoleResult.Errors;
|
||||
else if (getRoleResult.Value is null)
|
||||
return Errors.Authorization.RoleNotFound;
|
||||
return getRoleResult.Value.ToRolePermissionsResponse();
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRolePermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetRolePermissionsQuery"/>.
|
||||
/// </summary>
|
||||
public class GetRolePermissionsQueryValidator : AbstractValidator<GetRolePermissionsQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolePermissionsQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetRolePermissionsQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.RoleId)
|
||||
.NotEmpty().WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Authorization.RoleIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Query for retrieving the list of authorization roles.
|
||||
/// </summary>
|
||||
public record GetRolesQuery() : IRequest<ErrorOr<IEnumerable<RoleResponse>>>;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Errors;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.Admin.Authorization.Roles.Queries.GetRoles;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the list of authorization roles.
|
||||
/// </summary>
|
||||
public class GetRolesQueryHandler : IRequestHandler<GetRolesQuery, ErrorOr<IEnumerable<RoleResponse>>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IRoleRepository _roleRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRolesQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public GetRolesQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_roleRepository = unitOfWork.GetRepository<IRoleRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the list of authorization roles.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a collection of <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<IEnumerable<RoleResponse>>> Handle(GetRolesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can see the list of authorization roles
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
ErrorOr<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
return getRolesResult.Match(value => ErrorOrFactory.From(value.ToResponses()), errors => errors);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class GetDirectoriesQueryHandler : IRequestHandler<GetDirectoriesQuery, E
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<DirectoryResponse>>> Handle(GetDirectoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+13
-13
@@ -1,8 +1,8 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.FileSystem;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Common.Enums.FileSystem;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
@@ -81,10 +81,10 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
/// </returns>
|
||||
private ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> GetDrives()
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemItem>> driveResult = _driveService.GetDrives();
|
||||
if (driveResult.IsError)
|
||||
return driveResult.Errors;
|
||||
return ErrorOrFactory.From(driveResult.Value.ToTreeNodeResponses());
|
||||
ErrorOr<IEnumerable<FileSystemItem>> getDrivesResult = _driveService.GetDrives();
|
||||
if (getDrivesResult.IsError)
|
||||
return getDrivesResult.Errors;
|
||||
return ErrorOrFactory.From(getDrivesResult.Value.ToTreeNodeResponses());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -138,11 +138,11 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
private ErrorOr<Success> LoadChildren(FileSystemTreeNodeResponse node, bool includeFiles, bool includeHiddenElements)
|
||||
{
|
||||
// get subdirectories under the current node's path
|
||||
ErrorOr<IEnumerable<Directory>> subDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements);
|
||||
if (subDirectoriesResult.IsError)
|
||||
return subDirectoriesResult.Errors;
|
||||
ErrorOr<IEnumerable<Directory>> getSubDirectoriesResult = _directoryService.GetSubdirectories(node.Path, includeHiddenElements);
|
||||
if (getSubDirectoriesResult.IsError)
|
||||
return getSubDirectoriesResult.Errors;
|
||||
// add each subdirectory as a child node of the current directory
|
||||
foreach (Directory subDirectory in subDirectoriesResult.Value ?? [])
|
||||
foreach (Directory subDirectory in getSubDirectoriesResult.Value ?? [])
|
||||
{
|
||||
FileSystemTreeNodeResponse subDirNode = new()
|
||||
{
|
||||
@@ -157,11 +157,11 @@ public class GetDirectoryTreeQueryHandler : IRequestHandler<GetDirectoryTreeQuer
|
||||
if (includeFiles)
|
||||
{
|
||||
// get files under the current node's path
|
||||
ErrorOr<IEnumerable<File>> filesResult = _fileService.GetFiles(node.Path, includeHiddenElements);
|
||||
if (filesResult.IsError)
|
||||
return filesResult.Errors;
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(node.Path, includeHiddenElements);
|
||||
if (getFilesResult.IsError)
|
||||
return getFilesResult.Errors;
|
||||
// add each file as a child node of the current directory
|
||||
foreach (File file in filesResult.Value)
|
||||
foreach (File file in getFilesResult.Value)
|
||||
{
|
||||
FileSystemTreeNodeResponse fileNode = new()
|
||||
{
|
||||
|
||||
+3
-3
@@ -2,8 +2,8 @@
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Common;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Entities;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
@@ -38,7 +38,7 @@ public class GetTreeDirectoriesQueryHandler : IRequestHandler<GetTreeDirectories
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeDirectoriesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<Directory>> result = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<Directory>> getSubdirectoriesResult = _directoryService.GetSubdirectories(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getSubdirectoriesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class GetDrivesQueryHandler : IRequestHandler<GetDrivesQuery, ErrorOr<IEn
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetDrivesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<FileSystemItem>> result = _driveService.GetDrives();
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<FileSystemItem>> getDrivesResult = _driveService.GetDrives();
|
||||
return ValueTask.FromResult(getDrivesResult.Match(values => ErrorOrFactory.From(values.ToTreeNodeResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class GetFilesQueryHandler : IRequestHandler<GetFilesQuery, ErrorOr<IEnum
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileResponse>>> Handle(GetFilesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class GetTreeFilesQueryHandler : IRequestHandler<GetTreeFilesQuery, Error
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<FileSystemTreeNodeResponse>>> Handle(GetTreeFilesQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<File>> result = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<File>> getFilesResult = _fileService.GetFiles(request.Path!, request.IncludeHiddenElements);
|
||||
return ValueTask.FromResult(getFilesResult.Match(values => ErrorOrFactory.From(values.ToFileSystemTreeNodeResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -36,7 +36,7 @@ public class CombinePathCommandHandler : IRequestHandler<CombinePathCommand, Err
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(CombinePathCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<string> result = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(new PathSegmentResponse(result.Value)), errors => errors));
|
||||
ErrorOr<string> combinePathResult = _pathService.CombinePath(request.OriginalPath!, request.NewPath!);
|
||||
return ValueTask.FromResult(combinePathResult.Match(values => ErrorOrFactory.From(new PathSegmentResponse(combinePathResult.Value)), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class SplitPathCommandHandler : IRequestHandler<SplitPathCommand, ErrorOr
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(SplitPathCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegment>> result = _pathService.ParsePath(request.Path!);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<PathSegment>> parsePathResult = _pathService.ParsePath(request.Path!);
|
||||
return ValueTask.FromResult(parsePathResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,7 +38,7 @@ public class GetPathParentQueryHandler : IRequestHandler<GetPathParentQuery, Err
|
||||
/// </returns>
|
||||
public ValueTask<ErrorOr<IEnumerable<PathSegmentResponse>>> Handle(GetPathParentQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<IEnumerable<PathSegment>> result = _pathService.GoUpOneLevel(request.Path!);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
ErrorOr<IEnumerable<PathSegment>> goUpOneLevelResult = _pathService.GoUpOneLevel(request.Path!);
|
||||
return ValueTask.FromResult(goUpOneLevelResult.Match(values => ErrorOrFactory.From(values.ToResponses()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -35,7 +35,7 @@ public class GetPathRootQueryHandler : IRequestHandler<GetPathRootQuery, ErrorOr
|
||||
/// <returns>An <see cref="ErrorOr{TValue}"/> containing either the root of the specified path, or an error.</returns>
|
||||
public ValueTask<ErrorOr<PathSegmentResponse>> Handle(GetPathRootQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<PathSegment> result = _pathService.GetPathRoot(request.Path!);
|
||||
return ValueTask.FromResult(result.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
|
||||
ErrorOr<PathSegment> getPathRootResult = _pathService.GetPathRoot(request.Path!);
|
||||
return ValueTask.FromResult(getPathRootResult.Match(values => ErrorOrFactory.From(values.ToResponse()), errors => errors));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -35,7 +35,7 @@ public class GetThumbnailQueryHandler : IRequestHandler<GetThumbnailQuery, Error
|
||||
/// <returns>An <see cref="ErrorOr{T}"/> containing either a thumbnail, or an error.</returns>
|
||||
public async ValueTask<ErrorOr<ThumbnailResponse>> Handle(GetThumbnailQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ErrorOr<Thumbnail> result = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
|
||||
return await ValueTask.FromResult(result.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
|
||||
ErrorOr<Thumbnail> getThumbnailResult = await _thumbnailsService.GetThumbnailAsync(request.Path!, request.Quality, cancellationToken);
|
||||
return await ValueTask.FromResult(getThumbnailResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors));
|
||||
}
|
||||
}
|
||||
+4
-6
@@ -1,8 +1,6 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.Seed;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
@@ -74,10 +72,10 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
{
|
||||
// check if any users already exists (admin account is only set once!)
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<IEnumerable<UserEntity>> selectUserResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (selectUserResult.IsError)
|
||||
return selectUserResult.Errors;
|
||||
else if (selectUserResult.Value.Any())
|
||||
ErrorOr<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (selectUsersResult.IsError)
|
||||
return selectUsersResult.Errors;
|
||||
else if (selectUsersResult.Value.Any())
|
||||
return Errors.Authorization.AdminAccountAlreadyCreated;
|
||||
// no users are present, register the admin one
|
||||
string? totpSecret = null;
|
||||
|
||||
+3
-5
@@ -3,9 +3,7 @@ using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Contracts.Responses.FileSystemManagement.Path;
|
||||
using Lumina.Contracts.Responses.UsersManagement;
|
||||
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
|
||||
using Mediator;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -42,9 +40,9 @@ public class CheckInitializationQueryHandler : IRequestHandler<CheckInitializati
|
||||
{
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
// if the repository reports an error, or there are no users, the application has not been initialized
|
||||
ErrorOr<IEnumerable<UserEntity>> resultSelectUser = await userRepository.GetAllAsync(cancellationToken);
|
||||
if (!resultSelectUser.IsError)
|
||||
return new InitializationResponse(resultSelectUser.Value.Any());
|
||||
ErrorOr<IEnumerable<UserEntity>> selectUsersResult = await userRepository.GetAllAsync(cancellationToken);
|
||||
if (!selectUsersResult.IsError)
|
||||
return new InitializationResponse(selectUsersResult.Value.Any());
|
||||
return new InitializationResponse(false);
|
||||
}
|
||||
}
|
||||
-1
@@ -1,6 +1,5 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Domain.Common.Enums.MediaLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||
using Mediator;
|
||||
using System;
|
||||
|
||||
+5
-5
@@ -62,11 +62,11 @@ public class AddLibraryCommandHandler : IRequestHandler<AddLibraryCommand, Error
|
||||
return insertLibraryResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// retrieve the newly saved media library from the persistence medium and return it
|
||||
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (retrievedLibraryResult.IsError)
|
||||
return retrievedLibraryResult.Errors;
|
||||
if (retrievedLibraryResult.Value is null)
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
if (getLibraryResult.Value is null)
|
||||
return Errors.Persistence.ErrorPersistingMediaLibrary;
|
||||
return retrievedLibraryResult.Value.ToResponse();
|
||||
return getLibraryResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+10
-10
@@ -46,13 +46,13 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
{
|
||||
// get a library repository
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (resultGetLibrary.IsError)
|
||||
return resultGetLibrary.Errors;
|
||||
else if (resultGetLibrary.Value is null)
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
else if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
// if the user that made the request is not an Admin or is not the owner of the library, they do not have the right to update it
|
||||
if (resultGetLibrary.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too
|
||||
if (getLibraryResult.Value.UserId != request.CurrentUserId) // TODO: after implementing the Admin role, add that permission check here too
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// create a domain library object
|
||||
@@ -75,11 +75,11 @@ public class UpdateLibraryCommandHandler : IRequestHandler<UpdateLibraryCommand,
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// retrieve the updated media library from the persistence medium and return it
|
||||
ErrorOr<LibraryEntity?> retrievedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (retrievedLibraryResult.IsError)
|
||||
return retrievedLibraryResult.Errors;
|
||||
if (retrievedLibraryResult.Value is null)
|
||||
ErrorOr<LibraryEntity?> getCreatedLibraryResult = await libraryRepository.GetByIdAsync(createLibraryResult.Value.Id.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getCreatedLibraryResult.IsError)
|
||||
return getCreatedLibraryResult.Errors;
|
||||
if (getCreatedLibraryResult.Value is null)
|
||||
return ApplicationErrors.Persistence.ErrorPersistingMediaLibrary;
|
||||
return retrievedLibraryResult.Value.ToResponse();
|
||||
return getCreatedLibraryResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,8 @@ namespace Lumina.Application.Core.MediaLibrary.Management.Queries;
|
||||
/// Query for getting a media library by its Id.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the media library to get.</param>
|
||||
/// <param name="UserId">The Id os the user requesting the media library.</param>
|
||||
[DebuggerDisplay("Path: {Path}")]
|
||||
/// <param name="UserId">The Id of the user requesting the media library.</param>
|
||||
[DebuggerDisplay("Id: {Id}")]
|
||||
public record GetLibraryQuery(
|
||||
Guid Id,
|
||||
Guid UserId
|
||||
|
||||
+6
-6
@@ -42,14 +42,14 @@ public class GetLibraryQueryHandler : IRequestHandler<GetLibraryQuery, ErrorOr<L
|
||||
public async ValueTask<ErrorOr<LibraryResponse>> Handle(GetLibraryQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
ILibraryRepository libraryRepository = _unitOfWork.GetRepository<ILibraryRepository>();
|
||||
ErrorOr<LibraryEntity?> resultGetLibrary = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (resultGetLibrary.IsError)
|
||||
return resultGetLibrary.Errors;
|
||||
else if (resultGetLibrary.Value is null)
|
||||
ErrorOr<LibraryEntity?> getLibraryResult = await libraryRepository.GetByIdAsync(request.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsError)
|
||||
return getLibraryResult.Errors;
|
||||
else if (getLibraryResult.Value is null)
|
||||
return DomainErrors.Library.LibraryNotFound;
|
||||
// if the user that requested the library is not an Admin or is not the owner of the library, they do not have the right to view it
|
||||
if (resultGetLibrary.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too
|
||||
if (getLibraryResult.Value.UserId != request.UserId) // TODO: after implementing the Admin role, add that permission check here too
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
return resultGetLibrary.Value.ToResponse();
|
||||
return getLibraryResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+11
-11
@@ -46,22 +46,22 @@ public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordComman
|
||||
public async ValueTask<ErrorOr<ChangePasswordResponse>> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
// validate if the current password is correct
|
||||
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.CurrentPassword!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
return Errors.Authentication.InvalidCurrentPassword;
|
||||
resultSelectUser.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
|
||||
getUserResult.Value.Password = Uri.EscapeDataString(_hashService.HashString(request.NewPassword!));
|
||||
// if the password change was initiated via a password reset, remote the temporary password that was generated in the process
|
||||
resultSelectUser.Value.TempPassword = null;
|
||||
resultSelectUser.Value.TempPasswordCreated = null;
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
// update the user
|
||||
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultUpdateUser.IsError)
|
||||
return resultUpdateUser.Errors;
|
||||
ErrorOr<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsError)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new ChangePasswordResponse(true);
|
||||
}
|
||||
|
||||
+12
-12
@@ -56,29 +56,29 @@ public class RecoverPasswordCommandHandler : IRequestHandler<RecoverPasswordComm
|
||||
{
|
||||
// check if any users already exists
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
else if (resultSelectUser.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||
else if (getUserResult.Value.TempPassword is not null) // if a temp password is present, a password request was already requested
|
||||
return Errors.Authentication.PasswordResetAlreadyRequested;
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (!usesTotp)
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
// hash the new password and assign it to a temporary password that will be valid 15 minutes
|
||||
resultSelectUser.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||
resultSelectUser.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||
getUserResult.Value.TempPassword = Uri.EscapeDataString(_hashService.HashString("Abcd123$")); // TODO: replace with random password generator
|
||||
getUserResult.Value.TempPasswordCreated = DateTime.UtcNow;
|
||||
// update the user
|
||||
ErrorOr<Updated> resultUpdateUser = await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultUpdateUser.IsError)
|
||||
return resultUpdateUser.Errors;
|
||||
ErrorOr<Updated> updateUserResult = await userRepository.UpdateAsync(getUserResult.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (updateUserResult.IsError)
|
||||
return updateUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new RecoverPasswordResponse(true);
|
||||
}
|
||||
|
||||
+7
-7
@@ -65,10 +65,10 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
{
|
||||
// check if any users already exists (admin account is only set once!)
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is not null)
|
||||
ErrorOr<UserEntity?> getUserRResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserRResult.IsError)
|
||||
return getUserRResult.Errors;
|
||||
else if (getUserRResult.Value is not null)
|
||||
return Errors.Authentication.UsernameAlreadyExists;
|
||||
string? totpSecret = null;
|
||||
Guid id = Guid.NewGuid();
|
||||
@@ -94,9 +94,9 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
user.TotpSecret = _cryptographyService.Encrypt(Convert.ToBase64String(secret));
|
||||
}
|
||||
// insert the user
|
||||
ErrorOr<Created> resultInsertUser = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (resultInsertUser.IsError)
|
||||
return resultInsertUser.Errors;
|
||||
ErrorOr<Created> insertUserResult = await userRepository.InsertAsync(user, cancellationToken).ConfigureAwait(false);
|
||||
if (insertUserResult.IsError)
|
||||
return insertUserResult.Errors;
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
// TODO: insert the default admin profile preferences when they are implemented
|
||||
// if 2FA was enabled, the TOTP secret needs to be delivered to the client unhashed, so it can be displayed
|
||||
|
||||
+15
-15
@@ -65,29 +65,29 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
{
|
||||
// check if any users already exists
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
ErrorOr<UserEntity?> resultSelectUser = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (resultSelectUser.IsError)
|
||||
return resultSelectUser.Errors;
|
||||
else if (resultSelectUser.Value is null)
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByUsernameAsync(request.Username!, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
// validate that the password is correct
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.Password!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.Password!)))
|
||||
{
|
||||
// if a password reset was requested, a temp password is being used - if the hash check failed against the regular password, try against the temp one too
|
||||
if (resultSelectUser.Value.TempPassword is not null)
|
||||
if (getUserResult.Value.TempPassword is not null)
|
||||
{
|
||||
// the temporary password should only be valid for 15 minutes, if its obsolete, remove it and return error
|
||||
if (resultSelectUser.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
|
||||
if (getUserResult.Value.TempPasswordCreated!.Value.AddMinutes(15) < _dateTimeProvider.UtcNow)
|
||||
{
|
||||
resultSelectUser.Value.TempPassword = null;
|
||||
resultSelectUser.Value.TempPasswordCreated = null;
|
||||
await userRepository.UpdateAsync(resultSelectUser.Value, cancellationToken);
|
||||
getUserResult.Value.TempPassword = null;
|
||||
getUserResult.Value.TempPasswordCreated = null;
|
||||
await userRepository.UpdateAsync(getUserResult.Value, cancellationToken);
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||
return Errors.Authentication.TempPasswordExpired;
|
||||
}
|
||||
else // temporary password is still valid, validate password against it
|
||||
{
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(resultSelectUser.Value.TempPassword!)))
|
||||
if (!_hashService.CheckStringAgainstHash(request.Password!, Uri.UnescapeDataString(getUserResult.Value.TempPassword!)))
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
}
|
||||
}
|
||||
@@ -95,14 +95,14 @@ public class LoginUserQueryHandler : IRequestHandler<LoginUserQuery, ErrorOr<Log
|
||||
return Errors.Authentication.InvalidUsernameOrPassword;
|
||||
}
|
||||
// create the JWT token
|
||||
string token = _jwtTokenGenerator.GenerateToken(resultSelectUser.Value.Id.ToString(), resultSelectUser.Value.Username);
|
||||
string token = _jwtTokenGenerator.GenerateToken(getUserResult.Value.Id.ToString(), getUserResult.Value.Username);
|
||||
// check if the user uses TOTP
|
||||
bool usesTotp = !string.IsNullOrEmpty(resultSelectUser.Value.TotpSecret);
|
||||
bool usesTotp = !string.IsNullOrEmpty(getUserResult.Value.TotpSecret);
|
||||
if (usesTotp && string.IsNullOrEmpty(request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
else if (usesTotp && !string.IsNullOrEmpty(request.TotpCode)) // and if they do, validate it
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(resultSelectUser.Value.TotpSecret!)), request.TotpCode))
|
||||
if (!_totpTokenGenerator.ValidateToken(Convert.FromBase64String(_cryptographyService.Decrypt(getUserResult.Value.TotpSecret!)), request.TotpCode))
|
||||
return Errors.Authentication.InvalidTotpCode;
|
||||
return new LoginResponse(resultSelectUser.Value.Id, resultSelectUser.Value.Username, token, usesTotp);
|
||||
return new LoginResponse(getUserResult.Value.Id, getUserResult.Value.Username, token, usesTotp);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -15,4 +15,4 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public record GetAuthorizationQuery(
|
||||
Guid? UserId
|
||||
) : IRequest<ErrorOr<GetAuthorizationResponse>>;
|
||||
) : IRequest<ErrorOr<AuthorizationResponse>>;
|
||||
+10
-11
@@ -6,7 +6,6 @@ using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Mapping.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Lumina.Domain.Common.Enums.Authorization;
|
||||
using Mediator;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
@@ -18,13 +17,13 @@ namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetAutho
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the authorization roles and permissions of an account.
|
||||
/// </summary>
|
||||
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<GetAuthorizationResponse>>
|
||||
public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuery, ErrorOr<AuthorizationResponse>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AuthorizationService"/> class.
|
||||
/// Initializes a new instance of the <see cref="GetAuthorizationQueryHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
@@ -40,22 +39,22 @@ public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuer
|
||||
/// <param name="request">The request to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="GetAuthorizationResponse"/>, or an error message.
|
||||
/// An <see cref="ErrorOr{TValue}"/> containing either a <see cref="AuthorizationResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<GetAuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
|
||||
public async ValueTask<ErrorOr<AuthorizationResponse>> Handle(GetAuthorizationQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// first, check if the Id of the user for whom to get the permission list is different from the Id currently making the request
|
||||
if (_currentUserService.UserId != request.UserId)
|
||||
{
|
||||
// if it is, get the role of the current user, and see if they are Admin
|
||||
ErrorOr<UserAuthorizationEntity> resultGetCurrentUserPermission = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (resultGetCurrentUserPermission.IsError)
|
||||
return resultGetCurrentUserPermission.Errors;
|
||||
ErrorOr<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getCurrentUserPermissionResult.IsError)
|
||||
return getCurrentUserPermissionResult.Errors;
|
||||
// if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request
|
||||
if (!resultGetCurrentUserPermission.Value.Roles.Any(role => role == AuthorizationRole.Admin))
|
||||
if (!getCurrentUserPermissionResult.Value.Roles.Any(role => role == "Admin"))
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
}
|
||||
ErrorOr<UserAuthorizationEntity> resultGetUserPermission = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
return resultGetUserPermission.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
|
||||
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
return getUserPermissionResult.Match(value => ErrorOrFactory.From(value.ToResponse()), errors => errors);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user