Adds library ownership authorization policy

This commit is contained in:
BinaryAlley committed 2026-08-16 04:59:06 -07:00
1 parent 65a630155d
commit a7dfcbe926
23 files changed
+645 -202

No files matched your search

@@ -34,13 +34,14 @@ public interface IAuthorizationService
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken);
/// <summary>
/// Evaluates whether the specified user meets the conditions defined in the specified authorization policy.
/// Evaluates whether the specified user meets the conditions defined in the specified authorization policy, against the resource described by <paramref name="context"/>.
/// </summary>
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
/// <param name="userId">The unique identifier of the user for whom to evaluate the policy.</param>
/// <param name="context">The context describing the resource against which the policy is evaluated. Can be <see langword="null"/> for policies that do not require a resource.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the user satisfies the policy, <see langword="false"/> otherwise.</returns>
Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy;
Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, PolicyContext? context, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy;
/// <summary>
/// Retrieves all authorization roles and permissions of a user identified by <paramref name="userId"/>.
@@ -12,10 +12,11 @@ namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.Common
public interface IAuthorizationPolicy
{
/// <summary>
/// Evaluates a policy for a user identified by <paramref name="userId"/>.
/// Evaluates a policy for a user identified by <paramref name="userId"/> against the resource described by <paramref name="context"/>.
/// </summary>
/// <param name="userId">The unique identifier of the user for which to evaluate the policy.</param>
/// <param name="context">The context describing the resource against which the policy is evaluated. Can be <see langword="null"/> for policies that do not require a resource.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns><see langword="true"/> if the policy evaluation succeeds, <see langword="false"/> otherwise.</returns>
Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken);
Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken);
}
@@ -0,0 +1,6 @@
namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
/// <summary>
/// Represents the contextual information required to evaluate an authorization policy against a specific resource.
/// </summary>
public abstract record PolicyContext;
@@ -0,0 +1,12 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
/// <summary>
/// Interface for the library ownership authorization policy.
/// </summary>
public interface ILibraryOwnershipPolicy : IAuthorizationPolicy
{
}
@@ -0,0 +1,14 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
/// <summary>
/// Represents the context required to evaluate the library ownership authorization policy.
/// </summary>
/// <param name="LibraryId">The Id of the media library whose access is being evaluated.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public sealed record LibraryOwnershipPolicyContext(Guid LibraryId) : PolicyContext;
@@ -7,10 +7,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -65,6 +67,12 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
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;
// get the library scan from the repository
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
if (getLibraryScansResult.IsFailure)
@@ -72,9 +80,10 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
if (getLibraryScansResult.Value is null)
return DomainErrors.LibraryScanning.LibraryScanNotFound;
// if the user that wants to scan the library is not an Admin or is not the owner of the library, they do not have the right to scan it
if (getLibraryScansResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
// admins can cancel any library scan; for everyone else, only the ones of the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(getLibraryScansResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// convert the repository scan to a domain object
@@ -7,10 +7,12 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Domain.Common.Events;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -65,6 +67,12 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
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;
// get the library with the specified id from the repository
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
@@ -72,9 +80,10 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
else if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that wants to delete the library is not an Admin or is not the owner of the library, they do not have the right to delete it
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
// admins can delete any library; for everyone else, only the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
@@ -16,6 +17,7 @@ using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.Library
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
@@ -71,6 +73,12 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
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;
// get the media library from the persistence medium
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
@@ -79,9 +87,10 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
if (getLibraryResult.Value is null)
return DomainErrors.Library.LibraryNotFound;
// if the user that wants to scan the library is not an Admin or is not the owner of the library, they do not have the right to scan it
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
// admins can scan any library; for everyone else, only the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// check if the library is enabled and unlocked, before scanning it
@@ -110,7 +119,7 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
// queue the media library scan
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
LibraryId.Create(command.Id),
UserId.Create(_currentUserService.UserId!.Value),
UserId.Create(userId),
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
);
if (libraryScanResult.IsFailure)
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DomainEvents;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
@@ -82,6 +83,12 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
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;
// make sure the file is an actual supported image
if (command.CoverImage is not null)
{
@@ -103,10 +110,11 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
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 (getLibraryResult.Value.UserId != _currentUserService.UserId ||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken)))
// admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own
bool hasManagePermission = await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false);
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
if (!hasManagePermission && !canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
// create a domain library object
@@ -6,10 +6,12 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -62,6 +64,12 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
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;
// get the library with the specified id from the repository
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
@@ -69,9 +77,10 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
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 (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
// admins can see all libraries; for everyone else, only the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Id), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
return getLibraryResult.Value.ToResponse();
@@ -6,6 +6,7 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
using Lumina.Contracts.Responses.MediaLibrary.Management;
@@ -13,6 +14,7 @@ using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -69,6 +71,12 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
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;
// get the library with the specified id from the repository
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure)
@@ -76,13 +84,14 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
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 view its scan progress
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
// admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return ApplicationErrors.Authorization.NotAuthorized;
Result<MediaLibraryScanProgress> getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(_currentUserService.UserId!.Value)));
MediaLibraryScanCompositeId.Create(ScanId.Create(query.ScanId), UserId.Create(userId)));
if (getProgressResult.IsFailure)
return getProgressResult.Errors;
@@ -6,15 +6,16 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Contracts.Responses.Common;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DTO.Pagination;
#endregion
@@ -59,14 +60,17 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<Paginate
if (validationResult.Count > 0)
return validationResult;
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin) // if its not an admin, then it must own the library
{
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
return Errors.Authorization.NotAuthorized;
}
// 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;
// admins can see all libraries; for everyone else, only the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return Errors.Authorization.NotAuthorized;
// get all books of the media library from the book repository
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
@@ -6,15 +6,16 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Lumina.Contracts.Responses.Common;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Errors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DTO.Pagination;
#endregion
@@ -59,14 +60,17 @@ public class GetBooksLiteQueryHandler : IQueryHandler<GetBooksLiteQuery, Result<
if (validationResult.Count > 0)
return validationResult;
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
if (!isAdmin) // if its not an admin, then it must own the library
{
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
return Errors.Authorization.NotAuthorized;
}
// 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;
// admins can see all libraries; for everyone else, only the libraries they own
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(query.Filter.LibraryId), cancellationToken).ConfigureAwait(false);
if (!canAccessLibrary)
return Errors.Authorization.NotAuthorized;
// get all books of the media library from the book repository
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(