diff --git a/Moonlight.ApiServer/Http/Controllers/Auth/AuthController.cs b/Moonlight.ApiServer/Http/Controllers/Auth/AuthController.cs index 5d0c1c69..28de66d3 100644 --- a/Moonlight.ApiServer/Http/Controllers/Auth/AuthController.cs +++ b/Moonlight.ApiServer/Http/Controllers/Auth/AuthController.cs @@ -1,19 +1,7 @@ -using System.Text.Json; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; using MoonCore.Attributes; using MoonCore.Authentication; -using MoonCore.Exceptions; -using MoonCore.Extended.Abstractions; -using MoonCore.Extended.Helpers; -using MoonCore.Extended.OAuth2.ApiServer; -using MoonCore.Extensions; -using MoonCore.Helpers; -using MoonCore.Services; -using Moonlight.ApiServer.Configuration; using Moonlight.ApiServer.Database.Entities; -using Moonlight.ApiServer.Interfaces.Auth; -using Moonlight.ApiServer.Interfaces.OAuth2; -using Moonlight.Shared.Http.Requests.Auth; using Moonlight.Shared.Http.Responses.Auth; namespace Moonlight.ApiServer.Http.Controllers.Auth; @@ -22,6 +10,7 @@ namespace Moonlight.ApiServer.Http.Controllers.Auth; [Route("api/auth")] public class AuthController : Controller { + /* private readonly OAuth2Service OAuth2Service; private readonly TokenHelper TokenHelper; private readonly DatabaseRepository UserRepository; @@ -205,7 +194,7 @@ public class AuthController : Controller // All checks have passed, allow refresh newData.Add("userId", user.Id); return true; - } + }*/ [HttpGet("check")] [RequirePermission("meta.authenticated")] diff --git a/Moonlight.ApiServer/Http/Controllers/OAuth2/OAuth2Controller.cs b/Moonlight.ApiServer/Http/Controllers/OAuth2/OAuth2Controller.cs index d6a85c0f..8a50cdeb 100644 --- a/Moonlight.ApiServer/Http/Controllers/OAuth2/OAuth2Controller.cs +++ b/Moonlight.ApiServer/Http/Controllers/OAuth2/OAuth2Controller.cs @@ -3,8 +3,8 @@ using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Mvc; using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; -using MoonCore.Extended.OAuth2.AuthServer; using MoonCore.Extended.OAuth2.Models; +using MoonCore.Extended.OAuth2.Provider; using Moonlight.ApiServer.Database.Entities; using Moonlight.ApiServer.Http.Controllers.OAuth2.Pages; using Moonlight.ApiServer.Services; @@ -16,11 +16,11 @@ namespace Moonlight.ApiServer.Http.Controllers.OAuth2; [Microsoft.AspNetCore.Mvc.Route("oauth2")] public class OAuth2Controller : Controller { - private readonly OAuth2Service OAuth2Service; + private readonly OAuth2ProviderService OAuth2Service; private readonly AuthService AuthService; private readonly DatabaseRepository UserRepository; - public OAuth2Controller(OAuth2Service oAuth2Service, + public OAuth2Controller(OAuth2ProviderService oAuth2Service, AuthService authService, DatabaseRepository userRepository) { OAuth2Service = oAuth2Service; diff --git a/Moonlight.ApiServer/Implementations/TestyOuth2Provider.cs b/Moonlight.ApiServer/Implementations/TestyOuth2Provider.cs new file mode 100644 index 00000000..32053fc1 --- /dev/null +++ b/Moonlight.ApiServer/Implementations/TestyOuth2Provider.cs @@ -0,0 +1,65 @@ +using MoonCore.Extended.Abstractions; +using MoonCore.Extended.Interfaces; +using MoonCore.Extended.OAuth2.Models; +using MoonCore.Extensions; +using Moonlight.ApiServer.Configuration; +using Moonlight.ApiServer.Database.Entities; +using Moonlight.Shared.Http.Responses.OAuth2; + +namespace Moonlight.ApiServer.Implementations; + +public class TestyOuth2Provider : IOAuth2Provider +{ + public async Task> Sync(IServiceProvider provider, AccessData accessData) + { + var logger = provider.GetRequiredService>(); + + try + { + var configuration = provider.GetRequiredService(); + + using var httpClient = new HttpClient(); + + httpClient.DefaultRequestHeaders.Add("Authorization", accessData.AccessToken); + + var response = await httpClient.GetAsync($"{configuration.PublicUrl}/oauth2/info"); + await response.HandlePossibleApiError(); + var info = await response.ParseAsJson(); + + var userRepo = provider.GetRequiredService>(); + var user = userRepo.Get().FirstOrDefault(x => x.Email == info.Email); + + if (user == null) // User not found, register a new one + { + user = userRepo.Add(new User() + { + Email = info.Email, + Username = info.Username + }); + } + else if (user.Username != info.Username) // Username updated? + { + // Username not used by another user? + if (!userRepo.Get().Any(x => x.Username == info.Username)) + { + // Update username + user.Username = info.Username; + userRepo.Update(user); + } + } + + return new() + { + { + "userId", + user.Id + } + }; + } + catch (Exception e) + { + logger.LogCritical("Unable to sync user: {e}", e); + return new(); + } + } +} \ No newline at end of file diff --git a/Moonlight.ApiServer/Moonlight.ApiServer.csproj b/Moonlight.ApiServer/Moonlight.ApiServer.csproj index c657f43b..24cde91b 100644 --- a/Moonlight.ApiServer/Moonlight.ApiServer.csproj +++ b/Moonlight.ApiServer/Moonlight.ApiServer.csproj @@ -8,13 +8,13 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + diff --git a/Moonlight.ApiServer/Program.cs b/Moonlight.ApiServer/Program.cs index 2b56e739..a185c0a5 100644 --- a/Moonlight.ApiServer/Program.cs +++ b/Moonlight.ApiServer/Program.cs @@ -9,6 +9,7 @@ using Moonlight.ApiServer; using Moonlight.ApiServer.Configuration; using Moonlight.ApiServer.Helpers; using Moonlight.ApiServer.Http.Middleware; +using Moonlight.ApiServer.Implementations; using Moonlight.ApiServer.Interfaces.Auth; using Moonlight.ApiServer.Interfaces.OAuth2; using Moonlight.ApiServer.Interfaces.Startup; @@ -112,7 +113,6 @@ foreach (var startupInterface in appStartupInterfaces) builder.Services.AddControllers(); builder.Services.AddSingleton(config); builder.Services.AutoAddServices(); -builder.Services.AddSingleton(); builder.Services.AddHttpClient(); await Startup.ConfigureTokenAuthentication(builder, config); @@ -127,6 +127,8 @@ builder.Services.AddPlugins(configuration => configuration.AddAssembly(Assembly.GetEntryAssembly()!); }); +builder.Services.AddSingleton(new TestyOuth2Provider()); + var app = builder.Build(); await Startup.PrepareDatabase(app); @@ -145,6 +147,7 @@ app.UseRouting(); app.UseMiddleware(); await Startup.UseTokenAuthentication(app); +await Startup.UseOAuth2(app); // Call interfaces foreach (var startupInterface in appStartupInterfaces) diff --git a/Moonlight.ApiServer/Startup.cs b/Moonlight.ApiServer/Startup.cs index b97d4568..b01ec915 100644 --- a/Moonlight.ApiServer/Startup.cs +++ b/Moonlight.ApiServer/Startup.cs @@ -1,5 +1,6 @@ using System.Text.Json; using MoonCore.Authentication; +using MoonCore.Exceptions; using MoonCore.Extended.Abstractions; using MoonCore.Extended.Extensions; using MoonCore.Extended.Helpers; @@ -8,6 +9,7 @@ using MoonCore.Helpers; using Moonlight.ApiServer.Configuration; using Moonlight.ApiServer.Database.Entities; using Moonlight.ApiServer.Helpers; +using Moonlight.ApiServer.Interfaces.OAuth2; using Moonlight.ApiServer.Interfaces.Startup; namespace Moonlight.ApiServer; @@ -20,7 +22,7 @@ public static class Startup { // Create logging path Directory.CreateDirectory(PathBuilder.Dir("storage", "logs")); - + // Configure application logging builder.Logging.ClearProviders(); @@ -60,8 +62,9 @@ public static class Startup #region Token Authentication - public static Task ConfigureTokenAuthentication(IHostApplicationBuilder builder, AppConfiguration config) + public static Task ConfigureTokenAuthentication(WebApplicationBuilder builder, AppConfiguration config) { + /* builder.Services.AddTokenAuthentication(configuration => { configuration.AccessSecret = config.Authentication.AccessSecret; @@ -89,14 +92,123 @@ public static class Startup return true; }; + });*/ + + builder.AddTokenAuthentication(authenticationConfig => + { + authenticationConfig.AccessSecret = config.Authentication.AccessSecret; + authenticationConfig.RefreshSecret = config.Authentication.RefreshSecret; + + authenticationConfig.AccessDuration = config.Authentication.AccessDuration; + authenticationConfig.RefreshDuration = config.Authentication.RefreshDuration; + + authenticationConfig.ProcessAccess = (accessData, provider, httpContext) => + { + if (!accessData.TryGetValue("userId", out var userIdStr) || !userIdStr.TryGetInt32(out var userId)) + return Task.FromResult(false); + + var userRepo = provider.GetRequiredService>(); + var user = userRepo.Get().FirstOrDefault(x => x.Id == userId); + + if (user == null) + return Task.FromResult(false); + + // Load permissions, handle empty values + var permissions = JsonSerializer.Deserialize( + string.IsNullOrEmpty(user.PermissionsJson) ? "[]" : user.PermissionsJson + ) ?? []; + + // Save permission state + httpContext.User = new PermClaimsPrinciple(permissions) + { + IdentityModel = user + }; + + return Task.FromResult(true); + }; + + authenticationConfig.ProcessRefresh = (oldData, newData, serviceProvider) => + { + var oauth2Providers = serviceProvider.GetRequiredService(); + + // Find oauth2 provider + var provider = oauth2Providers.FirstOrDefault(); + + if (provider == null) + throw new HttpApiException("No oauth2 provider has been registered", 500); + + // Check if the userId is present in the refresh token + if (!oldData.TryGetValue("userId", out var userIdStr) || + !userIdStr.TryGetInt32(out var userId)) + { + return Task.FromResult(false); + } + + // Load user from database if existent + var userRepo = serviceProvider.GetRequiredService>(); + + var user = userRepo + .Get() + .FirstOrDefault(x => x.Id == userId); + + if (user == null) + return Task.FromResult(false); + + // Allow plugins to intercept the refresh call + //if (AuthInterceptors.Any(interceptor => !interceptor.AllowRefresh(user, serviceProvider))) + // return false; + + /* + + // Check if it's time to resync with the oauth2 provider + if (DateTime.UtcNow >= user.RefreshTimestamp) + { + try + { + // It's time to refresh the access to the external oauth2 provider + var refreshData = OAuth2Service.RefreshAccess(user.RefreshToken).Result; + + // Sync user with oauth2 provider + var syncedUser = provider.Sync(serviceProvider, refreshData.AccessToken).Result; + + if (syncedUser == null) // User sync has failed. No refresh allowed + return false; + + // Save oauth2 refresh and access tokens for later use (re-authentication etc.). + // Fetch user model in current db context, just in case the oauth2 provider + // uses a different db context or smth + + var userModel = UserRepository + .Get() + .First(x => x.Id == syncedUser.Id); + + userModel.AccessToken = refreshData.AccessToken; + userModel.RefreshToken = refreshData.RefreshToken; + userModel.RefreshTimestamp = DateTime.UtcNow.AddSeconds(refreshData.ExpiresIn); + + UserRepository.Update(userModel); + } + catch (Exception e) + { + // We are handling this error more softly, because it will occur when a user hasn't logged in a long period of time + Logger.LogDebug("An error occured while refreshing external oauth2 access: {e}", e); + return false; + } + }*/ + + // All checks have passed, allow refresh + newData.Add("userId", user.Id); + return Task.FromResult(true); + }; }); return Task.CompletedTask; } - public static Task UseTokenAuthentication(IApplicationBuilder builder) + public static Task UseTokenAuthentication(WebApplication builder) { builder.UseTokenAuthentication(); + return Task.CompletedTask; } @@ -140,9 +252,9 @@ public static class Startup #region OAuth2 - public static Task ConfigureOAuth2(IHostApplicationBuilder builder, ILogger logger, AppConfiguration config) + public static Task ConfigureOAuth2(WebApplicationBuilder builder, ILogger logger, AppConfiguration config) { - builder.Services.AddOAuth2Consumer(configuration => + builder.AddOAuth2Consumer(configuration => { configuration.ClientId = config.Authentication.OAuth2.ClientId; configuration.ClientSecret = config.Authentication.OAuth2.ClientSecret; @@ -168,6 +280,34 @@ public static class Startup configuration.AuthorizationEndpoint = config.Authentication.OAuth2.AuthorizationUri!; } }); + + /* + builder.Services.AddOAuth2Consumer(configuration => + { + configuration.ClientId = config.Authentication.OAuth2.ClientId; + configuration.ClientSecret = config.Authentication.OAuth2.ClientSecret; + configuration.AuthorizationRedirect = + config.Authentication.OAuth2.AuthorizationRedirect ?? $"{config.PublicUrl}/auth"; + + configuration.AccessEndpoint = + config.Authentication.OAuth2.AccessEndpoint ?? $"{config.PublicUrl}/oauth2/access"; + configuration.RefreshEndpoint = + config.Authentication.OAuth2.RefreshEndpoint ?? $"{config.PublicUrl}/oauth2/refresh"; + + if (config.Authentication.UseLocalOAuth2) + { + configuration.AuthorizationEndpoint = config.Authentication.OAuth2.AuthorizationRedirect ?? + $"{config.PublicUrl}/oauth2/authorize"; + } + else + { + if (config.Authentication.OAuth2.AuthorizationUri == null) + logger.LogWarning( + "The 'AuthorizationUri' for the oauth2 client is not set. If you want to use an external oauth2 provider, you need to specify this url. If you want to use the local oauth2 service, set 'UseLocalOAuth2Service' to true"); + + configuration.AuthorizationEndpoint = config.Authentication.OAuth2.AuthorizationUri!; + } + });*/ if (!config.Authentication.UseLocalOAuth2) return Task.CompletedTask; @@ -190,5 +330,11 @@ public static class Startup return Task.CompletedTask; } + public static Task UseOAuth2(WebApplication application) + { + application.UseOAuth2Consumer(); + return Task.CompletedTask; + } + #endregion } \ No newline at end of file diff --git a/Moonlight.Client/Implementations/AuthenticationUiHandler.cs b/Moonlight.Client/Implementations/AuthenticationUiHandler.cs index 95de0d66..64fe539d 100644 --- a/Moonlight.Client/Implementations/AuthenticationUiHandler.cs +++ b/Moonlight.Client/Implementations/AuthenticationUiHandler.cs @@ -12,6 +12,7 @@ public class AuthenticationUiHandler : IAppLoader, IAppScreen 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 @@ -21,6 +22,7 @@ public class AuthenticationUiHandler : IAppLoader, IAppScreen 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 6cb8f19d..14c61b8c 100644 --- a/Moonlight.Client/Moonlight.Client.csproj +++ b/Moonlight.Client/Moonlight.Client.csproj @@ -10,12 +10,12 @@ - - - - + + + + - + diff --git a/Moonlight.Client/Program.cs b/Moonlight.Client/Program.cs index 1b175154..33a3718f 100644 --- a/Moonlight.Client/Program.cs +++ b/Moonlight.Client/Program.cs @@ -56,6 +56,11 @@ builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); builder.Services.AddScoped(_ => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); + +builder.AddTokenAuthentication(); +builder.AddOAuth2(); + +/* builder.Services.AddScoped(sp => { var httpClient = sp.GetRequiredService(); @@ -93,7 +98,7 @@ builder.Services.AddScoped(sp => }); return result; -}); +});*/ builder.Services.AddMoonCoreBlazorTailwind(); builder.Services.AddScoped(); diff --git a/Moonlight.Client/UI/Components/TestyHmm.razor b/Moonlight.Client/UI/Components/TestyHmm.razor new file mode 100644 index 00000000..2a414127 --- /dev/null +++ b/Moonlight.Client/UI/Components/TestyHmm.razor @@ -0,0 +1,78 @@ +@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 2a7e4bf8..30b7ec79 100644 --- a/Moonlight.Client/UI/Layouts/MainLayout.razor +++ b/Moonlight.Client/UI/Layouts/MainLayout.razor @@ -2,6 +2,8 @@ @using Moonlight.Client.Interfaces @using Moonlight.Client.Services @using Moonlight.Client.UI.Partials +@using MoonCore.Blazor.Components +@using Moonlight.Client.UI.Components @inherits LayoutComponentBase @@ -35,17 +37,19 @@ else
- - - @Body - - - + + + + @Body + + + +
- - + + } @@ -72,9 +76,9 @@ else protected override async Task OnAfterRenderAsync(bool firstRender) { - if(!firstRender) + if (!firstRender) return; - + await Load(); } @@ -82,7 +86,7 @@ else { IsLoading = true; await InvokeAsync(StateHasChanged); - + // await RunLoaders(); @@ -126,7 +130,7 @@ else continue; CurrentScreen = screen.Render(); - + await InvokeAsync(StateHasChanged); return; } @@ -143,7 +147,7 @@ else Task.Run(Load); return Task.FromResult(true); } - + return Task.FromResult(false); } } \ No newline at end of file