40 lines
2.0 KiB
C#
40 lines
2.0 KiB
C#
using adas_core.Authentication.Interfaces;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
|
|
namespace adas_core.Authentication.Attributes;
|
|
|
|
/// <summary>
|
|
/// Represents an authorization attribute that enforces permission-based access control using the injected <see cref="IUserService"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Inherits from <see cref="Attribute"/> and implements <see cref="IAuthorizationFilter"/>, allowing it to be applied to controllers or actions and integrated into the request filtering pipeline.
|
|
/// </remarks>
|
|
/// <!-- aidoc:v1 sig=28ee847 -->
|
|
public class AuthorizePermissionsAttribute(
|
|
IUserService userService)
|
|
: Attribute, IAuthorizationFilter
|
|
{
|
|
/// <summary>
|
|
/// Handles authorization by validating the presence of the <c>Displayid</c> request header and ensuring the authenticated user exists in the user service. If the header is missing or the user cannot be found, the request is short-circuited with a <see cref="NotFoundObjectResult"/>.
|
|
/// </summary>
|
|
/// <param name="context">The <see cref="AuthorizationFilterContext"/> for the current request, providing access to the HTTP context, user identity, and the ability to set the action result.</param>
|
|
public void OnAuthorization(AuthorizationFilterContext context)
|
|
{
|
|
var user = context.HttpContext.User;
|
|
|
|
var userName = user.Identity?.Name ?? string.Empty;
|
|
var displayIdHeader = context.HttpContext.Request.Headers["Displayid"];
|
|
|
|
if (string.IsNullOrEmpty(displayIdHeader.ToString()))
|
|
{
|
|
context.Result = new NotFoundObjectResult("displayIdHeader not found reference id doesn't exist on header");
|
|
return;
|
|
}
|
|
|
|
var userDao = userService.GetUserByUserName(userName).Result;
|
|
|
|
if (userDao == null)
|
|
context.Result = new NotFoundObjectResult("User not found on AuthorizePermissionsAttribute");
|
|
}
|
|
} |