using MediatR.Behaviors.Authorization; namespace ExpenseTracker.Application.Common.Authorization; public class MustBeInRolesWhenInteractingWithUnOwnedEntityRequirement : IAuthorizationRequirement { public required string UserId { get; init; } = default!; public required ICollection UserRoles { get; init; } = default!; public required string RequiredUserId { get; init; } = default!; public required ICollection RequiredRoles { get; init; } = default!; class MustBeInAdministratorRoleRequirementHandler : IAuthorizationHandler { public async Task 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)}'."); } } }