Files
ROLAC/API/ROLAC.API/Services/Logging/CurrentUserAccessor.cs
Chris Chen 62592c29ae
ci-cd-vm / ci-cd (push) Successful in 4m2s
Add audit logs.
2026-06-23 12:13:47 -07:00

31 lines
1.3 KiB
C#

using System.Security.Claims;
namespace ROLAC.API.Services.Logging;
/// <summary>
/// One place to resolve the acting user + request context from the current HttpContext, so the
/// "sub" claim quirk (JWT uses NameClaimType="sub" + MapInboundClaims=false, leaving
/// ClaimTypes.NameIdentifier null) lives in a single spot. Used by the audit interceptor,
/// IAuditLogger, the exception middleware, and the timestamp-stamping interceptor.
/// </summary>
public sealed class CurrentUserAccessor
{
private readonly IHttpContextAccessor _http;
public CurrentUserAccessor(IHttpContextAccessor http) => _http = http;
/// <summary>The acting user id, or null when unauthenticated / off the request thread.</summary>
public string? UserId =>
_http.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier)
?? _http.HttpContext?.User.FindFirstValue("sub");
/// <summary>The acting user id, or "system" for background/unauthenticated work.</summary>
public string UserIdOrSystem => UserId ?? "system";
public string? Email => _http.HttpContext?.User.FindFirstValue("email");
public string? IpAddress => _http.HttpContext?.Connection.RemoteIpAddress?.ToString();
public string? CorrelationId => _http.HttpContext?.TraceIdentifier;
}