Files
adas-core/adas-core.Authentication/Attributes/AuthorizeUserByService.cs
T
2026-06-26 10:29:23 +02:00

33 lines
1.5 KiB
C#

using adas_core.Authentication.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace adas_core.Authentication.Attributes;
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");
}
}