mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-02 22:11:10 +00:00
Adds authorization permissions administrator dashboard
This commit is contained in:
1 parent
152cb48050
commit
583b8db865
106 files changed
+5916
-2085
No files matched your search
+2
-2
@@ -19,9 +19,9 @@ public class UserAuthorizationEntity
|
||||
public required Guid UserId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of roles associated to the user.
|
||||
/// Gets the role associated to the user.
|
||||
/// </summary>
|
||||
public required IReadOnlySet<string> Roles { get; init; }
|
||||
public required string? Role { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of permissions associated to the user.
|
||||
|
||||
@@ -51,9 +51,9 @@ public class UserEntity : IStorageEntity, IAuditableEntity
|
||||
public required ICollection<LibraryEntity> Libraries { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of user roles associations that include this user.
|
||||
/// Gets the user roles association that includes this user.
|
||||
/// </summary>
|
||||
public required ICollection<UserRoleEntity> UserRoles { get; init; } = [];
|
||||
public required UserRoleEntity? UserRole { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the collection of user permission associations that include this user.
|
||||
|
||||
@@ -25,5 +25,7 @@ public static partial class Errors
|
||||
public static Error PermissionIdCannotBeEmpty => Error.Validation(description: nameof(PermissionIdCannotBeEmpty));
|
||||
public static Error RoleNameCannotBeEmpty => Error.Validation(description: nameof(RoleNameCannotBeEmpty));
|
||||
public static Error RoleNameCannotBeNull => Error.Validation(description: nameof(RoleNameCannotBeNull));
|
||||
public static Error CannotRemoveLastAdmin => Error.Forbidden(description: nameof(CannotRemoveLastAdmin));
|
||||
public static Error UserMustHaveRoleOrDirectPermissions => Error.Forbidden(description: nameof(UserMustHaveRoleOrDirectPermissions));
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetUserPermissionsRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetUserPermissionsRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetUserPermissionsQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetUserPermissionsQuery ToQuery(this GetUserPermissionsRequest request)
|
||||
{
|
||||
return new GetUserPermissionsQuery(
|
||||
request.UserId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetUserRoleRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetUserRoleRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetUserRoleQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetUserRoleQuery ToQuery(this GetUserRoleRequest request)
|
||||
{
|
||||
return new GetUserRoleQuery(
|
||||
request.UserId
|
||||
);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
|
||||
using Lumina.Contracts.Requests.Authorization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="UpdateUserRoleAndPermissionsRequest"/>.
|
||||
/// </summary>
|
||||
public static class UpdateUserRoleAndPermissionsRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="UpdateUserRoleAndPermissionsCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static UpdateUserRoleAndPermissionsCommand ToCommand(this UpdateUserRoleAndPermissionsRequest request)
|
||||
{
|
||||
return new UpdateUserRoleAndPermissionsCommand(
|
||||
request.UserId!.Value,
|
||||
request.RoleId,
|
||||
request.Permissions!
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ public static class UserAuthorizationEntityMapping
|
||||
{
|
||||
return new AuthorizationResponse(
|
||||
repositoryEntity.UserId,
|
||||
repositoryEntity.Roles,
|
||||
repositoryEntity.Role,
|
||||
repositoryEntity.Permissions
|
||||
);
|
||||
}
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ namespace Lumina.Application.Core.Admin.Authorization.Roles.Commands.UpdateRole;
|
||||
/// </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>
|
||||
/// <param name="Permissions">The collection of Ids of the permissions of the role.</param>
|
||||
[DebuggerDisplay("RoleName: {RoleName}")]
|
||||
public record UpdateRoleCommand(
|
||||
Guid RoleId,
|
||||
|
||||
+1
@@ -51,6 +51,7 @@ public class GetRolePermissionsQueryHandler : IRequestHandler<GetRolePermissions
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
// get the role from the repository and return its role permissions
|
||||
ErrorOr<RoleEntity?> getRoleResult = await _roleRepository.GetByIdAsync(request.RoleId, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError)
|
||||
return getRoleResult.Errors;
|
||||
|
||||
+2
-2
@@ -87,8 +87,8 @@ public class SetupApplicationCommandHandler : IRequestHandler<SetupApplicationCo
|
||||
Password = Uri.EscapeDataString(_hashService.HashString(request.Password!)),
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRoles = [],
|
||||
UserPermissions = [],
|
||||
UserRole = null,
|
||||
CreatedBy = id
|
||||
};
|
||||
// if the user enabled two factor auth, include a QR with the totp secret
|
||||
|
||||
+2
-2
@@ -18,8 +18,8 @@ public class AddLibraryCommandValidator : AbstractValidator<AddLibraryCommand>
|
||||
public AddLibraryCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.LibraryType)
|
||||
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
|
||||
|
||||
+4
-4
@@ -22,12 +22,12 @@ public class UpdateLibraryCommandValidator : AbstractValidator<UpdateLibraryComm
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.CurrentUserId)
|
||||
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.OwnerId)
|
||||
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.LibraryType)
|
||||
.NotNull().WithMessage(Errors.Library.LibraryTypeCannotBeNull.Description)
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ public class GetLibraryQueryValidator : AbstractValidator<GetLibraryQuery>
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.LibraryIdCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage(Errors.Library.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Library.UserIdCannotBeEmpty.Description);
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -80,7 +80,7 @@ public class RegisterUserCommandHandler : IRequestHandler<RegisterUserCommand, E
|
||||
CreatedOnUtc = _dateTimeProvider.UtcNow,
|
||||
Libraries = [],
|
||||
UserPermissions = [],
|
||||
UserRoles = [],
|
||||
UserRole = null,
|
||||
CreatedBy = id
|
||||
};
|
||||
// if the user enabled two factor auth, include a QR with the totp secret
|
||||
|
||||
+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.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Command for updating the authorization role and permissions of a user.
|
||||
/// </summary>
|
||||
/// <param name="UserId">The Id of the user.</param>
|
||||
/// <param name="RoleId">The Id of the role.</param>
|
||||
/// <param name="Permissions">The collection of Ids of the permissions of the user.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public record UpdateUserRoleAndPermissionsCommand(
|
||||
Guid UserId,
|
||||
Guid? RoleId,
|
||||
List<Guid> Permissions
|
||||
) : IRequest<ErrorOr<AuthorizationResponse>>;
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
#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.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Contracts.Responses.Authorization;
|
||||
using Mediator;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to update an authorization role.
|
||||
/// </summary>
|
||||
public class UpdateUserRoleAndPermissionsCommandHandler : IRequestHandler<UpdateUserRoleAndPermissionsCommand, ErrorOr<AuthorizationResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsCommandHandler"/> 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 UpdateUserRoleAndPermissionsCommandHandler(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<AuthorizationResponse>> Handle(UpdateUserRoleAndPermissionsCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can update user authorizations
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// get repositories
|
||||
IUserRepository userRepository = _unitOfWork.GetRepository<IUserRepository>();
|
||||
IRoleRepository roleRepository = _unitOfWork.GetRepository<IRoleRepository>();
|
||||
IPermissionRepository permissionRepository = _unitOfWork.GetRepository<IPermissionRepository>();
|
||||
|
||||
// get the user to update
|
||||
ErrorOr<UserEntity?> getUserResult = await userRepository.GetByIdAsync(request.UserId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError || getUserResult.Value is null)
|
||||
return DomainErrors.Users.UserDoesNotExist;
|
||||
|
||||
ErrorOr<RoleEntity?> getRoleResult = default;
|
||||
if (request.RoleId is not null)
|
||||
{
|
||||
// get the new role
|
||||
getRoleResult = await roleRepository.GetByIdAsync(request.RoleId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getRoleResult.IsError || getRoleResult.Value is null)
|
||||
return ApplicationErrors.Authorization.RoleNotFound;
|
||||
|
||||
// check if we're changing an admin's role and if this would leave us without admins
|
||||
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin" && getRoleResult.Value.RoleName != "Admin")
|
||||
{
|
||||
// count how many admins we have
|
||||
ErrorOr<IEnumerable<UserEntity>> getAllUsersResult = await userRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (getAllUsersResult.IsError)
|
||||
return getAllUsersResult.Errors;
|
||||
|
||||
int adminCount = getAllUsersResult.Value.Count(user => user.UserRole?.Role.RoleName == "Admin");
|
||||
if (adminCount <= 1)
|
||||
return ApplicationErrors.Authorization.CannotRemoveLastAdmin;
|
||||
}
|
||||
}
|
||||
// get the permissions to assign
|
||||
ErrorOr<IEnumerable<PermissionEntity>> getPermissionsResult =
|
||||
await permissionRepository.GetByIdsAsync(request.Permissions, cancellationToken).ConfigureAwait(false);
|
||||
if (getPermissionsResult.IsError)
|
||||
return getPermissionsResult.Errors;
|
||||
|
||||
// update the user
|
||||
UserEntity userToUpdate = getUserResult.Value;
|
||||
|
||||
UserRoleEntity? userRole = default!;
|
||||
if (request.RoleId is not null)
|
||||
{
|
||||
userRole = new()
|
||||
{
|
||||
UserId = userToUpdate.Id,
|
||||
RoleId = request.RoleId.Value,
|
||||
Role = getRoleResult.Value!,
|
||||
User = userToUpdate
|
||||
};
|
||||
}
|
||||
|
||||
UserEntity updatedUser = new()
|
||||
{
|
||||
Id = userToUpdate.Id,
|
||||
Username = userToUpdate.Username,
|
||||
Password = userToUpdate.Password,
|
||||
TempPassword = userToUpdate.TempPassword,
|
||||
TotpSecret = userToUpdate.TotpSecret,
|
||||
TempPasswordCreated = userToUpdate.TempPasswordCreated,
|
||||
Libraries = userToUpdate.Libraries,
|
||||
UserRole = userRole,
|
||||
UserPermissions = request.Permissions.Select(permissionId => new UserPermissionEntity
|
||||
{
|
||||
UserId = userToUpdate.Id,
|
||||
PermissionId = permissionId,
|
||||
Permission = getPermissionsResult.Value.First(permission => permission.Id == permissionId),
|
||||
User = userToUpdate
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
// save changes and return result
|
||||
ErrorOr<Updated> updateResult = await userRepository.UpdateAsync(updatedUser, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsError)
|
||||
return updateResult.Errors;
|
||||
|
||||
await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new AuthorizationResponse(
|
||||
userToUpdate.Id,
|
||||
getRoleResult.Value?.RoleName,
|
||||
userToUpdate.UserPermissions
|
||||
.Select(up => up.Permission.PermissionName)
|
||||
.ToHashSet()
|
||||
);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Authorization.Commands.UpdateUserRoleAndPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="UpdateUserRoleAndPermissionsCommand"/>.
|
||||
/// </summary>
|
||||
public class UpdateUserRoleAndPermissionsCommandValidator : AbstractValidator<UpdateUserRoleAndPermissionsCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UpdateUserRoleAndPermissionsCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public UpdateUserRoleAndPermissionsCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(DomainErrors.Users.UserIdCannotBeEmpty.Description);
|
||||
|
||||
// validate Permissions only if provided
|
||||
When(x => x.Permissions != null && x.Permissions.Count != 0, () =>
|
||||
{
|
||||
RuleForEach(x => x.Permissions)
|
||||
.NotEmpty().WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(ApplicationErrors.Authorization.PermissionIdCannotBeEmpty.Description);
|
||||
});
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -51,7 +51,7 @@ public class GetAuthorizationQueryHandler : IRequestHandler<GetAuthorizationQuer
|
||||
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 (!getCurrentUserPermissionResult.Value.Roles.Any(role => role == "Admin"))
|
||||
if (getCurrentUserPermissionResult.Value.Role != "Admin")
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
}
|
||||
ErrorOr<UserAuthorizationEntity> getUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#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.UsersManagement.Authorization.Queries.GetUserPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Query for retrieving the authorization permissions of a user identified by <paramref name="UserId"/>.
|
||||
/// </summary>
|
||||
/// <param name="UserId">The Id of the user for whom to get the authorization permissions.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public record GetUserPermissionsQuery(
|
||||
Guid? UserId
|
||||
) : IRequest<ErrorOr<IEnumerable<PermissionResponse>>>;
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
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.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the authorization permissions of a user.
|
||||
/// </summary>
|
||||
public class GetUserPermissionsQueryHandler : IRequestHandler<GetUserPermissionsQuery, ErrorOr<IEnumerable<PermissionResponse>>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsQueryHandler"/> 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 GetUserPermissionsQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the authorization permissions of a user.
|
||||
/// </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(GetUserPermissionsQuery 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;
|
||||
// get the user from the repository and return its permissions
|
||||
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
return ErrorOrFactory.From(getUserResult.Value.UserPermissions.Select(userPermission => userPermission.Permission).ToResponses());
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetUserPermissionsQuery"/>.
|
||||
/// </summary>
|
||||
public class GetUserPermissionsQueryValidator : AbstractValidator<GetUserPermissionsQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserPermissionsQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetUserPermissionsQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.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.UsersManagement.Authorization.Queries.GetUserRole;
|
||||
|
||||
/// <summary>
|
||||
/// Query for retrieving the authorization role of a user identified by <paramref name="UserId"/>.
|
||||
/// </summary>
|
||||
/// <param name="UserId">The Id of the user for whom to get the authorization role.</param>
|
||||
[DebuggerDisplay("UserId: {UserId}")]
|
||||
public record GetUserRoleQuery(
|
||||
Guid? UserId
|
||||
) : IRequest<ErrorOr<RoleResponse?>>;
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using ErrorOr;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
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.UsersManagement.Authorization.Queries.GetUserRole;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to retrieve the authorization role of a user.
|
||||
/// </summary>
|
||||
public class GetUserRoleQueryHandler : IRequestHandler<GetUserRoleQuery, ErrorOr<RoleResponse?>>
|
||||
{
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IUserRepository _userRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleQueryHandler"/> 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 GetUserRoleQueryHandler(IAuthorizationService authorizationService, ICurrentUserService currentUserService, IUnitOfWork unitOfWork)
|
||||
{
|
||||
_authorizationService = authorizationService;
|
||||
_currentUserService = currentUserService;
|
||||
_userRepository = unitOfWork.GetRepository<IUserRepository>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to retrieve the authorization role of a user.
|
||||
/// </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 <see cref="RoleResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async ValueTask<ErrorOr<RoleResponse?>> Handle(GetUserRoleQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
// only admins can see the authorization role
|
||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
||||
if (!isAdmin)
|
||||
return Errors.Authorization.NotAuthorized;
|
||||
// get the user from the repository and return its roles
|
||||
ErrorOr<UserEntity?> getUserResult = await _userRepository.GetByIdAsync(request.UserId!.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsError)
|
||||
return getUserResult.Errors;
|
||||
else if (getUserResult.Value is null)
|
||||
return Errors.Authentication.UsernameDoesNotExist;
|
||||
return ErrorOrFactory.From(getUserResult.Value.UserRole?.Role.ToResponse());
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.UsersManagement.Authorization.Queries.GetUserRole;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetUserRoleQuery"/>.
|
||||
/// </summary>
|
||||
public class GetUserRoleQueryValidator : AbstractValidator<GetUserRoleQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserRoleQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetUserRoleQueryValidator()
|
||||
{
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage(Errors.Users.UserIdCannotBeEmpty.Description)
|
||||
.Must(id => id != Guid.Empty).WithMessage(Errors.Users.UserIdCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user