29 lines
1.3 KiB
C#
29 lines
1.3 KiB
C#
using MediatR.Behaviors.Authorization;
|
|
|
|
namespace ExpenseTracker.Application.Common.Authorization;
|
|
|
|
public class MustBeInRolesWhenInteractingWithUnOwnedEntityRequirement : IAuthorizationRequirement
|
|
{
|
|
public required string UserId { get; init; } = default!;
|
|
public required ICollection<string> UserRoles { get; init; } = default!;
|
|
|
|
public required string RequiredUserId { get; init; } = default!;
|
|
public required ICollection<string> RequiredRoles { get; init; } = default!;
|
|
|
|
class MustBeInAdministratorRoleRequirementHandler : IAuthorizationHandler<MustBeInRolesWhenInteractingWithUnOwnedEntityRequirement>
|
|
{
|
|
public async Task<AuthorizationResult> Handle(MustBeInRolesWhenInteractingWithUnOwnedEntityRequirement request, CancellationToken cancellationToken)
|
|
{
|
|
var isUserOwner = request.UserId == request.RequiredUserId;
|
|
var isUserInRequiredRoles = request.UserRoles.Any(ur => request.RequiredRoles.Contains(ur));
|
|
|
|
if (isUserOwner || isUserInRequiredRoles)
|
|
{
|
|
return AuthorizationResult.Succeed();
|
|
}
|
|
|
|
return AuthorizationResult.Fail($"You must be the entity owner or be in one of the following roles: '{String.Join("', ", request.RequiredRoles)}'.");
|
|
}
|
|
}
|
|
}
|