From 9e68e1290336e689cb6af73ac0696c059b1e0332 Mon Sep 17 00:00:00 2001 From: XShine555 Date: Fri, 29 May 2026 22:29:54 +0200 Subject: [PATCH] Current User --- WebApi/Authentication/CurrentUser.cs | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 WebApi/Authentication/CurrentUser.cs diff --git a/WebApi/Authentication/CurrentUser.cs b/WebApi/Authentication/CurrentUser.cs new file mode 100644 index 0000000..f5b8df2 --- /dev/null +++ b/WebApi/Authentication/CurrentUser.cs @@ -0,0 +1,43 @@ +using System.Reflection; +using System.Security.Claims; + +namespace WebApi.Authentication; + +public sealed class CurrentUser : IBindableFromHttpContext +{ + private CurrentUser(ClaimsPrincipal principal) + { + Principal = principal; + var isAuthenticated = principal.Identity?.IsAuthenticated; + IsAuthenticated = isAuthenticated.HasValue && isAuthenticated.Value; + + var rawId = principal.FindFirstValue(ClaimTypes.NameIdentifier); + Id = Guid.TryParse(rawId, out var id)? id : Guid.Empty; + + Username = principal.FindFirstValue(ClaimTypes.Name); + FirstName = principal.FindFirstValue(ClaimTypes.GivenName); + LastName = principal.FindFirstValue(ClaimTypes.Surname); + } + + public ClaimsPrincipal Principal { get; } + + public bool IsAuthenticated { get; } + + public Guid? Id { get; } + + public string? Username { get; } + + public string? FirstName { get; } + + public string? LastName { get; } + + public Guid RequiredId => Id + ?? throw new InvalidOperationException("The current request does not contain an authenticated user id."); + + public bool HasClaim(string type) => Principal.HasClaim(c => c.Type == type); + + public string? FindClaim(string type) => Principal.FindFirstValue(type); + + public static ValueTask BindAsync(HttpContext context, ParameterInfo parameter) => + ValueTask.FromResult(new CurrentUser(context.User)); +} \ No newline at end of file