|
| 1 | +using System.IdentityModel.Tokens.Jwt; |
| 2 | +using System.Net.Http; |
| 3 | +using System.Net.Http.Json; |
| 4 | +using System.Security.Claims; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using SentenceStudio.Abstractions; |
| 7 | + |
| 8 | +namespace SentenceStudio.Services; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Auth service that authenticates against the API's ASP.NET Identity endpoints |
| 12 | +/// using email/password credentials and JWT tokens. |
| 13 | +/// </summary> |
| 14 | +public sealed class IdentityAuthService : IAuthService |
| 15 | +{ |
| 16 | + private const string JwtKey = "auth_jwt"; |
| 17 | + private const string RefreshKey = "auth_refresh"; |
| 18 | + private const string ExpiresKey = "auth_expires"; |
| 19 | + |
| 20 | + private readonly HttpClient _http; |
| 21 | + private readonly ISecureStorageService _secureStorage; |
| 22 | + private readonly ILogger<IdentityAuthService> _logger; |
| 23 | + |
| 24 | + private string? _cachedToken; |
| 25 | + private DateTimeOffset _cachedExpires; |
| 26 | + private string? _cachedUserName; |
| 27 | + |
| 28 | + public IdentityAuthService( |
| 29 | + IHttpClientFactory httpClientFactory, |
| 30 | + ISecureStorageService secureStorage, |
| 31 | + ILogger<IdentityAuthService> logger) |
| 32 | + { |
| 33 | + _http = httpClientFactory.CreateClient("AuthClient"); |
| 34 | + _secureStorage = secureStorage; |
| 35 | + _logger = logger; |
| 36 | + } |
| 37 | + |
| 38 | + public bool IsSignedIn => _cachedToken is not null && _cachedExpires > DateTimeOffset.UtcNow; |
| 39 | + |
| 40 | + public string? UserName => _cachedUserName; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Silent sign-in: tries to restore a session from stored refresh token. |
| 44 | + /// Returns null if no stored token or refresh fails (UI should show login). |
| 45 | + /// </summary> |
| 46 | + public async Task<AuthResult?> SignInAsync() |
| 47 | + { |
| 48 | + try |
| 49 | + { |
| 50 | + var refreshToken = await _secureStorage.GetAsync(RefreshKey); |
| 51 | + if (string.IsNullOrEmpty(refreshToken)) |
| 52 | + return null; |
| 53 | + |
| 54 | + return await RefreshTokenAsync(refreshToken); |
| 55 | + } |
| 56 | + catch (Exception ex) |
| 57 | + { |
| 58 | + _logger.LogWarning(ex, "Silent sign-in failed"); |
| 59 | + return null; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + /// <summary> |
| 64 | + /// Sign in with email and password against POST /api/auth/login. |
| 65 | + /// </summary> |
| 66 | + public async Task<AuthResult?> SignInAsync(string email, string password) |
| 67 | + { |
| 68 | + try |
| 69 | + { |
| 70 | + var response = await _http.PostAsJsonAsync("/api/auth/login", new { Email = email, Password = password }); |
| 71 | + |
| 72 | + if (!response.IsSuccessStatusCode) |
| 73 | + { |
| 74 | + _logger.LogWarning("Login failed with status {Status}", response.StatusCode); |
| 75 | + return null; |
| 76 | + } |
| 77 | + |
| 78 | + var authResponse = await response.Content.ReadFromJsonAsync<AuthResponseDto>(); |
| 79 | + if (authResponse is null) |
| 80 | + return null; |
| 81 | + |
| 82 | + await StoreTokens(authResponse); |
| 83 | + return ToAuthResult(authResponse); |
| 84 | + } |
| 85 | + catch (Exception ex) |
| 86 | + { |
| 87 | + _logger.LogError(ex, "Sign-in with credentials failed"); |
| 88 | + return null; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// <summary> |
| 93 | + /// Register a new account via POST /api/auth/register. |
| 94 | + /// On success returns an AuthResult if the API auto-logs-in, or null |
| 95 | + /// if the user needs to confirm their email first. |
| 96 | + /// </summary> |
| 97 | + public async Task<AuthResult?> RegisterAsync(string email, string password, string displayName) |
| 98 | + { |
| 99 | + try |
| 100 | + { |
| 101 | + var response = await _http.PostAsJsonAsync("/api/auth/register", new |
| 102 | + { |
| 103 | + Email = email, |
| 104 | + Password = password, |
| 105 | + DisplayName = displayName |
| 106 | + }); |
| 107 | + |
| 108 | + if (!response.IsSuccessStatusCode) |
| 109 | + { |
| 110 | + _logger.LogWarning("Registration failed with status {Status}", response.StatusCode); |
| 111 | + return null; |
| 112 | + } |
| 113 | + |
| 114 | + // Some APIs return tokens on register; try to read them |
| 115 | + try |
| 116 | + { |
| 117 | + var authResponse = await response.Content.ReadFromJsonAsync<AuthResponseDto>(); |
| 118 | + if (authResponse?.Token is not null) |
| 119 | + { |
| 120 | + await StoreTokens(authResponse); |
| 121 | + return ToAuthResult(authResponse); |
| 122 | + } |
| 123 | + } |
| 124 | + catch |
| 125 | + { |
| 126 | + // Registration succeeded but no token returned (email confirmation required) |
| 127 | + } |
| 128 | + |
| 129 | + return null; |
| 130 | + } |
| 131 | + catch (Exception ex) |
| 132 | + { |
| 133 | + _logger.LogError(ex, "Registration failed"); |
| 134 | + return null; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + public async Task SignOutAsync() |
| 139 | + { |
| 140 | + _cachedToken = null; |
| 141 | + _cachedExpires = DateTimeOffset.MinValue; |
| 142 | + _cachedUserName = null; |
| 143 | + |
| 144 | + _secureStorage.Remove(JwtKey); |
| 145 | + _secureStorage.Remove(RefreshKey); |
| 146 | + _secureStorage.Remove(ExpiresKey); |
| 147 | + |
| 148 | + _logger.LogInformation("Signed out, tokens cleared"); |
| 149 | + } |
| 150 | + |
| 151 | + /// <summary> |
| 152 | + /// Returns a valid JWT access token. If the cached token is expired, |
| 153 | + /// attempts a refresh. Returns null if no valid token is available. |
| 154 | + /// </summary> |
| 155 | + public async Task<string?> GetAccessTokenAsync(string[] scopes) |
| 156 | + { |
| 157 | + // Return cached token if still valid (with 60s buffer) |
| 158 | + if (_cachedToken is not null && _cachedExpires > DateTimeOffset.UtcNow.AddSeconds(60)) |
| 159 | + return _cachedToken; |
| 160 | + |
| 161 | + // Try refresh |
| 162 | + try |
| 163 | + { |
| 164 | + var refreshToken = await _secureStorage.GetAsync(RefreshKey); |
| 165 | + if (string.IsNullOrEmpty(refreshToken)) |
| 166 | + return null; |
| 167 | + |
| 168 | + var result = await RefreshTokenAsync(refreshToken); |
| 169 | + return result?.AccessToken; |
| 170 | + } |
| 171 | + catch (Exception ex) |
| 172 | + { |
| 173 | + _logger.LogWarning(ex, "Token refresh failed"); |
| 174 | + return null; |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + private async Task<AuthResult?> RefreshTokenAsync(string refreshToken) |
| 179 | + { |
| 180 | + var response = await _http.PostAsJsonAsync("/api/auth/refresh", new { RefreshToken = refreshToken }); |
| 181 | + |
| 182 | + if (!response.IsSuccessStatusCode) |
| 183 | + { |
| 184 | + _logger.LogWarning("Token refresh returned {Status}", response.StatusCode); |
| 185 | + // Clear invalid refresh token |
| 186 | + _secureStorage.Remove(RefreshKey); |
| 187 | + _cachedToken = null; |
| 188 | + _cachedExpires = DateTimeOffset.MinValue; |
| 189 | + _cachedUserName = null; |
| 190 | + return null; |
| 191 | + } |
| 192 | + |
| 193 | + var authResponse = await response.Content.ReadFromJsonAsync<AuthResponseDto>(); |
| 194 | + if (authResponse is null) |
| 195 | + return null; |
| 196 | + |
| 197 | + await StoreTokens(authResponse); |
| 198 | + return ToAuthResult(authResponse); |
| 199 | + } |
| 200 | + |
| 201 | + private async Task StoreTokens(AuthResponseDto response) |
| 202 | + { |
| 203 | + _cachedToken = response.Token; |
| 204 | + _cachedExpires = new DateTimeOffset(response.ExpiresAt, TimeSpan.Zero); |
| 205 | + _cachedUserName = response.UserName ?? ExtractUserNameFromJwt(response.Token); |
| 206 | + |
| 207 | + await _secureStorage.SetAsync(JwtKey, response.Token); |
| 208 | + await _secureStorage.SetAsync(RefreshKey, response.RefreshToken); |
| 209 | + await _secureStorage.SetAsync(ExpiresKey, response.ExpiresAt.ToString("O")); |
| 210 | + |
| 211 | + _logger.LogInformation("Tokens stored, expires at {Expires}", _cachedExpires); |
| 212 | + } |
| 213 | + |
| 214 | + private AuthResult ToAuthResult(AuthResponseDto response) |
| 215 | + { |
| 216 | + return new AuthResult( |
| 217 | + response.Token, |
| 218 | + response.UserName ?? ExtractUserNameFromJwt(response.Token), |
| 219 | + new DateTimeOffset(response.ExpiresAt, TimeSpan.Zero)); |
| 220 | + } |
| 221 | + |
| 222 | + private static string? ExtractUserNameFromJwt(string token) |
| 223 | + { |
| 224 | + try |
| 225 | + { |
| 226 | + var handler = new JwtSecurityTokenHandler(); |
| 227 | + var jwt = handler.ReadJwtToken(token); |
| 228 | + return jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value |
| 229 | + ?? jwt.Claims.FirstOrDefault(c => c.Type == "email")?.Value |
| 230 | + ?? jwt.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value |
| 231 | + ?? jwt.Claims.FirstOrDefault(c => c.Type == "name")?.Value; |
| 232 | + } |
| 233 | + catch |
| 234 | + { |
| 235 | + return null; |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + /// <summary> |
| 240 | + /// Maps the API's AuthResponse JSON shape. |
| 241 | + /// </summary> |
| 242 | + private sealed record AuthResponseDto( |
| 243 | + string Token, |
| 244 | + string RefreshToken, |
| 245 | + DateTime ExpiresAt, |
| 246 | + string? UserName); |
| 247 | +} |
0 commit comments