Sube carpetas API, API.Tests, Application y Domain del Backend
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace API.Utils.Helpers;
|
||||
|
||||
public static class AuthHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Extracts the caller's role and id from the Role and NameIdentifier claims, letting Guid.Parse throw a FormatException on an unauthenticated or malformed principal rather than returning a default value.
|
||||
/// </summary>
|
||||
public static (string role, Guid id) GetCallerClaims(this ClaimsPrincipal principal)
|
||||
{
|
||||
string role = principal.FindFirstValue(ClaimTypes.Role) ?? string.Empty;
|
||||
string sub = principal.FindFirstValue(ClaimTypes.NameIdentifier) ?? string.Empty;
|
||||
return (role, Guid.Parse(sub));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using Application.Interfaces.Services;
|
||||
|
||||
using Domain.Constants;
|
||||
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace API.Utils.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the current caller's identity from the HTTP context for the audit trail, falling back to AuditConstants.SystemUser when there is no authenticated request.
|
||||
/// </summary>
|
||||
public sealed class HttpCurrentUserAccessor(IHttpContextAccessor httpContextAccessor) : ICurrentUserAccessor
|
||||
{
|
||||
public string Actor
|
||||
{
|
||||
get
|
||||
{
|
||||
ClaimsPrincipal? user = httpContextAccessor.HttpContext?.User;
|
||||
|
||||
string? identifier = user?.FindFirstValue(ClaimTypes.Email)
|
||||
?? user?.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
return string.IsNullOrWhiteSpace(identifier) ? AuditConstants.SystemUser : identifier;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user