mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 04:11:10 +00:00
Adds library ownership authorization policy
This commit is contained in:
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"/>.
|
||||
|
||||
+3
-2
@@ -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);
|
||||
}
|
||||
+6
@@ -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;
|
||||
+12
@@ -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
|
||||
{
|
||||
}
|
||||
+14
@@ -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;
|
||||
+12
-3
@@ -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
|
||||
|
||||
+12
-3
@@ -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
|
||||
|
||||
+13
-4
@@ -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)
|
||||
|
||||
+12
-4
@@ -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
|
||||
|
||||
+12
-3
@@ -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();
|
||||
|
||||
+13
-4
@@ -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;
|
||||
|
||||
|
||||
+13
-9
@@ -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(
|
||||
|
||||
+13
-9
@@ -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(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
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.Authorization.Policies.Over18;
|
||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
||||
@@ -19,6 +20,7 @@ using Lumina.Infrastructure.Common.Models.DTO.Plugins;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Authorization;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Infrastructure.Core.Authorization.Policies.Over18;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||
@@ -80,6 +82,7 @@ public static class InfrastructureLayerServices
|
||||
|
||||
// authorization
|
||||
services.AddScoped<IOver18Policy, Over18Policy>();
|
||||
services.AddScoped<ILibraryOwnershipPolicy, LibraryOwnershipPolicy>();
|
||||
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
|
||||
services.AddScoped<IAuthorizationService, AuthorizationService>();
|
||||
|
||||
|
||||
@@ -75,17 +75,18 @@ public class AuthorizationService : IAuthorizationService
|
||||
}
|
||||
|
||||
/// <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>
|
||||
public async Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy
|
||||
public async Task<bool> EvaluatePolicyAsync<TAuthorizationPolicy>(Guid userId, PolicyContext? context, CancellationToken cancellationToken) where TAuthorizationPolicy : IAuthorizationPolicy
|
||||
{
|
||||
// resolve the authorization policy dynamically using the factory
|
||||
IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy<TAuthorizationPolicy>();
|
||||
return await policy.EvaluateAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
return await policy.EvaluateAsync(userId, context, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
|
||||
|
||||
/// <summary>
|
||||
/// Authorization policy that checks whether a user can access a media library: admins can access any library, while other users can only access the libraries they own.
|
||||
/// </summary>
|
||||
public class LibraryOwnershipPolicy : ILibraryOwnershipPolicy
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LibraryOwnershipPolicy"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
public LibraryOwnershipPolicy(IUnitOfWork unitOfWork)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates the policy for the user identified by <paramref name="userId"/> against the media library identified in <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 carrying the Id of the media library whose access is being evaluated.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns><see langword="true"/> if the user is an admin or owns the media library, <see langword="false"/> otherwise.</returns>
|
||||
public async Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
|
||||
{
|
||||
if (context is not LibraryOwnershipPolicyContext libraryContext)
|
||||
return false;
|
||||
|
||||
// admins can access any media library
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||
return false;
|
||||
if (getUserResult.Value.UserRole?.Role.RoleName == "Admin")
|
||||
return true;
|
||||
|
||||
// regular users can only access the media libraries they own
|
||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryContext.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||
if (getLibraryResult.IsFailure || getLibraryResult.Value is null)
|
||||
return false;
|
||||
return getLibraryResult.Value.UserId == userId;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Over18;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using System;
|
||||
@@ -32,12 +33,13 @@ public class Over18Policy : IOver18Policy
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates the policy for the user identified by <paramref name="userId"/>.
|
||||
/// Evaluates the policy for the user identified by <paramref name="userId"/>. The <paramref name="context"/> is not used by this policy.
|
||||
/// </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. Not used by this policy.</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>
|
||||
public async Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
||||
public async Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
|
||||
{
|
||||
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||
|
||||
Reference in new issue
Block a user