@page "/auth" @using MoonCore.Blazor.Services @using MoonCore.Helpers @using Moonlight.Client.Services @using Moonlight.Shared.Http.Requests.Auth @using Moonlight.Shared.Http.Responses.Auth @inject NavigationManager Navigation @inject HttpApiClient HttpApiClient @inject WindowService WindowService @inject HttpClient HttpClient @inject LocalStorageService LocalStorageService @inject ILogger Logger @if (Code == null) {
@if (IsAuthenticating) {

Login flow started in new window/tab

} else {
Moonlight

Login to access your account

Proceed to login
}
} else {
@if (IsHandlingDone) {
Completed illustration

Login successful. You can close this window now

} else {
}
} @code { [SupplyParameterFromQuery(Name = "code")] [Parameter] public string? Code { get; set; } private bool IsAuthenticating = false; private bool IsHandlingDone = false; protected override async Task OnAfterRenderAsync(bool firstRender) { if (!firstRender) return; if (Code == null) return; try { var authHandleData = await HttpApiClient.PostJson("api/auth", new OAuth2HandleRequest() { Code = Code }); // Save the auth handle data await LocalStorageService.SetString("AccessToken", authHandleData.AccessToken); await LocalStorageService.SetString("RefreshToken", authHandleData.RefreshToken); await LocalStorageService.Set("ExpiresAt", authHandleData.ExpiresAt); // Update UI IsHandlingDone = true; await InvokeAsync(StateHasChanged); try { await WindowService.Close(); } finally { await Task.Delay(TimeSpan.FromSeconds(2)); Navigation.NavigateTo("/", true); } } catch (Exception e) { Logger.LogError("An unhandled error occured while handling oauth2 code: {e}", e); } } private async Task StartAuth(WButton _) { var authStartData = await HttpApiClient.GetJson("api/auth"); var uri = authStartData.Endpoint + $"?client_id={authStartData.ClientId}" + $"&redirect_uri={authStartData.RedirectUri}" + $"&response_type=code"; //Navigation.NavigateTo(uri, true); //return; try { await WindowService.Open( uri, "OAuth2 Flow", 600, 470 ); IsAuthenticating = true; await InvokeAsync(StateHasChanged); Task.Run(async () => { while (true) { await Task.Delay(1000); try { if(!await LocalStorageService.ContainsKey("AccessToken")) continue; if (HttpClient.DefaultRequestHeaders.Contains("Authorization")) HttpClient.DefaultRequestHeaders.Remove("Authorization"); HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + await LocalStorageService.GetString("AccessToken")); var res = await HttpClient.GetAsync("api/auth/check"); if (res.IsSuccessStatusCode) break; } catch (Exception e) { Console.WriteLine(e); } } Navigation.NavigateTo(Navigation.Uri, true); }); } catch (Exception) { Navigation.NavigateTo(uri, true); } } }