#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Enums.Authorization;
using Microsoft.AspNetCore.Authorization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.Authorization;
///
/// Handles the by checking the currently logged in user's permissions against the remote API.
///
public class PermissionAuthorizationHandler : AuthorizationHandler
{
private readonly IAuthorizationService _authorizationService;
///
/// Initializes a new instance of the class.
///
/// Injected service for authorization checks against the remote API.
public PermissionAuthorizationHandler(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
///
/// Succeeds the requirement when the currently logged in user is an administrator, or holds any of the required permissions.
///
/// The authorization context.
/// The permission requirement to evaluate.
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authorizationHandlerContext, PermissionRequirement permissionRequirement)
{
// The API lets administrators do what the permission allows even when they do not hold it, so the Web does not deny them what the API grants.
if (await _authorizationService.IsInRoleAsync("Admin", CancellationToken.None).ConfigureAwait(false))
{
authorizationHandlerContext.Succeed(permissionRequirement);
return;
}
foreach (AuthorizationPermission permission in permissionRequirement.Permissions)
{
if (await _authorizationService.HasPermissionAsync(permission, CancellationToken.None).ConfigureAwait(false))
{
authorizationHandlerContext.Succeed(permissionRequirement);
return;
}
}
}
}