| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Chronicis.Api.Services; |
| | | 3 | | using Chronicis.Shared.Models; |
| | | 4 | | |
| | | 5 | | namespace Chronicis.Api.Infrastructure; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Implementation of ICurrentUserService that resolves the user from HTTP context claims. |
| | | 9 | | /// This service is scoped per-request and caches the user lookup for the request lifetime. |
| | | 10 | | /// </summary> |
| | | 11 | | public class CurrentUserService : ICurrentUserService |
| | | 12 | | { |
| | | 13 | | private readonly IHttpContextAccessor _httpContextAccessor; |
| | | 14 | | private readonly IUserService _userService; |
| | | 15 | | private User? _cachedUser; |
| | | 16 | | private bool _userLookedUp; |
| | | 17 | | |
| | 0 | 18 | | public CurrentUserService( |
| | 0 | 19 | | IHttpContextAccessor httpContextAccessor, |
| | 0 | 20 | | IUserService userService) |
| | | 21 | | { |
| | 0 | 22 | | _httpContextAccessor = httpContextAccessor; |
| | 0 | 23 | | _userService = userService; |
| | 0 | 24 | | } |
| | | 25 | | |
| | | 26 | | public bool IsAuthenticated => |
| | 0 | 27 | | _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false; |
| | | 28 | | |
| | | 29 | | public string? GetAuth0UserId() |
| | | 30 | | { |
| | 0 | 31 | | var user = _httpContextAccessor.HttpContext?.User; |
| | 0 | 32 | | if (user == null || !IsAuthenticated) |
| | 0 | 33 | | return null; |
| | | 34 | | |
| | | 35 | | // Auth0 puts the user ID in the 'sub' claim (NameIdentifier) |
| | 0 | 36 | | return user.FindFirst(ClaimTypes.NameIdentifier)?.Value |
| | 0 | 37 | | ?? user.FindFirst("sub")?.Value; |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | public async Task<User?> GetCurrentUserAsync() |
| | | 41 | | { |
| | | 42 | | // Return cached user if already looked up this request |
| | 0 | 43 | | if (_userLookedUp) |
| | 0 | 44 | | return _cachedUser; |
| | | 45 | | |
| | 0 | 46 | | _userLookedUp = true; |
| | | 47 | | |
| | 0 | 48 | | var auth0UserId = GetAuth0UserId(); |
| | 0 | 49 | | if (string.IsNullOrEmpty(auth0UserId)) |
| | 0 | 50 | | return null; |
| | | 51 | | |
| | | 52 | | // Extract additional claims for user creation/update |
| | 0 | 53 | | var claimsPrincipal = _httpContextAccessor.HttpContext?.User; |
| | | 54 | | |
| | | 55 | | const string customNamespace = "https://chronicis.app"; |
| | | 56 | | |
| | 0 | 57 | | var email = claimsPrincipal?.FindFirst($"{customNamespace}/email")?.Value |
| | 0 | 58 | | ?? claimsPrincipal?.FindFirst(ClaimTypes.Email)?.Value |
| | 0 | 59 | | ?? claimsPrincipal?.FindFirst("email")?.Value |
| | 0 | 60 | | ?? ""; |
| | | 61 | | |
| | 0 | 62 | | var displayName = claimsPrincipal?.FindFirst($"{customNamespace}/name")?.Value |
| | 0 | 63 | | ?? claimsPrincipal?.FindFirst(ClaimTypes.Name)?.Value |
| | 0 | 64 | | ?? claimsPrincipal?.FindFirst("name")?.Value |
| | 0 | 65 | | ?? claimsPrincipal?.FindFirst("nickname")?.Value |
| | 0 | 66 | | ?? claimsPrincipal?.FindFirst("preferred_username")?.Value |
| | 0 | 67 | | ?? claimsPrincipal?.FindFirst("given_name")?.Value |
| | 0 | 68 | | ?? ExtractNameFromEmail(email) |
| | 0 | 69 | | ?? "Unknown User"; |
| | | 70 | | |
| | 0 | 71 | | var avatarUrl = claimsPrincipal?.FindFirst($"{customNamespace}/picture")?.Value |
| | 0 | 72 | | ?? claimsPrincipal?.FindFirst("picture")?.Value; |
| | | 73 | | |
| | | 74 | | // Get or create the user in the database |
| | 0 | 75 | | _cachedUser = await _userService.GetOrCreateUserAsync( |
| | 0 | 76 | | auth0UserId, |
| | 0 | 77 | | email, |
| | 0 | 78 | | displayName, |
| | 0 | 79 | | avatarUrl); |
| | | 80 | | |
| | 0 | 81 | | return _cachedUser; |
| | 0 | 82 | | } |
| | | 83 | | |
| | | 84 | | public async Task<User> GetRequiredUserAsync() |
| | | 85 | | { |
| | 0 | 86 | | var user = await GetCurrentUserAsync(); |
| | 0 | 87 | | return user ?? throw new InvalidOperationException( |
| | 0 | 88 | | "User not found. Ensure this endpoint requires authentication."); |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | /// <summary> |
| | | 92 | | /// Extracts a display name from an email address as a fallback. |
| | | 93 | | /// e.g., "john.doe@example.com" becomes "John Doe" |
| | | 94 | | /// </summary> |
| | | 95 | | private static string? ExtractNameFromEmail(string? email) |
| | | 96 | | { |
| | 0 | 97 | | if (string.IsNullOrEmpty(email) || !email.Contains('@')) |
| | 0 | 98 | | return null; |
| | | 99 | | |
| | 0 | 100 | | var localPart = email.Split('@')[0]; |
| | | 101 | | |
| | | 102 | | // Replace common separators with spaces |
| | 0 | 103 | | var name = localPart |
| | 0 | 104 | | .Replace('.', ' ') |
| | 0 | 105 | | .Replace('_', ' ') |
| | 0 | 106 | | .Replace('-', ' '); |
| | | 107 | | |
| | | 108 | | // Title case each word |
| | 0 | 109 | | var words = name.Split(' ', StringSplitOptions.RemoveEmptyEntries); |
| | 0 | 110 | | var titleCased = words.Select(w => |
| | 0 | 111 | | char.ToUpper(w[0]) + (w.Length > 1 ? w.Substring(1).ToLower() : "")); |
| | | 112 | | |
| | 0 | 113 | | var result = string.Join(" ", titleCased); |
| | | 114 | | |
| | | 115 | | // Don't return if it looks like gibberish (all numbers, too short, etc.) |
| | 0 | 116 | | if (result.Length < 2 || result.All(c => char.IsDigit(c))) |
| | 0 | 117 | | return null; |
| | | 118 | | |
| | 0 | 119 | | return result; |
| | | 120 | | } |
| | | 121 | | } |