| | | 1 | | using System.Text.Json; |
| | | 2 | | using Microsoft.AspNetCore.Components; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using Microsoft.JSInterop; |
| | | 5 | | using RaidLoop.Client.Configuration; |
| | | 6 | | using Supabase.Gotrue; |
| | | 7 | | |
| | | 8 | | namespace RaidLoop.Client.Services; |
| | | 9 | | |
| | | 10 | | public sealed class SupabaseAuthService : ISupabaseSessionProvider |
| | | 11 | | { |
| | | 12 | | private const string SessionStorageKey = "raidloop.auth.session.v1"; |
| | | 13 | | private const string PkceVerifierStorageKey = "raidloop.auth.pkce-verifier.v1"; |
| | | 14 | | |
| | | 15 | | private readonly IJSRuntime _jsRuntime; |
| | | 16 | | private readonly NavigationManager _navigationManager; |
| | | 17 | | private readonly IClientTelemetryService Telemetry; |
| | | 18 | | private readonly SupabaseOptions _options; |
| | | 19 | | |
| | | 20 | | private Supabase.Client? _client; |
| | | 21 | | private bool _isInitialized; |
| | | 22 | | private bool _isSignedOutLocally; |
| | | 23 | | |
| | 2 | 24 | | public SupabaseAuthService( |
| | 2 | 25 | | IJSRuntime jsRuntime, |
| | 2 | 26 | | NavigationManager navigationManager, |
| | 2 | 27 | | IClientTelemetryService telemetry, |
| | 2 | 28 | | IOptions<SupabaseOptions> options) |
| | | 29 | | { |
| | 2 | 30 | | _jsRuntime = jsRuntime; |
| | 2 | 31 | | _navigationManager = navigationManager; |
| | 2 | 32 | | Telemetry = telemetry; |
| | 2 | 33 | | _options = options.Value; |
| | 2 | 34 | | } |
| | | 35 | | |
| | | 36 | | public event Action? AuthStateChanged; |
| | | 37 | | |
| | 0 | 38 | | public bool IsLoading { get; private set; } |
| | | 39 | | |
| | 1 | 40 | | public bool IsAuthenticated => !_isSignedOutLocally && _client?.Auth.CurrentSession is not null; |
| | | 41 | | |
| | 0 | 42 | | public string? UserEmail => _client?.Auth.CurrentUser?.Email; |
| | | 43 | | |
| | 0 | 44 | | public Supabase.Client? Client => _client; |
| | | 45 | | |
| | | 46 | | public async Task InitializeAsync() |
| | | 47 | | { |
| | 0 | 48 | | if (_isInitialized) |
| | | 49 | | { |
| | 0 | 50 | | return; |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | IsLoading = true; |
| | 0 | 54 | | NotifyAuthStateChanged(); |
| | | 55 | | |
| | 0 | 56 | | _client = new Supabase.Client( |
| | 0 | 57 | | _options.Url, |
| | 0 | 58 | | _options.PublishableKey, |
| | 0 | 59 | | new Supabase.SupabaseOptions |
| | 0 | 60 | | { |
| | 0 | 61 | | AutoConnectRealtime = false |
| | 0 | 62 | | }); |
| | | 63 | | |
| | 0 | 64 | | await _client.InitializeAsync(); |
| | 0 | 65 | | _client.Auth.AddStateChangedListener((_, _) => _ = HandleAuthSessionChangedAsync()); |
| | 0 | 66 | | _isSignedOutLocally = false; |
| | | 67 | | |
| | 0 | 68 | | var currentUri = new Uri(_navigationManager.Uri); |
| | 0 | 69 | | if (TryGetQueryParameter(currentUri, "code", out var code)) |
| | | 70 | | { |
| | 0 | 71 | | Session? session = null; |
| | 0 | 72 | | var pkceVerifier = await LoadPkceVerifierAsync(); |
| | 0 | 73 | | if (!string.IsNullOrWhiteSpace(pkceVerifier)) |
| | | 74 | | { |
| | | 75 | | try |
| | | 76 | | { |
| | 0 | 77 | | session = await _client.Auth.ExchangeCodeForSession(pkceVerifier, code); |
| | 0 | 78 | | } |
| | 0 | 79 | | catch (Exception ex) |
| | | 80 | | { |
| | 0 | 81 | | await ReportHandledErrorAsync("Supabase PKCE session exchange failed.", "auth-session", ex); |
| | 0 | 82 | | throw; |
| | | 83 | | } |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | if (session is not null) |
| | | 87 | | { |
| | 0 | 88 | | await PersistSessionAsync(session); |
| | | 89 | | } |
| | | 90 | | |
| | 0 | 91 | | await ClearPkceVerifierAsync(); |
| | 0 | 92 | | _navigationManager.NavigateTo(GetCurrentPathWithoutQueryOrFragment(), replace: true); |
| | 0 | 93 | | } |
| | | 94 | | else |
| | | 95 | | { |
| | 0 | 96 | | var persisted = await LoadPersistedSessionAsync(); |
| | 0 | 97 | | if (persisted is not null) |
| | | 98 | | { |
| | | 99 | | try |
| | | 100 | | { |
| | 0 | 101 | | await _client.Auth.SetSession(persisted.AccessToken, persisted.RefreshToken, false); |
| | 0 | 102 | | } |
| | 0 | 103 | | catch (Exception ex) |
| | | 104 | | { |
| | 0 | 105 | | await ReportHandledErrorAsync("Supabase session restore failed.", "auth-session", ex); |
| | 0 | 106 | | await ClearPersistedSessionAsync(); |
| | | 107 | | } |
| | | 108 | | } |
| | | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | if (_client.Auth.CurrentSession is not null) |
| | | 112 | | { |
| | 0 | 113 | | _isSignedOutLocally = false; |
| | 0 | 114 | | await PersistSessionAsync(_client.Auth.CurrentSession); |
| | | 115 | | } |
| | | 116 | | |
| | 0 | 117 | | _isInitialized = true; |
| | 0 | 118 | | IsLoading = false; |
| | 0 | 119 | | NotifyAuthStateChanged(); |
| | 0 | 120 | | } |
| | | 121 | | |
| | | 122 | | public async Task SignInWithGoogleAsync() |
| | | 123 | | { |
| | 0 | 124 | | if (_client is null) |
| | | 125 | | { |
| | 0 | 126 | | await InitializeAsync(); |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | _isSignedOutLocally = false; |
| | | 130 | | |
| | 0 | 131 | | var providerState = await _client!.Auth.SignIn( |
| | 0 | 132 | | Supabase.Gotrue.Constants.Provider.Google, |
| | 0 | 133 | | new SignInOptions |
| | 0 | 134 | | { |
| | 0 | 135 | | FlowType = Constants.OAuthFlowType.PKCE, |
| | 0 | 136 | | RedirectTo = GetCurrentUriWithoutQueryOrFragment() |
| | 0 | 137 | | }); |
| | | 138 | | |
| | 0 | 139 | | if (!string.IsNullOrWhiteSpace(providerState.PKCEVerifier)) |
| | | 140 | | { |
| | 0 | 141 | | await PersistPkceVerifierAsync(providerState.PKCEVerifier); |
| | | 142 | | } |
| | | 143 | | |
| | 0 | 144 | | _navigationManager.NavigateTo(providerState.Uri.ToString(), forceLoad: true); |
| | 0 | 145 | | } |
| | | 146 | | |
| | | 147 | | public async Task SignInWithEmailPasswordAsync(string email, string password) |
| | | 148 | | { |
| | 0 | 149 | | if (_client is null) |
| | | 150 | | { |
| | 0 | 151 | | await InitializeAsync(); |
| | | 152 | | } |
| | | 153 | | |
| | 0 | 154 | | var session = await _client!.Auth.SignIn(email, password); |
| | 0 | 155 | | _isSignedOutLocally = false; |
| | | 156 | | |
| | 0 | 157 | | if (session is not null) |
| | | 158 | | { |
| | 0 | 159 | | await PersistSessionAsync(session); |
| | | 160 | | } |
| | | 161 | | |
| | 0 | 162 | | NotifyAuthStateChanged(); |
| | 0 | 163 | | } |
| | | 164 | | |
| | | 165 | | public async Task SignUpWithEmailPasswordAsync(string email, string password) |
| | | 166 | | { |
| | 0 | 167 | | if (_client is null) |
| | | 168 | | { |
| | 0 | 169 | | await InitializeAsync(); |
| | | 170 | | } |
| | | 171 | | |
| | 0 | 172 | | var session = await _client!.Auth.SignUp(email, password, new SignUpOptions()); |
| | 0 | 173 | | _isSignedOutLocally = false; |
| | | 174 | | |
| | 0 | 175 | | if (session is not null) |
| | | 176 | | { |
| | 0 | 177 | | await PersistSessionAsync(session); |
| | | 178 | | } |
| | | 179 | | |
| | 0 | 180 | | NotifyAuthStateChanged(); |
| | 0 | 181 | | } |
| | | 182 | | |
| | | 183 | | public async Task SignOutAsync() |
| | | 184 | | { |
| | 1 | 185 | | if (_client?.Auth is not null) |
| | | 186 | | { |
| | | 187 | | try |
| | | 188 | | { |
| | 0 | 189 | | await _client.Auth.SignOut(); |
| | 0 | 190 | | } |
| | 0 | 191 | | catch (Exception ex) |
| | | 192 | | { |
| | 0 | 193 | | await ReportHandledErrorAsync("Supabase remote sign-out failed.", "auth-session", ex); |
| | | 194 | | // Force a local sign-out path when the remote session is already invalid. |
| | | 195 | | } |
| | | 196 | | } |
| | | 197 | | |
| | 1 | 198 | | _isSignedOutLocally = true; |
| | 1 | 199 | | await ClearPersistedSessionAsync(); |
| | 1 | 200 | | await ClearPkceVerifierAsync(); |
| | 1 | 201 | | NotifyAuthStateChanged(); |
| | 1 | 202 | | } |
| | | 203 | | |
| | | 204 | | public async Task<string> GetAccessTokenAsync() |
| | | 205 | | { |
| | 0 | 206 | | if (_client is null) |
| | | 207 | | { |
| | 0 | 208 | | await InitializeAsync(); |
| | | 209 | | } |
| | | 210 | | |
| | 0 | 211 | | if (_client is null) |
| | | 212 | | { |
| | 0 | 213 | | throw new InvalidOperationException("Supabase client is not available."); |
| | | 214 | | } |
| | | 215 | | |
| | 0 | 216 | | var session = _client.Auth.CurrentSession; |
| | 0 | 217 | | if (session?.ExpiresAt().Subtract(TimeSpan.FromMinutes(1)) <= DateTime.UtcNow) |
| | | 218 | | { |
| | | 219 | | try |
| | | 220 | | { |
| | 0 | 221 | | await _client.Auth.RefreshSession(); |
| | 0 | 222 | | session = _client.Auth.CurrentSession; |
| | 0 | 223 | | } |
| | 0 | 224 | | catch (Exception ex) |
| | | 225 | | { |
| | 0 | 226 | | await ReportHandledErrorAsync("Supabase session refresh failed.", "auth-session", ex); |
| | 0 | 227 | | _isSignedOutLocally = true; |
| | 0 | 228 | | await ClearPersistedSessionAsync(); |
| | 0 | 229 | | NotifyAuthStateChanged(); |
| | 0 | 230 | | throw new InvalidOperationException("Supabase session refresh failed."); |
| | | 231 | | } |
| | | 232 | | } |
| | | 233 | | |
| | 0 | 234 | | var accessToken = session?.AccessToken; |
| | 0 | 235 | | if (string.IsNullOrWhiteSpace(accessToken)) |
| | | 236 | | { |
| | 0 | 237 | | throw new InvalidOperationException("Supabase session is not available."); |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | return accessToken; |
| | 0 | 241 | | } |
| | | 242 | | |
| | | 243 | | private async Task PersistSessionAsync(Session session) |
| | | 244 | | { |
| | 0 | 245 | | if (string.IsNullOrWhiteSpace(session.AccessToken) || string.IsNullOrWhiteSpace(session.RefreshToken)) |
| | | 246 | | { |
| | 0 | 247 | | return; |
| | | 248 | | } |
| | | 249 | | |
| | 0 | 250 | | var persisted = new PersistedSession(session.AccessToken, session.RefreshToken); |
| | 0 | 251 | | var payload = JsonSerializer.Serialize(persisted); |
| | 0 | 252 | | await _jsRuntime.InvokeVoidAsync("raidLoopStorage.save", SessionStorageKey, payload); |
| | 0 | 253 | | } |
| | | 254 | | |
| | | 255 | | private async Task<PersistedSession?> LoadPersistedSessionAsync() |
| | | 256 | | { |
| | 0 | 257 | | var payload = await _jsRuntime.InvokeAsync<string?>("raidLoopStorage.load", SessionStorageKey); |
| | 0 | 258 | | if (string.IsNullOrWhiteSpace(payload)) |
| | | 259 | | { |
| | 0 | 260 | | return null; |
| | | 261 | | } |
| | | 262 | | |
| | | 263 | | try |
| | | 264 | | { |
| | 0 | 265 | | return JsonSerializer.Deserialize<PersistedSession>(payload); |
| | | 266 | | } |
| | 0 | 267 | | catch |
| | | 268 | | { |
| | 0 | 269 | | return null; |
| | | 270 | | } |
| | 0 | 271 | | } |
| | | 272 | | |
| | | 273 | | private async Task ClearPersistedSessionAsync() |
| | | 274 | | { |
| | 1 | 275 | | await _jsRuntime.InvokeVoidAsync("raidLoopStorage.remove", SessionStorageKey); |
| | 1 | 276 | | } |
| | | 277 | | |
| | | 278 | | private async Task PersistPkceVerifierAsync(string verifier) |
| | | 279 | | { |
| | 0 | 280 | | await _jsRuntime.InvokeVoidAsync("raidLoopStorage.save", PkceVerifierStorageKey, verifier); |
| | 0 | 281 | | } |
| | | 282 | | |
| | | 283 | | private Task<string?> LoadPkceVerifierAsync() |
| | | 284 | | { |
| | 0 | 285 | | return _jsRuntime.InvokeAsync<string?>("raidLoopStorage.load", PkceVerifierStorageKey).AsTask(); |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | private async Task ClearPkceVerifierAsync() |
| | | 289 | | { |
| | 1 | 290 | | await _jsRuntime.InvokeVoidAsync("raidLoopStorage.remove", PkceVerifierStorageKey); |
| | 1 | 291 | | } |
| | | 292 | | |
| | | 293 | | private async Task HandleAuthSessionChangedAsync() |
| | | 294 | | { |
| | 0 | 295 | | if (_client?.Auth.CurrentSession is not null) |
| | | 296 | | { |
| | 0 | 297 | | _isSignedOutLocally = false; |
| | 0 | 298 | | await PersistSessionAsync(_client.Auth.CurrentSession); |
| | | 299 | | } |
| | | 300 | | else |
| | | 301 | | { |
| | 0 | 302 | | _isSignedOutLocally = true; |
| | 0 | 303 | | await ClearPersistedSessionAsync(); |
| | | 304 | | } |
| | | 305 | | |
| | 0 | 306 | | NotifyAuthStateChanged(); |
| | 0 | 307 | | } |
| | | 308 | | |
| | | 309 | | private void NotifyAuthStateChanged() |
| | | 310 | | { |
| | 1 | 311 | | AuthStateChanged?.Invoke(); |
| | 0 | 312 | | } |
| | | 313 | | |
| | | 314 | | private ValueTask ReportHandledErrorAsync(string message, string source, Exception? exception = null) |
| | | 315 | | { |
| | 0 | 316 | | return Telemetry.ReportErrorAsync( |
| | 0 | 317 | | message, |
| | 0 | 318 | | new |
| | 0 | 319 | | { |
| | 0 | 320 | | source, |
| | 0 | 321 | | exception = exception?.GetType().FullName, |
| | 0 | 322 | | exceptionMessage = exception?.Message, |
| | 0 | 323 | | stack = exception?.ToString() |
| | 0 | 324 | | }); |
| | | 325 | | } |
| | | 326 | | |
| | | 327 | | private string GetCurrentUriWithoutQueryOrFragment() |
| | | 328 | | { |
| | 0 | 329 | | var currentUri = new Uri(_navigationManager.Uri); |
| | 0 | 330 | | return currentUri.GetLeftPart(UriPartial.Path); |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | private string GetCurrentPathWithoutQueryOrFragment() |
| | | 334 | | { |
| | 0 | 335 | | var currentUri = new Uri(_navigationManager.Uri); |
| | 0 | 336 | | var path = currentUri.GetLeftPart(UriPartial.Path); |
| | 0 | 337 | | return _navigationManager.ToBaseRelativePath(path) switch |
| | 0 | 338 | | { |
| | 0 | 339 | | "" => ".", |
| | 0 | 340 | | var relativePath => relativePath |
| | 0 | 341 | | }; |
| | | 342 | | } |
| | | 343 | | |
| | | 344 | | private static bool TryGetQueryParameter(Uri uri, string key, out string value) |
| | | 345 | | { |
| | 0 | 346 | | foreach (var pair in uri.Query.TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) |
| | | 347 | | { |
| | 0 | 348 | | var parts = pair.Split('=', 2); |
| | 0 | 349 | | if (!string.Equals(parts[0], key, StringComparison.OrdinalIgnoreCase)) |
| | | 350 | | { |
| | | 351 | | continue; |
| | | 352 | | } |
| | | 353 | | |
| | 0 | 354 | | value = parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : string.Empty; |
| | 0 | 355 | | return true; |
| | | 356 | | } |
| | | 357 | | |
| | 0 | 358 | | value = string.Empty; |
| | 0 | 359 | | return false; |
| | | 360 | | } |
| | | 361 | | |
| | 0 | 362 | | private sealed record PersistedSession(string AccessToken, string RefreshToken); |
| | | 363 | | |
| | | 364 | | } |