Refactors current user identity handling in handlers

This commit is contained in:
BinaryAlley committed 2026-08-16 04:59:44 -07:00
1 parent a7dfcbe926
commit f0a1942691
28 files changed
+336 -30

No files matched your search

@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -48,8 +49,14 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
/// </returns>
public async Task<Result<IEnumerable<PermissionResponse>>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the list of authorization permissions
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -57,8 +58,14 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can create authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -56,8 +56,14 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can delete authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -57,8 +58,14 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can update authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -56,8 +57,14 @@ public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQu
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the role from the repository and return its role permissions
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -48,8 +49,14 @@ public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, Result<IEnumera
/// </returns>
public async Task<Result<IEnumerable<RoleResponse>>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the list of authorization roles
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
@@ -79,9 +79,15 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
if (validationResult.Count > 0)
return validationResult;
// if the user that made the request is not an Admin or they don't have the permission to manage media libraries, they do not have the right to create it
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins or users with the permission to manage media libraries can create them
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
return ApplicationErrors.Authorization.NotAuthorized;
// make sure the file is an actual supported image
@@ -100,7 +106,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
// create a domain library object
Result<Library> createLibraryResult = Library.Create(
UserId.Create(_currentUserService.UserId!.Value),
UserId.Create(userId),
command.Title!,
Enum.Parse<LibraryType>(command.LibraryType!),
command.ContentLocations!,
@@ -8,9 +8,11 @@ using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.Errors;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -56,6 +58,12 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<Success>> HandleAsync(CancelLibrariesScanCommand command, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the running library scans of the current user from the repository
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
if (getRunningLibraryScansResult.IsFailure)
@@ -64,10 +72,10 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
// filter the library scans to process
List<LibraryScanEntity> authorizedLibraryScans = [];
// admins can see all library scans
if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
else // for regular users, only take the library scans that belong to them
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == _currentUserService.UserId));
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value.Where(libraryScan => libraryScan.UserId == userId));
// convert persistence library scans to domain entities
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
@@ -8,12 +8,14 @@ using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Application.Common.Errors;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -59,6 +61,12 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
public async Task<Result<IEnumerable<MediaLibraryScanResponse>>> HandleAsync(ScanLibrariesCommand command, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get all media libraries that are enabled and unlocked from the persistence medium
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
@@ -68,8 +76,8 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
IEnumerable<Result<Library>> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities();
// if the current user is not an admin, they can only scan the libraries that belong to them
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value);
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId);
List<MediaLibraryScanResponse> responses = [];
List<IDomainEvent> domainEvents = [];
@@ -95,7 +103,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
// start the media library scan
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
LibraryId.Create(domainLibraryResult.Value.Id.Value),
UserId.Create(_currentUserService.UserId!.Value),
UserId.Create(userId),
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
);
if (libraryScanResult.IsFailure)
@@ -4,10 +4,12 @@ using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
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.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -51,19 +53,25 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibraries
/// </returns>
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the enabled libraries from the repository
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
if (getEnabledLibrariesResult.IsFailure)
return getEnabledLibrariesResult.Errors;
// admins can see all libraries
if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return Result.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
else
{
// for regular users, only take the libraries that belong to them
LibraryResponse[] userEnabledLibraries = [.. getEnabledLibrariesResult.Value
.Where(library => library.UserId == _currentUserService.UserId)
.Where(library => library.UserId == userId)
.Select(library => library.ToResponse())];
return Result.From(userEnabledLibraries);
@@ -4,10 +4,12 @@ using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
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.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -51,19 +53,25 @@ public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, Result<
/// </returns>
public async Task<Result<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the libraries from the repository
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
if (getLibrariesResult.IsFailure)
return getLibrariesResult.Errors;
// admins can see all libraries
if (await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
return Result.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
else
{
// for regular users, only take the libraries that belong to them
LibraryResponse[] userLibraries = [.. getLibrariesResult.Value
.Where(library => library.UserId == _currentUserService.UserId)
.Where(library => library.UserId == userId)
.Select(library => library.ToResponse())];
return Result.From(userLibraries);
@@ -4,6 +4,7 @@ using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
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.MediaLibrary.Management;
@@ -11,6 +12,7 @@ using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -58,19 +60,24 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
/// </returns>
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// get the ongoing library scans from the repository
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
if (getRunningScansResult.IsFailure)
return getRunningScansResult.Errors;
// filter the library scans by what the user is allowed to see
// filter the library scans by what the user is allowed to see: admins see all libraries, regular users only their own
LibraryScanEntity[] userRunningRepositoryLibraryScans = [];
// admins can see all libraries
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
else // for regular users, only take the libraries that belong to them
else
userRunningRepositoryLibraryScans = getRunningScansResult.Value
.Where(libraryScan => libraryScan.UserId == _currentUserService.UserId).ToArray();
.Where(libraryScan => libraryScan.UserId == userId).ToArray();
// for each of the filtered library scans, get their progress
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Application.Common.Mapping.UsersManagement.Users;
using Lumina.Contracts.Responses.UsersManagement.Users;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -49,8 +50,14 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
/// </returns>
public async Task<Result<IEnumerable<UserResponse>>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken)
{
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the list of users
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
Result<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
@@ -60,8 +60,14 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return ApplicationErrors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can update user authorizations
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return ApplicationErrors.Authorization.NotAuthorized;
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -52,11 +53,17 @@ public class GetAuthorizationQueryHandler : IQueryHandler<GetAuthorizationQuery,
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// 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 != query.UserId)
if (userId != query.UserId)
{
// if it is, get the role of the current user, and see if they are Admin
Result<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(_currentUserService.UserId!.Value, cancellationToken).ConfigureAwait(false);
Result<UserAuthorizationEntity> getCurrentUserPermissionResult = await _authorizationService.GetUserAuthorizationAsync(userId, cancellationToken).ConfigureAwait(false);
if (getCurrentUserPermissionResult.IsFailure)
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
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -57,8 +58,14 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the list of authorization permissions
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its permissions
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.Authorization;
using Lumina.Contracts.Responses.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -56,8 +57,14 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
if (validationResult.Count > 0)
return validationResult;
// an authenticated request must always carry a user identity
Guid? currentUserId = _currentUserService.UserId;
if (currentUserId is null)
return Errors.Authorization.NotAuthorized;
Guid userId = currentUserId.Value;
// only admins can see the authorization role
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return Errors.Authorization.NotAuthorized;
// get the user from the repository and return its roles
@@ -98,6 +98,23 @@ public class GetPermissionsQueryHandlerTests
await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetPermissionsQuery query = new();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<PermissionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetAllPermissionsReturnsError_ShouldReturnError()
{
@@ -76,6 +76,23 @@ public class AddRoleCommandHandlerTests
await _mockRoleRepository.DidNotReceive().InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
AddRoleCommand command = _addRoleCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<RolePermissionsResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError()
{
@@ -73,6 +73,23 @@ public class DeleteRoleCommandHandlerTests
await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
DeleteRoleCommand command = _deleteRoleCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError()
{
@@ -76,6 +76,23 @@ public class UpdateRoleCommandHandlerTests
await _mockRoleRepository.DidNotReceive().UpdateAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateRoleCommand command = _updateRoleCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<RolePermissionsResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().UpdateAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError()
{
@@ -75,6 +75,23 @@ public class GetRolePermissionsQueryHandlerTests
await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetRolePermissionsQuery query = _getRolePermissionsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<RolePermissionsResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
{
@@ -70,6 +70,23 @@ public class GetRolesQueryHandlerTests
await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetRolesQuery query = _getRolesQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<RoleResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError()
{
@@ -73,6 +73,23 @@ public class GetUsersQueryHandlerTests
await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUsersQuery query = _getUsersQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<UserResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError()
{
@@ -88,6 +88,23 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
UpdateUserRoleAndPermissionsCommand command = _updateUserRoleAndPermissionsCommandFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<AuthorizationResponse> result = await _sut.HandleAsync(command, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError()
{
@@ -112,6 +112,22 @@ public class GetAuthorizationQueryHandlerTests
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetAuthorizationQuery query = _getAuthorizationQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<AuthorizationResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().GetUserAuthorizationAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetCurrentUserAuthorizationFails_ShouldReturnError()
{
@@ -77,6 +77,23 @@ public class GetUserPermissionsQueryHandlerTests
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUserPermissionsQuery query = _getUserPermissionsQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<IEnumerable<PermissionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
{
@@ -76,6 +76,23 @@ public class GetUserRoleQueryHandlerTests
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
{
// Arrange
GetUserRoleQuery query = _getUserRoleQueryFixture.Create();
_mockCurrentUserService.UserId.Returns((Guid?)null);
// Act
Result<RoleResponse?> result = await _sut.HandleAsync(query, CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
{