mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Merge pull request #150 from BinaryAlley/feature/library-ownership-policy
Feature/library ownership policy
This commit is contained in:
51 files changed
+981
-232
No files matched your search
@@ -34,13 +34,14 @@ public interface IAuthorizationService
|
|||||||
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken);
|
Task<bool> IsInRoleAsync(Guid userId, string role, CancellationToken cancellationToken);
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
|
/// <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="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>
|
/// <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>
|
/// <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>
|
/// <summary>
|
||||||
/// Retrieves all authorization roles and permissions of a user identified by <paramref name="userId"/>.
|
/// 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
|
public interface IAuthorizationPolicy
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="userId">The unique identifier of the user for which to evaluate the policy.</param>
|
/// <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>
|
/// <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>
|
/// <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;
|
||||||
+8
-1
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
|
|||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -48,8 +49,14 @@ public class GetPermissionsQueryHandler : IQueryHandler<GetPermissionsQuery, Res
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IEnumerable<PermissionResponse>>> HandleAsync(GetPermissionsQuery query, CancellationToken cancellationToken)
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<PermissionEntity>> getPermissionsResult = await _unitOfWork.PermissionRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -57,8 +58,14 @@ public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand, Result<Role
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
|
|||||||
+7
-1
@@ -56,8 +56,14 @@ public class DeleteRoleCommandHandler : ICommandHandler<DeleteRoleCommand, Resul
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -57,8 +58,14 @@ public class UpdateRoleCommandHandler : ICommandHandler<UpdateRoleCommand, Resul
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -56,8 +57,14 @@ public class GetRolePermissionsQueryHandler : IQueryHandler<GetRolePermissionsQu
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
// get the role from the repository and return its role permissions
|
// get the role from the repository and return its role permissions
|
||||||
|
|||||||
+8
-1
@@ -9,6 +9,7 @@ using Lumina.Application.Common.Infrastructure.Authentication;
|
|||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -48,8 +49,14 @@ public class GetRolesQueryHandler : IQueryHandler<GetRolesQuery, Result<IEnumera
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IEnumerable<RoleResponse>>> HandleAsync(GetRolesQuery query, CancellationToken cancellationToken)
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<RoleEntity>> getRolesResult = await _roleRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+10
-4
@@ -79,9 +79,15 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// an authenticated request must always carry a user identity
|
||||||
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
|
Guid? currentUserId = _currentUserService.UserId;
|
||||||
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false))
|
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;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// make sure the file is an actual supported image
|
// make sure the file is an actual supported image
|
||||||
@@ -100,7 +106,7 @@ public class AddLibraryCommandHandler : ICommandHandler<AddLibraryCommand, Resul
|
|||||||
|
|
||||||
// create a domain library object
|
// create a domain library object
|
||||||
Result<Library> createLibraryResult = Library.Create(
|
Result<Library> createLibraryResult = Library.Create(
|
||||||
UserId.Create(_currentUserService.UserId!.Value),
|
UserId.Create(userId),
|
||||||
command.Title!,
|
command.Title!,
|
||||||
Enum.Parse<LibraryType>(command.LibraryType!),
|
Enum.Parse<LibraryType>(command.LibraryType!),
|
||||||
command.ContentLocations!,
|
command.ContentLocations!,
|
||||||
|
|||||||
+10
-2
@@ -8,9 +8,11 @@ using Lumina.Application.Common.DomainEvents;
|
|||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
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>
|
/// <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)
|
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
|
// get the running library scans of the current user from the repository
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> getRunningLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getRunningLibraryScansResult.IsFailure)
|
if (getRunningLibraryScansResult.IsFailure)
|
||||||
@@ -64,10 +72,10 @@ public class CancelLibrariesScanCommandHandler : ICommandHandler<CancelLibraries
|
|||||||
// filter the library scans to process
|
// filter the library scans to process
|
||||||
List<LibraryScanEntity> authorizedLibraryScans = [];
|
List<LibraryScanEntity> authorizedLibraryScans = [];
|
||||||
// admins can see all library scans
|
// 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);
|
authorizedLibraryScans.AddRange(getRunningLibraryScansResult.Value);
|
||||||
else // for regular users, only take the library scans that belong to them
|
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
|
// convert persistence library scans to domain entities
|
||||||
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
IEnumerable<Result<LibraryScan>> libraryScansDomainResult = authorizedLibraryScans.ToDomainEntities();
|
||||||
|
|||||||
+12
-3
@@ -7,10 +7,12 @@ using Lumina.Application.Common.DataAccess.UoW;
|
|||||||
using Lumina.Application.Common.DomainEvents;
|
using Lumina.Application.Common.DomainEvents;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -65,6 +67,12 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// get the library scan from the repository
|
||||||
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
Result<LibraryScanEntity?> getLibraryScansResult = await _unitOfWork.LibraryScanRepository.GetByIdAsync(command.ScanId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryScansResult.IsFailure)
|
if (getLibraryScansResult.IsFailure)
|
||||||
@@ -72,9 +80,10 @@ public class CancelLibraryScanCommandHandler : ICommandHandler<CancelLibraryScan
|
|||||||
if (getLibraryScansResult.Value is null)
|
if (getLibraryScansResult.Value is null)
|
||||||
return DomainErrors.LibraryScanning.LibraryScanNotFound;
|
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
|
// admins can cancel any library scan; for everyone else, only the ones of the libraries they own
|
||||||
if (getLibraryScansResult.Value.UserId != _currentUserService.UserId ||
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
userId, new LibraryOwnershipPolicyContext(getLibraryScansResult.Value.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// convert the repository scan to a domain object
|
// 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.DomainEvents;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -65,6 +67,12 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// get the library with the specified id from the repository
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
@@ -72,9 +80,10 @@ public class DeleteLibraryCommandHandler : ICommandHandler<DeleteLibraryCommand,
|
|||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
return DomainErrors.Library.LibraryNotFound;
|
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
|
// admins can delete any library; for everyone else, only the libraries they own
|
||||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// create a domain library object
|
// create a domain library object
|
||||||
|
|||||||
+11
-3
@@ -8,12 +8,14 @@ using Lumina.Application.Common.DomainEvents;
|
|||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
using Lumina.Domain.Common.Events;
|
using Lumina.Domain.Common.Events;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
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>
|
/// <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)
|
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
|
// get all media libraries that are enabled and unlocked from the persistence medium
|
||||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAndUnlockedAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibrariesResult.IsFailure)
|
if (getLibrariesResult.IsFailure)
|
||||||
@@ -68,8 +76,8 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
|||||||
IEnumerable<Result<Library>> domainEntitiesResult = getLibrariesResult.Value.ToDomainEntities();
|
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 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))
|
if (!await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||||
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == _currentUserService.UserId!.Value);
|
domainEntitiesResult = domainEntitiesResult.Where(libraryResult => libraryResult.Value.UserId.Value == userId);
|
||||||
|
|
||||||
List<MediaLibraryScanResponse> responses = [];
|
List<MediaLibraryScanResponse> responses = [];
|
||||||
List<IDomainEvent> domainEvents = [];
|
List<IDomainEvent> domainEvents = [];
|
||||||
@@ -95,7 +103,7 @@ public class ScanLibrariesCommandHandler : ICommandHandler<ScanLibrariesCommand,
|
|||||||
// start the media library scan
|
// start the media library scan
|
||||||
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||||
LibraryId.Create(domainLibraryResult.Value.Id.Value),
|
LibraryId.Create(domainLibraryResult.Value.Id.Value),
|
||||||
UserId.Create(_currentUserService.UserId!.Value),
|
UserId.Create(userId),
|
||||||
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
||||||
);
|
);
|
||||||
if (libraryScanResult.IsFailure)
|
if (libraryScanResult.IsFailure)
|
||||||
|
|||||||
+13
-4
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
|
|||||||
using Lumina.Application.Common.DomainEvents;
|
using Lumina.Application.Common.DomainEvents;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.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;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -71,6 +73,12 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// get the media library from the persistence medium
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(command.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
@@ -79,9 +87,10 @@ public class ScanLibraryCommandHandler : ICommandHandler<ScanLibraryCommand, Res
|
|||||||
if (getLibraryResult.Value is null)
|
if (getLibraryResult.Value is null)
|
||||||
return DomainErrors.Library.LibraryNotFound;
|
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
|
// admins can scan any library; for everyone else, only the libraries they own
|
||||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// check if the library is enabled and unlocked, before scanning it
|
// 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
|
// queue the media library scan
|
||||||
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
Result<LibraryScan> libraryScanResult = LibraryScan.Create(
|
||||||
LibraryId.Create(command.Id),
|
LibraryId.Create(command.Id),
|
||||||
UserId.Create(_currentUserService.UserId!.Value),
|
UserId.Create(userId),
|
||||||
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
[.. pastLibraryScansDomainResult.Select(pastLibraryScanDomainResult => pastLibraryScanDomainResult.Value)]
|
||||||
);
|
);
|
||||||
if (libraryScanResult.IsFailure)
|
if (libraryScanResult.IsFailure)
|
||||||
|
|||||||
+12
-4
@@ -7,6 +7,7 @@ using Lumina.Application.Common.DataAccess.UoW;
|
|||||||
using Lumina.Application.Common.DomainEvents;
|
using Lumina.Application.Common.DomainEvents;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
@@ -82,6 +83,12 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// make sure the file is an actual supported image
|
||||||
if (command.CoverImage is not null)
|
if (command.CoverImage is not null)
|
||||||
{
|
{
|
||||||
@@ -103,10 +110,11 @@ public class UpdateLibraryCommandHandler : ICommandHandler<UpdateLibraryCommand,
|
|||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
return DomainErrors.Library.LibraryNotFound;
|
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
|
// admins or users with the permission to manage media libraries can update any library; other users can only update the libraries they own
|
||||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
bool hasManagePermission = await _authorizationService.HasPermissionAsync(userId, AuthorizationPermission.CanCreateLibraries, cancellationToken).ConfigureAwait(false);
|
||||||
(!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false) &&
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.HasPermissionAsync(_currentUserService.UserId!.Value, AuthorizationPermission.CanCreateLibraries, cancellationToken)))
|
userId, new LibraryOwnershipPolicyContext(command.Id), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!hasManagePermission && !canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
// create a domain library object
|
// create a domain library object
|
||||||
|
|||||||
+10
-2
@@ -4,10 +4,12 @@ using Lumina.Application.Common.CQRS;
|
|||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -51,19 +53,25 @@ public class GetEnabledLibrariesQueryHandler : IQueryHandler<GetEnabledLibraries
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<LibraryResponse[]>> HandleAsync(GetEnabledLibrariesQuery query, CancellationToken cancellationToken)
|
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
|
// get the enabled libraries from the repository
|
||||||
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryEntity>> getEnabledLibrariesResult = await _unitOfWork.LibraryRepository.GetAllEnabledAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getEnabledLibrariesResult.IsFailure)
|
if (getEnabledLibrariesResult.IsFailure)
|
||||||
return getEnabledLibrariesResult.Errors;
|
return getEnabledLibrariesResult.Errors;
|
||||||
|
|
||||||
// admins can see all libraries
|
// 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());
|
return Result.From(getEnabledLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// for regular users, only take the libraries that belong to them
|
// for regular users, only take the libraries that belong to them
|
||||||
LibraryResponse[] userEnabledLibraries = [.. getEnabledLibrariesResult.Value
|
LibraryResponse[] userEnabledLibraries = [.. getEnabledLibrariesResult.Value
|
||||||
.Where(library => library.UserId == _currentUserService.UserId)
|
.Where(library => library.UserId == userId)
|
||||||
.Select(library => library.ToResponse())];
|
.Select(library => library.ToResponse())];
|
||||||
|
|
||||||
return Result.From(userEnabledLibraries);
|
return Result.From(userEnabledLibraries);
|
||||||
|
|||||||
+10
-2
@@ -4,10 +4,12 @@ using Lumina.Application.Common.CQRS;
|
|||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -51,19 +53,25 @@ public class GetLibrariesQueryHandler : IQueryHandler<GetLibrariesQuery, Result<
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<LibraryResponse[]>> HandleAsync(GetLibrariesQuery query, CancellationToken cancellationToken)
|
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
|
// get the libraries from the repository
|
||||||
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryEntity>> getLibrariesResult = await _unitOfWork.LibraryRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibrariesResult.IsFailure)
|
if (getLibrariesResult.IsFailure)
|
||||||
return getLibrariesResult.Errors;
|
return getLibrariesResult.Errors;
|
||||||
|
|
||||||
// admins can see all libraries
|
// 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());
|
return Result.From(getLibrariesResult.Value.Select(library => library.ToResponse()).ToArray());
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// for regular users, only take the libraries that belong to them
|
// for regular users, only take the libraries that belong to them
|
||||||
LibraryResponse[] userLibraries = [.. getLibrariesResult.Value
|
LibraryResponse[] userLibraries = [.. getLibrariesResult.Value
|
||||||
.Where(library => library.UserId == _currentUserService.UserId)
|
.Where(library => library.UserId == userId)
|
||||||
.Select(library => library.ToResponse())];
|
.Select(library => library.ToResponse())];
|
||||||
|
|
||||||
return Result.From(userLibraries);
|
return Result.From(userLibraries);
|
||||||
|
|||||||
+12
-3
@@ -6,10 +6,12 @@ using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
|||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -62,6 +64,12 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// get the library with the specified id from the repository
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Id, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
@@ -69,9 +77,10 @@ public class GetLibraryQueryHandler : IQueryHandler<GetLibraryQuery, Result<Libr
|
|||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
return DomainErrors.Library.LibraryNotFound;
|
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
|
// admins can see all libraries; for everyone else, only the libraries they own
|
||||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
userId, new LibraryOwnershipPolicyContext(query.Id), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
return getLibraryResult.Value.ToResponse();
|
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.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
||||||
using Lumina.Contracts.Responses.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.Services.Progress;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.UserManagementBoundedContext.UserAggregate.ValueObjects;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -69,6 +71,12 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// get the library with the specified id from the repository
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.LibraryId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getLibraryResult.IsFailure)
|
if (getLibraryResult.IsFailure)
|
||||||
@@ -76,13 +84,14 @@ public class GetLibraryScanProgressQueryHandler : IQueryHandler<GetLibraryScanPr
|
|||||||
else if (getLibraryResult.Value is null)
|
else if (getLibraryResult.Value is null)
|
||||||
return DomainErrors.Library.LibraryNotFound;
|
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
|
// admins can view the progress of any library scan; for everyone else, only the ones of the libraries they own
|
||||||
if (getLibraryResult.Value.UserId != _currentUserService.UserId ||
|
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
userId, new LibraryOwnershipPolicyContext(query.LibraryId), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (!canAccessLibrary)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
Result<MediaLibraryScanProgress> getProgressResult = _mediaLibrariesScanProgressTracker.GetScanProgress(
|
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)
|
if (getProgressResult.IsFailure)
|
||||||
return getProgressResult.Errors;
|
return getProgressResult.Errors;
|
||||||
|
|
||||||
|
|||||||
+12
-5
@@ -4,6 +4,7 @@ using Lumina.Application.Common.CQRS;
|
|||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.Management;
|
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;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Progress;
|
||||||
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.ValueObjects;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -58,19 +60,24 @@ public class GetRunningLibraryScansQueryHandler : IQueryHandler<GetRunningLibrar
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IEnumerable<MediaLibraryScanProgressResponse>>> HandleAsync(GetRunningLibraryScansQuery query, CancellationToken cancellationToken)
|
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
|
// get the ongoing library scans from the repository
|
||||||
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<LibraryScanEntity>> getRunningScansResult = await _unitOfWork.LibraryScanRepository.GetRunningScansAsync(cancellationToken).ConfigureAwait(false);
|
||||||
if (getRunningScansResult.IsFailure)
|
if (getRunningScansResult.IsFailure)
|
||||||
return getRunningScansResult.Errors;
|
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 = [];
|
LibraryScanEntity[] userRunningRepositoryLibraryScans = [];
|
||||||
// admins can see all libraries
|
if (await _authorizationService.IsInRoleAsync(userId, "Admin", cancellationToken).ConfigureAwait(false))
|
||||||
if (!await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false))
|
|
||||||
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
|
userRunningRepositoryLibraryScans = [.. getRunningScansResult.Value];
|
||||||
else // for regular users, only take the libraries that belong to them
|
else
|
||||||
userRunningRepositoryLibraryScans = getRunningScansResult.Value
|
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
|
// for each of the filtered library scans, get their progress
|
||||||
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
List<MediaLibraryScanProgressResponse> libraryScanProgresses = [];
|
||||||
|
|||||||
+13
-9
@@ -6,15 +6,16 @@ using Lumina.Application.Common.DataAccess.Repositories.Books;
|
|||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Lumina.Contracts.Responses.Common;
|
using Lumina.Contracts.Responses.Common;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Errors;
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
|
||||||
using Lumina.Application.Common.DTO.Pagination;
|
using Lumina.Application.Common.DTO.Pagination;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -59,14 +60,17 @@ public class GetBooksQueryHandler : IQueryHandler<GetBooksQuery, Result<Paginate
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
|
// an authenticated request must always carry a user identity
|
||||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
Guid? currentUserId = _currentUserService.UserId;
|
||||||
if (!isAdmin) // if its not an admin, then it must own the library
|
if (currentUserId is null)
|
||||||
{
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
|
Guid userId = currentUserId.Value;
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
|
|
||||||
return Errors.Authorization.NotAuthorized;
|
// 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
|
// get all books of the media library from the book repository
|
||||||
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
|
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.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||||
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Lumina.Contracts.Responses.Common;
|
using Lumina.Contracts.Responses.Common;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Errors;
|
using Lumina.Application.Common.Errors;
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
|
||||||
using Lumina.Application.Common.DTO.Pagination;
|
using Lumina.Application.Common.DTO.Pagination;
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
@@ -59,14 +60,17 @@ public class GetBooksLiteQueryHandler : IQueryHandler<GetBooksLiteQuery, Result<
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
return validationResult;
|
||||||
|
|
||||||
// check if the user has the rights to access the library they are requesting (admins can see all libraries)
|
// an authenticated request must always carry a user identity
|
||||||
bool isAdmin = await _authorizationService.IsInRoleAsync(_currentUserService.UserId!.Value, "Admin", cancellationToken).ConfigureAwait(false);
|
Guid? currentUserId = _currentUserService.UserId;
|
||||||
if (!isAdmin) // if its not an admin, then it must own the library
|
if (currentUserId is null)
|
||||||
{
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<LibraryEntity?> getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(query.Filter.LibraryId, cancellationToken).ConfigureAwait(false);
|
Guid userId = currentUserId.Value;
|
||||||
if (getLibraryResult.IsFailure || getLibraryResult.Value?.UserId != _currentUserService.UserId)
|
|
||||||
return Errors.Authorization.NotAuthorized;
|
// 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
|
// get all books of the media library from the book repository
|
||||||
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
|
Result<PaginatedResultDto<BookEntity>> getBooksResult = await _unitOfWork.BookRepository.GetPaginatedAsync(
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
using Lumina.Application.Common.Mapping.UsersManagement.Users;
|
||||||
using Lumina.Contracts.Responses.UsersManagement.Users;
|
using Lumina.Contracts.Responses.UsersManagement.Users;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -49,8 +50,14 @@ public class GetUsersQueryHandler : IQueryHandler<GetUsersQuery, Result<IEnumera
|
|||||||
/// </returns>
|
/// </returns>
|
||||||
public async Task<Result<IEnumerable<UserResponse>>> HandleAsync(GetUsersQuery query, CancellationToken cancellationToken)
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
Result<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
Result<IEnumerable<UserEntity>> getRolesResult = await _unitOfWork.UserRepository.GetAllAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
|||||||
+7
-1
@@ -60,8 +60,14 @@ public class UpdateUserRoleAndPermissionsCommandHandler : ICommandHandler<Update
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return ApplicationErrors.Authorization.NotAuthorized;
|
return ApplicationErrors.Authorization.NotAuthorized;
|
||||||
|
|
||||||
|
|||||||
+9
-2
@@ -8,6 +8,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -52,11 +53,17 @@ public class GetAuthorizationQueryHandler : IQueryHandler<GetAuthorizationQuery,
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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
|
// 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)
|
if (getCurrentUserPermissionResult.IsFailure)
|
||||||
return getCurrentUserPermissionResult.Errors;
|
return getCurrentUserPermissionResult.Errors;
|
||||||
// if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request
|
// if the current user is not an Admin, and the account for whom they request the permissions list is not theirs, deny the request
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
@@ -57,8 +58,14 @@ public class GetUserPermissionsQueryHandler : IQueryHandler<GetUserPermissionsQu
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
// get the user from the repository and return its permissions
|
// get the user from the repository and return its permissions
|
||||||
|
|||||||
+8
-1
@@ -10,6 +10,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
|
|||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Common.Mapping.Authorization;
|
using Lumina.Application.Common.Mapping.Authorization;
|
||||||
using Lumina.Contracts.Responses.Authorization;
|
using Lumina.Contracts.Responses.Authorization;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -56,8 +57,14 @@ public class GetUserRoleQueryHandler : IQueryHandler<GetUserRoleQuery, Result<Ro
|
|||||||
if (validationResult.Count > 0)
|
if (validationResult.Count > 0)
|
||||||
return validationResult;
|
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
|
// 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)
|
if (!isAdmin)
|
||||||
return Errors.Authorization.NotAuthorized;
|
return Errors.Authorization.NotAuthorized;
|
||||||
// get the user from the repository and return its roles
|
// get the user from the repository and return its roles
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
using Lumina.Application.Common.DomainEvents;
|
using Lumina.Application.Common.DomainEvents;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
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.Authorization.Policies.Over18;
|
||||||
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||||
using Lumina.Application.Common.Infrastructure.Plugins;
|
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.Authentication;
|
||||||
using Lumina.Infrastructure.Core.Authorization;
|
using Lumina.Infrastructure.Core.Authorization;
|
||||||
using Lumina.Infrastructure.Core.Authorization.Policies.Common.Factory;
|
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.Authorization.Policies.Over18;
|
||||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Cancellation;
|
||||||
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
using Lumina.Infrastructure.Core.MediaLibrary.Management.Scanning.Jobs.Common;
|
||||||
@@ -80,6 +82,7 @@ public static class InfrastructureLayerServices
|
|||||||
|
|
||||||
// authorization
|
// authorization
|
||||||
services.AddScoped<IOver18Policy, Over18Policy>();
|
services.AddScoped<IOver18Policy, Over18Policy>();
|
||||||
|
services.AddScoped<ILibraryOwnershipPolicy, LibraryOwnershipPolicy>();
|
||||||
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
|
services.AddScoped<IAuthorizationPolicyFactory, AuthorizationPolicyFactory>();
|
||||||
services.AddScoped<IAuthorizationService, AuthorizationService>();
|
services.AddScoped<IAuthorizationService, AuthorizationService>();
|
||||||
|
|
||||||
|
|||||||
@@ -75,17 +75,18 @@ public class AuthorizationService : IAuthorizationService
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <typeparam name="TAuthorizationPolicy">The type of authorization policy to evaluate.</typeparam>
|
/// <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="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>
|
/// <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>
|
/// <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
|
// resolve the authorization policy dynamically using the factory
|
||||||
IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy<TAuthorizationPolicy>();
|
IAuthorizationPolicy policy = _authorizationPolicyFactory.CreatePolicy<TAuthorizationPolicy>();
|
||||||
return await policy.EvaluateAsync(userId, cancellationToken).ConfigureAwait(false);
|
return await policy.EvaluateAsync(userId, context, cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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.Entities.UsersManagement;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
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.Authorization.Policies.Over18;
|
||||||
using Lumina.Application.Common.Infrastructure.Time;
|
using Lumina.Application.Common.Infrastructure.Time;
|
||||||
using System;
|
using System;
|
||||||
@@ -32,12 +33,13 @@ public class Over18Policy : IOver18Policy
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <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>
|
/// </summary>
|
||||||
/// <param name="userId">The unique identifier of the user for which to evaluate the policy.</param>
|
/// <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>
|
/// <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>
|
/// <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);
|
Result<UserEntity?> getUserResult = await _unitOfWork.UserRepository.GetByIdAsync(userId, cancellationToken).ConfigureAwait(false);
|
||||||
if (getUserResult.IsFailure || getUserResult.Value is null)
|
if (getUserResult.IsFailure || getUserResult.Value is null)
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ namespace Lumina.Infrastructure.Fixtures.Core.Authorization;
|
|||||||
[ExcludeFromCodeCoverage]
|
[ExcludeFromCodeCoverage]
|
||||||
public class TestAuthorizationPolicy : IAuthorizationPolicy
|
public class TestAuthorizationPolicy : IAuthorizationPolicy
|
||||||
{
|
{
|
||||||
public Task<bool> EvaluateAsync(Guid userId, CancellationToken cancellationToken)
|
public Task<bool> EvaluateAsync(Guid userId, PolicyContext? context, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
return Task.FromResult(true);
|
return Task.FromResult(true);
|
||||||
}
|
}
|
||||||
|
|||||||
+17
@@ -98,6 +98,23 @@ public class GetPermissionsQueryHandlerTests
|
|||||||
await _mockPermissionRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetAllPermissionsReturnsError_ShouldReturnError()
|
public async Task HandleAsync_WhenGetAllPermissionsReturnsError_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -76,6 +76,23 @@ public class AddRoleCommandHandlerTests
|
|||||||
await _mockRoleRepository.DidNotReceive().InsertAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError()
|
public async Task HandleAsync_WhenInsertRoleFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -73,6 +73,23 @@ public class DeleteRoleCommandHandlerTests
|
|||||||
await _mockRoleRepository.DidNotReceive().DeleteByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError()
|
public async Task HandleAsync_WhenRoleDoesNotExist_ShouldReturnRoleNotFoundError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -76,6 +76,23 @@ public class UpdateRoleCommandHandlerTests
|
|||||||
await _mockRoleRepository.DidNotReceive().UpdateAsync(Arg.Any<RoleEntity>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError()
|
public async Task HandleAsync_WhenUpdateRoleFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -75,6 +75,23 @@ public class GetRolePermissionsQueryHandlerTests
|
|||||||
await _mockRoleRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetRoleByIdFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -70,6 +70,23 @@ public class GetRolesQueryHandlerTests
|
|||||||
await _mockRoleRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetRolesFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+173
@@ -0,0 +1,173 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
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.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.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||||
|
using Lumina.Application.Fixtures.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||||
|
using Lumina.Contracts.Responses.MediaLibrary.Management;
|
||||||
|
using Lumina.Domain.Common.Errors;
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
|
using NSubstitute;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||||
|
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Application.UnitTests.Core.MediaLibrary.Management.Queries.GetLibrary;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains unit tests for the <see cref="GetLibraryQueryHandler"/> class.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class GetLibraryQueryHandlerTests
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _mockUnitOfWork;
|
||||||
|
private readonly ILibraryRepository _mockLibraryRepository;
|
||||||
|
private readonly IAuthorizationService _mockAuthorizationService;
|
||||||
|
private readonly ICurrentUserService _mockCurrentUserService;
|
||||||
|
private readonly IValidator<GetLibraryQuery> _mockValidator;
|
||||||
|
private readonly GetLibraryQueryHandler _sut;
|
||||||
|
private readonly Guid _userId;
|
||||||
|
private readonly GetLibraryQueryFixture _getLibraryQueryFixture = new();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="GetLibraryQueryHandlerTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public GetLibraryQueryHandlerTests()
|
||||||
|
{
|
||||||
|
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||||
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
|
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||||
|
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||||
|
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||||
|
_mockValidator = Substitute.For<IValidator<GetLibraryQuery>>();
|
||||||
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
|
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||||
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(true);
|
||||||
|
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
UserId = _userId,
|
||||||
|
Title = "Test Library",
|
||||||
|
LibraryType = LibraryType.EBook,
|
||||||
|
ContentLocations = [],
|
||||||
|
CreatedBy = _userId,
|
||||||
|
CreatedOnUtc = DateTime.UtcNow,
|
||||||
|
UpdatedBy = null
|
||||||
|
}));
|
||||||
|
_mockValidator.Validate(Arg.Any<GetLibraryQuery>()).Returns([]);
|
||||||
|
|
||||||
|
_sut = new GetLibraryQueryHandler(_mockAuthorizationService, _mockCurrentUserService, _mockUnitOfWork, _mockValidator);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnLibraryResponse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result.IsFailure);
|
||||||
|
Assert.NotNull(result.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(false);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
|
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Id), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotFoundError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result<LibraryEntity?>.Success(null));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenRepositoryFails_ShouldReturnRepositoryError()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Errors.Library.LibraryNotFound);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
GetLibraryQuery query = _getLibraryQueryFixture.Create();
|
||||||
|
_mockValidator.Validate(Arg.Any<GetLibraryQuery>()).Returns([Errors.Library.LibraryIdCannotBeEmpty]);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
Result<LibraryResponse> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result.IsFailure);
|
||||||
|
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||||
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
-69
@@ -1,11 +1,10 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
|
||||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
@@ -15,7 +14,6 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
|
|||||||
using Lumina.Domain.Common.Errors;
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -38,7 +36,6 @@ public class GetBooksQueryHandlerTests
|
|||||||
{
|
{
|
||||||
private readonly IUnitOfWork _mockUnitOfWork;
|
private readonly IUnitOfWork _mockUnitOfWork;
|
||||||
private readonly IBookRepository _mockBookRepository;
|
private readonly IBookRepository _mockBookRepository;
|
||||||
private readonly ILibraryRepository _mockLibraryRepository;
|
|
||||||
private readonly IAuthorizationService _mockAuthorizationService;
|
private readonly IAuthorizationService _mockAuthorizationService;
|
||||||
private readonly ICurrentUserService _mockCurrentUserService;
|
private readonly ICurrentUserService _mockCurrentUserService;
|
||||||
private readonly IValidator<GetBooksQuery> _mockValidator;
|
private readonly IValidator<GetBooksQuery> _mockValidator;
|
||||||
@@ -55,35 +52,22 @@ public class GetBooksQueryHandlerTests
|
|||||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
|
||||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
|
||||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||||
_mockValidator = Substitute.For<IValidator<GetBooksQuery>>();
|
_mockValidator = Substitute.For<IValidator<GetBooksQuery>>();
|
||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
// default stubs: the current user is not an admin, but owns the requested library
|
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
.Returns(true);
|
||||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
|
||||||
{
|
|
||||||
Id = Guid.NewGuid(),
|
|
||||||
UserId = _userId,
|
|
||||||
Title = "Test Library",
|
|
||||||
LibraryType = LibraryType.EBook,
|
|
||||||
ContentLocations = [],
|
|
||||||
CreatedBy = _userId,
|
|
||||||
CreatedOnUtc = DateTime.UtcNow,
|
|
||||||
UpdatedBy = null
|
|
||||||
}));
|
|
||||||
_mockValidator.Validate(Arg.Any<GetBooksQuery>()).Returns([]);
|
_mockValidator.Validate(Arg.Any<GetBooksQuery>()).Returns([]);
|
||||||
|
|
||||||
_sut = new GetBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
_sut = new GetBooksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
|
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||||
@@ -241,53 +225,12 @@ public class GetBooksQueryHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
|
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
PaginatedResultDto<BookEntity> paginatedBooks = new()
|
.Returns(false);
|
||||||
{
|
|
||||||
Data = [],
|
|
||||||
CurrentPage = 1,
|
|
||||||
PerPage = 10,
|
|
||||||
Count = 0,
|
|
||||||
NumberOfPages = 0
|
|
||||||
};
|
|
||||||
_mockBookRepository.GetPaginatedAsync(
|
|
||||||
Arg.Any<PaginationDataDto?>(),
|
|
||||||
Arg.Any<string?>(),
|
|
||||||
Arg.Any<SortOrder?>(),
|
|
||||||
Arg.Any<LibraryFilterDto>(),
|
|
||||||
Arg.Any<CancellationToken>())
|
|
||||||
.Returns(Result.From(paginatedBooks));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.False(result.IsFailure);
|
|
||||||
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
|
||||||
Guid otherUserId = Guid.NewGuid();
|
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
|
||||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
|
||||||
{
|
|
||||||
Id = Guid.NewGuid(),
|
|
||||||
UserId = otherUserId,
|
|
||||||
Title = "Someone else's library",
|
|
||||||
LibraryType = LibraryType.EBook,
|
|
||||||
ContentLocations = [],
|
|
||||||
CreatedBy = otherUserId,
|
|
||||||
CreatedOnUtc = DateTime.UtcNow,
|
|
||||||
UpdatedBy = null
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
@@ -295,16 +238,17 @@ public class GetBooksQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
|
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
|
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksQuery query = _getBooksQueryFixture.Create();
|
GetBooksQuery query = _getBooksQueryFixture.Create();
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||||
.Returns(Result<LibraryEntity?>.Success(null));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
Result<PaginatedResponse<BookResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
@@ -312,6 +256,7 @@ public class GetBooksQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,7 +273,7 @@ public class GetBooksQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||||
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-69
@@ -1,11 +1,10 @@
|
|||||||
#region ========================================================================= USING =====================================================================================
|
#region ========================================================================= USING =====================================================================================
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
|
||||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
using Lumina.Application.Common.DataAccess.Repositories.Books;
|
||||||
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Application.Common.Infrastructure.Validation;
|
using Lumina.Application.Common.Infrastructure.Validation;
|
||||||
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooksLite;
|
||||||
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
|
||||||
@@ -15,7 +14,6 @@ using Lumina.Contracts.Responses.MediaLibrary.WrittenContentLibrary.BookLibrary.
|
|||||||
using Lumina.Domain.Common.Errors;
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
using Lumina.Domain.SharedKernel.Common.Enums.Common;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
|
||||||
using NSubstitute;
|
using NSubstitute;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -38,7 +36,6 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
{
|
{
|
||||||
private readonly IUnitOfWork _mockUnitOfWork;
|
private readonly IUnitOfWork _mockUnitOfWork;
|
||||||
private readonly IBookRepository _mockBookRepository;
|
private readonly IBookRepository _mockBookRepository;
|
||||||
private readonly ILibraryRepository _mockLibraryRepository;
|
|
||||||
private readonly IAuthorizationService _mockAuthorizationService;
|
private readonly IAuthorizationService _mockAuthorizationService;
|
||||||
private readonly ICurrentUserService _mockCurrentUserService;
|
private readonly ICurrentUserService _mockCurrentUserService;
|
||||||
private readonly IValidator<GetBooksLiteQuery> _mockValidator;
|
private readonly IValidator<GetBooksLiteQuery> _mockValidator;
|
||||||
@@ -55,35 +52,22 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||||
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
|
||||||
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
|
||||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||||
_mockValidator = Substitute.For<IValidator<GetBooksLiteQuery>>();
|
_mockValidator = Substitute.For<IValidator<GetBooksLiteQuery>>();
|
||||||
_userId = Guid.NewGuid();
|
_userId = Guid.NewGuid();
|
||||||
|
|
||||||
// default stubs: the current user is not an admin, but owns the requested library
|
// default stubs: the current user is authenticated and the library ownership policy allows access
|
||||||
_mockCurrentUserService.UserId.Returns(_userId);
|
_mockCurrentUserService.UserId.Returns(_userId);
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(false);
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
.Returns(true);
|
||||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
|
||||||
{
|
|
||||||
Id = Guid.NewGuid(),
|
|
||||||
UserId = _userId,
|
|
||||||
Title = "Test Library",
|
|
||||||
LibraryType = LibraryType.EBook,
|
|
||||||
ContentLocations = [],
|
|
||||||
CreatedBy = _userId,
|
|
||||||
CreatedOnUtc = DateTime.UtcNow,
|
|
||||||
UpdatedBy = null
|
|
||||||
}));
|
|
||||||
_mockValidator.Validate(Arg.Any<GetBooksLiteQuery>()).Returns([]);
|
_mockValidator.Validate(Arg.Any<GetBooksLiteQuery>()).Returns([]);
|
||||||
|
|
||||||
_sut = new GetBooksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
_sut = new GetBooksLiteQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenRepositoryReturnsPaginatedBooks_ShouldReturnMappedPaginatedResponses()
|
public async Task HandleAsync_WhenPolicyAllowsAccess_ShouldReturnMappedPaginatedResponses()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
@@ -241,53 +225,12 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserIsAdmin_ShouldBypassLibraryOwnershipCheck()
|
public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
_mockAuthorizationService.IsInRoleAsync(_userId, "Admin", Arg.Any<CancellationToken>()).Returns(true);
|
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||||
PaginatedResultDto<BookEntity> paginatedBooks = new()
|
.Returns(false);
|
||||||
{
|
|
||||||
Data = [],
|
|
||||||
CurrentPage = 1,
|
|
||||||
PerPage = 10,
|
|
||||||
Count = 0,
|
|
||||||
NumberOfPages = 0
|
|
||||||
};
|
|
||||||
_mockBookRepository.GetPaginatedAsync(
|
|
||||||
Arg.Any<PaginationDataDto?>(),
|
|
||||||
Arg.Any<string?>(),
|
|
||||||
Arg.Any<SortOrder?>(),
|
|
||||||
Arg.Any<LibraryFilterDto>(),
|
|
||||||
Arg.Any<CancellationToken>())
|
|
||||||
.Returns(Result.From(paginatedBooks));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
Assert.False(result.IsFailure);
|
|
||||||
await _mockUnitOfWork.LibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task HandleAsync_WhenUserDoesNotOwnLibrary_ShouldReturnNotAuthorizedError()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
|
||||||
Guid otherUserId = Guid.NewGuid();
|
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
|
||||||
.Returns(Result.From((LibraryEntity?)new LibraryEntity
|
|
||||||
{
|
|
||||||
Id = Guid.NewGuid(),
|
|
||||||
UserId = otherUserId,
|
|
||||||
Title = "Someone else's library",
|
|
||||||
LibraryType = LibraryType.EBook,
|
|
||||||
ContentLocations = [],
|
|
||||||
CreatedBy = otherUserId,
|
|
||||||
CreatedOnUtc = DateTime.UtcNow,
|
|
||||||
UpdatedBy = null
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
@@ -295,16 +238,17 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||||
|
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == query.Filter.LibraryId), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnNotAuthorizedError()
|
public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
|
||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
GetBooksLiteQuery query = _getBooksLiteQueryFixture.Create();
|
||||||
_mockLibraryRepository.GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||||
.Returns(Result<LibraryEntity?>.Success(null));
|
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
Result<PaginatedResponse<BookLiteResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||||
@@ -312,6 +256,7 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||||
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,7 +273,7 @@ public class GetBooksLiteQueryHandlerTests
|
|||||||
// Assert
|
// Assert
|
||||||
Assert.True(result.IsFailure);
|
Assert.True(result.IsFailure);
|
||||||
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
|
||||||
await _mockAuthorizationService.DidNotReceive().IsInRoleAsync(Arg.Any<Guid>(), Arg.Any<string>(), Arg.Any<CancellationToken>());
|
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<ILibraryOwnershipPolicy>(Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||||
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
await _mockBookRepository.DidNotReceive().GetPaginatedAsync(Arg.Any<PaginationDataDto?>(), Arg.Any<string?>(), Arg.Any<SortOrder?>(), Arg.Any<LibraryFilterDto>(), Arg.Any<CancellationToken>());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+17
@@ -73,6 +73,23 @@ public class GetUsersQueryHandlerTests
|
|||||||
await _mockUserRepository.DidNotReceive().GetAllAsync(Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetUsersFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -88,6 +88,23 @@ public class UpdateUserRoleAndPermissionsCommandHandlerTests
|
|||||||
await _mockUserRepository.DidNotReceive().UpdateAsync(Arg.Any<UserEntity>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError()
|
public async Task HandleAsync_WhenUserDoesNotExist_ShouldReturnUserDoesNotExistError()
|
||||||
{
|
{
|
||||||
|
|||||||
+16
@@ -112,6 +112,22 @@ public class GetAuthorizationQueryHandlerTests
|
|||||||
Assert.Equal(Errors.Authorization.NotAuthorized, result.FirstError);
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetCurrentUserAuthorizationFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetCurrentUserAuthorizationFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -77,6 +77,23 @@ public class GetUserPermissionsQueryHandlerTests
|
|||||||
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+17
@@ -76,6 +76,23 @@ public class GetUserRoleQueryHandlerTests
|
|||||||
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
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]
|
[Fact]
|
||||||
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
|
public async Task HandleAsync_WhenGetUserByIdFails_ShouldReturnError()
|
||||||
{
|
{
|
||||||
|
|||||||
+22
-15
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
|||||||
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
using Lumina.Application.Common.DataAccess.Repositories.Users;
|
||||||
using Lumina.Application.Common.DataAccess.UoW;
|
using Lumina.Application.Common.DataAccess.UoW;
|
||||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base;
|
||||||
|
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||||
using Lumina.Domain.Common.Errors;
|
using Lumina.Domain.Common.Errors;
|
||||||
using Lumina.Domain.Common.Primitives;
|
using Lumina.Domain.Common.Primitives;
|
||||||
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||||
@@ -280,19 +281,20 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||||
.Returns(true);
|
.Returns(true);
|
||||||
|
|
||||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||||
.Returns(mockPolicy);
|
.Returns(mockPolicy);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result);
|
Assert.True(result);
|
||||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,19 +303,20 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||||
.Returns(false);
|
.Returns(false);
|
||||||
|
|
||||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||||
.Returns(mockPolicy);
|
.Returns(mockPolicy);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
bool result = await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.False(result);
|
Assert.False(result);
|
||||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,20 +325,21 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||||
.Throws(new InvalidOperationException("Policy evaluation failed"));
|
.Throws(new InvalidOperationException("Policy evaluation failed"));
|
||||||
|
|
||||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||||
.Returns(mockPolicy);
|
.Returns(mockPolicy);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
||||||
Assert.Equal("Policy evaluation failed", exception.Message);
|
Assert.Equal("Policy evaluation failed", exception.Message);
|
||||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,11 +348,12 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
_mockAuthorizationPolicyFactory.CreatePolicy<IAuthorizationPolicy>()
|
||||||
.Throws(new InvalidOperationException("Policy creation failed"));
|
.Throws(new InvalidOperationException("Policy creation failed"));
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, CancellationToken.None);
|
Func<Task> act = async () => await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(act);
|
||||||
@@ -361,6 +366,7 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
IAuthorizationPolicy mockPolicy = Substitute.For<IAuthorizationPolicy>();
|
||||||
CancellationToken cancellationToken = new(true);
|
CancellationToken cancellationToken = new(true);
|
||||||
|
|
||||||
@@ -368,10 +374,10 @@ public class AuthorizationServiceTests
|
|||||||
.Returns(mockPolicy);
|
.Returns(mockPolicy);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, cancellationToken);
|
await _sut.EvaluatePolicyAsync<IAuthorizationPolicy>(userId, context, cancellationToken);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
await mockPolicy.Received(1).EvaluateAsync(userId, cancellationToken);
|
await mockPolicy.Received(1).EvaluateAsync(userId, context, cancellationToken);
|
||||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<IAuthorizationPolicy>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -380,19 +386,20 @@ public class AuthorizationServiceTests
|
|||||||
{
|
{
|
||||||
// Arrange
|
// Arrange
|
||||||
Guid userId = Guid.NewGuid();
|
Guid userId = Guid.NewGuid();
|
||||||
|
PolicyContext context = new LibraryOwnershipPolicyContext(Guid.NewGuid());
|
||||||
IAuthorizationPolicy mockPolicy = Substitute.For<ITestAuthorizationPolicy>();
|
IAuthorizationPolicy mockPolicy = Substitute.For<ITestAuthorizationPolicy>();
|
||||||
mockPolicy.EvaluateAsync(userId, Arg.Any<CancellationToken>())
|
mockPolicy.EvaluateAsync(userId, context, Arg.Any<CancellationToken>())
|
||||||
.Returns(true);
|
.Returns(true);
|
||||||
|
|
||||||
_mockAuthorizationPolicyFactory.CreatePolicy<ITestAuthorizationPolicy>()
|
_mockAuthorizationPolicyFactory.CreatePolicy<ITestAuthorizationPolicy>()
|
||||||
.Returns(mockPolicy);
|
.Returns(mockPolicy);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, CancellationToken.None);
|
bool result = await _sut.EvaluatePolicyAsync<ITestAuthorizationPolicy>(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
Assert.True(result);
|
Assert.True(result);
|
||||||
await mockPolicy.Received(1).EvaluateAsync(userId, Arg.Any<CancellationToken>());
|
await mockPolicy.Received(1).EvaluateAsync(userId, context, Arg.Any<CancellationToken>());
|
||||||
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<ITestAuthorizationPolicy>();
|
_mockAuthorizationPolicyFactory.Received(1).CreatePolicy<ITestAuthorizationPolicy>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+216
@@ -0,0 +1,216 @@
|
|||||||
|
#region ========================================================================= USING =====================================================================================
|
||||||
|
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||||
|
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
|
||||||
|
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||||
|
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.LibraryOwnership;
|
||||||
|
using Lumina.Domain.Common.Primitives;
|
||||||
|
using Lumina.Domain.SharedKernel.Common.Enums.Authorization;
|
||||||
|
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||||
|
using Lumina.Infrastructure.Core.Authorization.Policies.LibraryOwnership;
|
||||||
|
using Lumina.Infrastructure.Fixtures.Core.Authorization;
|
||||||
|
using NSubstitute;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace Lumina.Infrastructure.UnitTests.Core.Authorization.Policies.LibraryOwnership;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Contains unit tests for the <see cref="LibraryOwnershipPolicy"/> class.
|
||||||
|
/// </summary>
|
||||||
|
[ExcludeFromCodeCoverage]
|
||||||
|
public class LibraryOwnershipPolicyTests
|
||||||
|
{
|
||||||
|
private readonly IUnitOfWork _mockUnitOfWork;
|
||||||
|
private readonly IUserRepository _mockUserRepository;
|
||||||
|
private readonly ILibraryRepository _mockLibraryRepository;
|
||||||
|
private readonly LibraryOwnershipPolicy _sut;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Initializes a new instance of the <see cref="LibraryOwnershipPolicyTests"/> class.
|
||||||
|
/// </summary>
|
||||||
|
public LibraryOwnershipPolicyTests()
|
||||||
|
{
|
||||||
|
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||||
|
_mockUserRepository = Substitute.For<IUserRepository>();
|
||||||
|
_mockLibraryRepository = Substitute.For<ILibraryRepository>();
|
||||||
|
_mockUnitOfWork.UserRepository.Returns(_mockUserRepository);
|
||||||
|
_mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
|
||||||
|
|
||||||
|
_sut = new LibraryOwnershipPolicy(_mockUnitOfWork);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenContextIsNotLibraryOwnershipContext_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, null, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
await _mockUserRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenUserDoesNotExist_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(null));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenGetUserFails_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Error.Failure("Database.Error", "Failed to retrieve user"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenUserIsAdmin_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
UserEntity adminUser = AuthorizationServiceFixture.CreateUserWithPermissions(
|
||||||
|
rolePermissions: new Dictionary<string, IEnumerable<AuthorizationPermission>>
|
||||||
|
{
|
||||||
|
{ "Admin", [] }
|
||||||
|
});
|
||||||
|
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||||
|
_mockUserRepository.GetByIdAsync(adminUser.Id, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(adminUser));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(adminUser.Id, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result);
|
||||||
|
await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenLibraryDoesNotExist_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||||
|
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(regularUser));
|
||||||
|
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result<LibraryEntity?>.Success(null));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenGetLibraryFails_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||||
|
LibraryOwnershipPolicyContext context = new(Guid.NewGuid());
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(regularUser));
|
||||||
|
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Error.Failure("Database.Error", "Failed to retrieve library"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenUserOwnsLibrary_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||||
|
LibraryEntity library = CreateLibrary(userId);
|
||||||
|
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(regularUser));
|
||||||
|
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<LibraryEntity?>(library));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.True(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task EvaluateAsync_WhenUserDoesNotOwnLibrary_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
Guid userId = Guid.NewGuid();
|
||||||
|
UserEntity regularUser = AuthorizationServiceFixture.CreateUserWithPermissions();
|
||||||
|
LibraryEntity library = CreateLibrary(Guid.NewGuid());
|
||||||
|
LibraryOwnershipPolicyContext context = new(library.Id);
|
||||||
|
_mockUserRepository.GetByIdAsync(userId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<UserEntity?>(regularUser));
|
||||||
|
_mockLibraryRepository.GetByIdAsync(context.LibraryId, Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Result.From<LibraryEntity?>(library));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
bool result = await _sut.EvaluateAsync(userId, context, CancellationToken.None);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Assert.False(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates a library entity owned by <paramref name="ownerId"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="ownerId">The Id of the user owning the library.</param>
|
||||||
|
/// <returns>The created library entity.</returns>
|
||||||
|
private static LibraryEntity CreateLibrary(Guid ownerId)
|
||||||
|
{
|
||||||
|
return new LibraryEntity
|
||||||
|
{
|
||||||
|
Id = Guid.NewGuid(),
|
||||||
|
UserId = ownerId,
|
||||||
|
Title = "Test Library",
|
||||||
|
LibraryType = LibraryType.Book,
|
||||||
|
ContentLocations = [],
|
||||||
|
CreatedBy = ownerId,
|
||||||
|
CreatedOnUtc = DateTime.UtcNow,
|
||||||
|
UpdatedBy = null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user