classlib/ExpenseTracker.Application/Accounts/Queries/Get/GetAccountQueryAuthorizer.cs
2024-08-07 21:12:02 +03:00

38 lines
1.4 KiB
C#

using MediatR.Behaviors.Authorization;
using ExpenseTracker.Application.Common.Authorization;
using ExpenseTracker.Application.Common.Interfaces.Repositories;
using ExpenseTracker.Application.Common.Interfaces.Services;
using ExpenseTracker.Application.Common.Models;
namespace ExpenseTracker.Application.Accounts.Queries.Get;
public class GetAccountQueryAuthorizer : AbstractRequestAuthorizer<GetAccountQuery>
{
private readonly ISessionUserService _sessionUserService;
private readonly IAccountRepository _repository;
public GetAccountQueryAuthorizer(ISessionUserService currentUserService, IAccountRepository repository)
{
_sessionUserService = currentUserService;
_repository = repository;
}
public override void BuildPolicy(GetAccountQuery request)
{
UseRequirement(new MustBeAuthenticatedRequirement
{
IsAuthenticated = _sessionUserService.IsAuthenticated
});
var requiredUserId = _repository.Queryable.FirstOrDefault(e => e.Id == request.Id)?.UserId;
UseRequirement(new MustBeInRolesWhenInteractingWithUnOwnedEntityRequirement
{
UserId = _sessionUserService.Id,
UserRoles = _sessionUserService.Roles,
RequiredUserId = requiredUserId,
RequiredRoles = new[] { IdentityRoles.Administrator.ToString() }
});
}
}