From f2d653563c8f64f5b644608a96d3dc4829daa749 Mon Sep 17 00:00:00 2001 From: Masu-Baumgartner <68913099+Masu-Baumgartner@users.noreply.github.com> Date: Wed, 6 Nov 2024 16:46:24 +0100 Subject: [PATCH] Adjusting to use new extension methods to configure and handle token auth and oauth2 --- .../Properties/launchSettings.json | 11 ++ .../AuthenticationUiHandler.cs | 12 +- Moonlight.Client/Moonlight.Client.csproj | 4 + Moonlight.Client/Services/IdentityService.cs | 27 ++- Moonlight.Client/UI/App.razor | 44 +++-- Moonlight.Client/UI/Components/TestyHmm.razor | 78 -------- Moonlight.Client/UI/Layouts/MainLayout.razor | 31 +-- .../UI/Screens/AuthenticationScreen.razor | 186 ------------------ 8 files changed, 63 insertions(+), 330 deletions(-) delete mode 100644 Moonlight.Client/UI/Components/TestyHmm.razor delete mode 100644 Moonlight.Client/UI/Screens/AuthenticationScreen.razor diff --git a/Moonlight.ApiServer/Properties/launchSettings.json b/Moonlight.ApiServer/Properties/launchSettings.json index ccaf2211..ebab08ea 100644 --- a/Moonlight.ApiServer/Properties/launchSettings.json +++ b/Moonlight.ApiServer/Properties/launchSettings.json @@ -9,6 +9,17 @@ "ASPNETCORE_ENVIRONMENT": "Development" }, "hotReloadEnabled": true + }, + "WASM Debug": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": false, + "applicationUrl": "http://localhost:5165", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "hotReloadEnabled": true, + "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}" } } } \ No newline at end of file diff --git a/Moonlight.Client/Implementations/AuthenticationUiHandler.cs b/Moonlight.Client/Implementations/AuthenticationUiHandler.cs index 64fe539d..df4afc3a 100644 --- a/Moonlight.Client/Implementations/AuthenticationUiHandler.cs +++ b/Moonlight.Client/Implementations/AuthenticationUiHandler.cs @@ -1,8 +1,6 @@ using Microsoft.AspNetCore.Components; -using MoonCore.Blazor.Helpers; using Moonlight.Client.Interfaces; using Moonlight.Client.Services; -using Moonlight.Client.UI.Screens; namespace Moonlight.Client.Implementations; @@ -11,18 +9,12 @@ public class AuthenticationUiHandler : IAppLoader, IAppScreen public int Priority => 0; public Task ShouldRender(IServiceProvider serviceProvider) - { - return Task.FromResult(false); - var identityService = serviceProvider.GetRequiredService(); - - return Task.FromResult(!identityService.IsLoggedIn); // Only show the screen when we are not logged in - } + => Task.FromResult(false); - public RenderFragment Render() => ComponentHelper.FromType(); + public RenderFragment Render() => throw new NotImplementedException(); public async Task Load(IServiceProvider serviceProvider) { - return; var identityService = serviceProvider.GetRequiredService(); await identityService.Check(); } diff --git a/Moonlight.Client/Moonlight.Client.csproj b/Moonlight.Client/Moonlight.Client.csproj index 14c61b8c..3e4f3a5d 100644 --- a/Moonlight.Client/Moonlight.Client.csproj +++ b/Moonlight.Client/Moonlight.Client.csproj @@ -31,4 +31,8 @@ + + <_ContentIncludedByDefault Remove="UI\Screens\AuthenticationScreen.razor" /> + + diff --git a/Moonlight.Client/Services/IdentityService.cs b/Moonlight.Client/Services/IdentityService.cs index f5d70ad7..79fd0d62 100644 --- a/Moonlight.Client/Services/IdentityService.cs +++ b/Moonlight.Client/Services/IdentityService.cs @@ -9,10 +9,10 @@ namespace Moonlight.Client.Services; [Scoped] public class IdentityService { - public string Username { get; private set; } - public string Email { get; private set; } - public string[] Permissions { get; private set; } - public bool IsLoggedIn { get; private set; } + public string Username { get; private set; } = ""; + public string Email { get; private set; } = ""; + public string[] Permissions { get; private set; } = []; + public bool IsLoggedIn { get; private set; } = false; private readonly HttpApiClient HttpApiClient; private readonly LocalStorageService LocalStorageService; @@ -25,20 +25,15 @@ public class IdentityService public async Task Check() { - try - { - var response = await HttpApiClient.GetJson("api/auth/check"); + IsLoggedIn = false; + + var response = await HttpApiClient.GetJson("api/auth/check"); - Username = response.Username; - Email = response.Email; - Permissions = response.Permissions; + Username = response.Username; + Email = response.Email; + Permissions = response.Permissions; - IsLoggedIn = true; - } - catch (HttpApiException) - { - IsLoggedIn = false; - } + IsLoggedIn = true; //await OnStateChanged?.Invoke(); } diff --git a/Moonlight.Client/UI/App.razor b/Moonlight.Client/UI/App.razor index 9b4d90b4..cd153a74 100644 --- a/Moonlight.Client/UI/App.razor +++ b/Moonlight.Client/UI/App.razor @@ -1,22 +1,28 @@ @using Moonlight.Client.UI.Layouts +@using MoonCore.Blazor.Components +@using Moonlight.Client.UI.Components - - - - - - - - Not found - -
- Not found illustration + + + + + + + + + + Not found + +
+ Not found illustration -

Page not found

-

- The page you requested does not exist -

-
-
-
-
\ No newline at end of file +

Page not found

+

+ The page you requested does not exist +

+
+
+
+
+ + \ No newline at end of file diff --git a/Moonlight.Client/UI/Components/TestyHmm.razor b/Moonlight.Client/UI/Components/TestyHmm.razor deleted file mode 100644 index 2a414127..00000000 --- a/Moonlight.Client/UI/Components/TestyHmm.razor +++ /dev/null @@ -1,78 +0,0 @@ -@using Microsoft.AspNetCore.WebUtilities -@using MoonCore.Blazor.Services -@using MoonCore.Exceptions -@using MoonCore.Helpers -@inherits ErrorBoundaryBase - -@inject NavigationManager Navigation -@inject OAuth2FrontendService OAuth2FrontendService - -@if (IsCompleting) -{ - -} -else -{ - @ChildContent -} - -@code -{ - private bool IsCompleting = false; - private string Code; - - protected override void OnInitialized() - { - var uri = new Uri(Navigation.Uri); - - if (!QueryHelpers.ParseQuery(uri.Query).TryGetValue("code", out var codeSv)) - return; - - try - { - if (codeSv.Count == 0 || string.IsNullOrEmpty(codeSv.First())) - return; - - var code = codeSv.First(); - - Code = code!; - IsCompleting = true; - } - catch (Exception e) - { - Console.WriteLine("FUUCK"); - Console.WriteLine(e); - throw; - } - } - - protected override async Task OnAfterRenderAsync(bool firstRender) - { - if (!firstRender) - return; - - if(!IsCompleting) - return; - - if (!await OAuth2FrontendService.Complete(Code)) - await RedirectToAuth(); - - IsCompleting = false; - await InvokeAsync(StateHasChanged); - } - - protected override async Task OnErrorAsync(Exception exception) - { - if (exception is not HttpApiException httpApiException || httpApiException.Status != 401) - throw exception; - - // If we reach this point, we got a 401 unauthenticated, so we need to log in - await RedirectToAuth(); - } - - private async Task RedirectToAuth() - { - var url = await OAuth2FrontendService.Start(); - Navigation.NavigateTo(url, true); - } -} \ No newline at end of file diff --git a/Moonlight.Client/UI/Layouts/MainLayout.razor b/Moonlight.Client/UI/Layouts/MainLayout.razor index 30b7ec79..0ec8e144 100644 --- a/Moonlight.Client/UI/Layouts/MainLayout.razor +++ b/Moonlight.Client/UI/Layouts/MainLayout.razor @@ -35,16 +35,12 @@ else
- - - - - - @Body - - - - + + + + @Body + +
@@ -110,6 +106,10 @@ else Logger.LogDebug("Running application loader '{name}'", loader.GetType().Name); await loader.Load(ServiceProvider); } + catch (HttpApiException) + { + throw; + } catch (Exception e) { Logger.LogCritical("An app loader threw an unhandled exception: {e}", e); @@ -139,15 +139,4 @@ else } private bool CheckPermission(string permission) => IdentityService.HasPermission(permission); - - private Task HandleException(Exception exception, ErrorHandler handler) - { - if (exception is HttpApiException httpApiException && httpApiException.Status == 401) - { - Task.Run(Load); - return Task.FromResult(true); - } - - return Task.FromResult(false); - } } \ No newline at end of file diff --git a/Moonlight.Client/UI/Screens/AuthenticationScreen.razor b/Moonlight.Client/UI/Screens/AuthenticationScreen.razor deleted file mode 100644 index ae28892a..00000000 --- a/Moonlight.Client/UI/Screens/AuthenticationScreen.razor +++ /dev/null @@ -1,186 +0,0 @@ -@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; - - // TODO: Make this configurable - - 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); - } - } -} \ No newline at end of file