classlib/ExpenseTracker.Application/Common/Authorization/MustBeInRolesRequirement.cs
2024-08-07 21:12:02 +03:00

25 lines
957 B
C#

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