#region ========================================================================= USING ===================================================================================== using Lumina.Presentation.Web.Common.Enums.Authorization; using Lumina.Presentation.Web.Common.Http; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; 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; private readonly IHttpContextAccessor _httpContextAccessor; /// /// Initializes a new instance of the class. /// /// Injected service for authorization checks against the remote API. /// Injected accessor for the current HTTP context. public PermissionAuthorizationHandler(IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; } /// /// 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; } } // The authorization service marks a page navigation when the API could not answer. The page itself is still rendered, with // no permission granted, and it reports the failure to the user; the API remains the enforcement point for every data call. // Endpoint routing passes the Endpoint, not the HttpContext, as the authorization resource, so the current request is read // from the accessor instead. Only an authenticated user is allowed through, because the outage is not a reason to expose a // page to an anonymous visitor. HttpContext? httpContext = _httpContextAccessor.HttpContext; if (httpContext?.User.Identity?.IsAuthenticated == true && httpContext.Items[HttpContextItemKeys.SERVER_UNREACHABLE] is true) authorizationHandlerContext.Succeed(permissionRequirement); } }