From dcef6e45005c177923fc2bcbbd313e47a1533321 Mon Sep 17 00:00:00 2001 From: Marcel Baumgartner Date: Sat, 6 Jul 2024 11:29:45 +0200 Subject: [PATCH] Switched to new mooncore authentication service --- .../Core/Configuration/CoreConfiguration.cs | 10 ++ Moonlight/Core/CoreFeature.cs | 5 +- .../Extensions/IdentityServiceExtensions.cs | 54 +++++++ .../Helpers/AuthenticationStateProvider.cs | 50 ++++++ .../Core/Http/Controllers/AvatarController.cs | 14 +- .../Core/Models/Forms/UpdateAccountForm.cs | 6 - Moonlight/Core/Models/Session.cs | 2 +- Moonlight/Core/Services/IdentityService.cs | 147 ------------------ Moonlight/Core/UI/Components/Auth/Login.razor | 8 +- .../Core/UI/Components/Auth/Register.razor | 8 +- .../UI/Components/Auth/TwoFactorWizard.razor | 12 +- .../Cards/TimeBasedGreetingMessages.razor | 5 +- .../UI/Components/Partials/AppHeader.razor | 16 +- .../UI/Components/Partials/AppSidebar.razor | 4 +- .../Partials/CookieConsentBanner.razor | 64 ++++---- .../Partials/PermissionChecker.razor | 2 +- .../Partials/SoftErrorHandler.razor | 4 +- Moonlight/Core/UI/Layouts/MainLayout.razor | 8 +- Moonlight/Core/UI/Views/Account/Api.razor | 2 +- Moonlight/Core/UI/Views/Account/Index.razor | 16 +- .../Core/UI/Views/Account/Security.razor | 6 +- Moonlight/Core/UI/Views/Admin/Index.razor | 4 +- .../Core/UI/Views/Admin/Users/Sessions.razor | 8 +- Moonlight/Core/UI/Views/Index.razor | 2 +- .../Cards/UserDashboardServerCount.razor | 4 +- .../Servers/UI/Layouts/UserLayout.razor | 5 +- .../Servers/UI/NodeComponents/NodeSetup.razor | 5 +- .../Servers/UI/Views/Servers/Index.razor | 2 +- .../Servers/UI/Views/Servers/Networks.razor | 8 +- Moonlight/_Imports.razor | 4 + 30 files changed, 224 insertions(+), 261 deletions(-) create mode 100644 Moonlight/Core/Extensions/IdentityServiceExtensions.cs create mode 100644 Moonlight/Core/Helpers/AuthenticationStateProvider.cs delete mode 100644 Moonlight/Core/Services/IdentityService.cs diff --git a/Moonlight/Core/Configuration/CoreConfiguration.cs b/Moonlight/Core/Configuration/CoreConfiguration.cs index db0e59fa..f89e839a 100644 --- a/Moonlight/Core/Configuration/CoreConfiguration.cs +++ b/Moonlight/Core/Configuration/CoreConfiguration.cs @@ -90,6 +90,16 @@ public class CoreConfiguration [JsonProperty("DenyRegister")] [Description("This disables the register function. No user will be able to sign up anymore. Its recommended to enable this for private instances")] public bool DenyRegister { get; set; } = false; + + [JsonProperty("EnablePeriodicReAuth")] + [Description( + "If this option is enabled, every session will reauthenticate perdiodicly to track state changes in real time without the user refreshing the page")] + public bool EnablePeriodicReAuth { get; set; } = true; + + [JsonProperty("PeriodicReAuthDelay")] + [Description( + "This option specifies how long the intervals are between reauthentications. The value is specified in minutes")] + public int PeriodicReAuthDelay { get; set; } = 5; } public class SecurityData diff --git a/Moonlight/Core/CoreFeature.cs b/Moonlight/Core/CoreFeature.cs index 6743a11f..3a614ef6 100644 --- a/Moonlight/Core/CoreFeature.cs +++ b/Moonlight/Core/CoreFeature.cs @@ -26,7 +26,7 @@ using Moonlight.Core.Implementations.AdminDashboard; using Moonlight.Core.Implementations.ApiDefinition; using Moonlight.Core.Implementations.UserDashboard; using Swashbuckle.AspNetCore.SwaggerGen; -using IdentityService = Moonlight.Core.Services.IdentityService; +using AuthenticationStateProvider = Moonlight.Core.Helpers.AuthenticationStateProvider; namespace Moonlight.Core; @@ -68,6 +68,9 @@ public class CoreFeature : MoonlightFeature builder.Services.AddMoonCore(configuration => { configuration.Identity.Token = config.Security.Token; + configuration.Identity.PeriodicReAuthDelay = TimeSpan.FromMinutes(config.Authentication.PeriodicReAuthDelay); + configuration.Identity.EnablePeriodicReAuth = config.Authentication.EnablePeriodicReAuth; + configuration.Identity.Provider = new AuthenticationStateProvider(); }); builder.Services.AddMoonCoreBlazor(); diff --git a/Moonlight/Core/Extensions/IdentityServiceExtensions.cs b/Moonlight/Core/Extensions/IdentityServiceExtensions.cs new file mode 100644 index 00000000..83142cae --- /dev/null +++ b/Moonlight/Core/Extensions/IdentityServiceExtensions.cs @@ -0,0 +1,54 @@ +using MoonCore.Abstractions; +using MoonCore.Services; +using Moonlight.Core.Database.Entities; + +namespace Moonlight.Core.Extensions; + +public static class IdentityServiceExtensions +{ + public static User GetUser(this IdentityService identityService) + { + return identityService.Storage.Get(); + } + + public static Task HasFlag(this IdentityService identityService, string flag) + { + if (!identityService.IsAuthenticated) + return Task.FromResult(false); + + var result = identityService.GetUser().Flags.Split(";").Contains(flag); + return Task.FromResult(result); + } + + public static Task SetFlag(this IdentityService identityService, string flag, bool toggle) + { + if (!identityService.IsAuthenticated) + return Task.CompletedTask; + + var user = identityService.GetUser(); + + // Rebuild flags + var flags = user.Flags.Split(";").ToList(); + + if (toggle) + { + if(!flags.Contains(flag)) + flags.Add(flag); + } + else + { + if (flags.Contains(flag)) + flags.Remove(flag); + } + + user.Flags = string.Join(';', flags); + + // Save changes + var serviceProvider = identityService.Storage.Get(); + var userRepo = serviceProvider.GetRequiredService>(); + + userRepo.Update(user); + + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/Moonlight/Core/Helpers/AuthenticationStateProvider.cs b/Moonlight/Core/Helpers/AuthenticationStateProvider.cs new file mode 100644 index 00000000..4b830999 --- /dev/null +++ b/Moonlight/Core/Helpers/AuthenticationStateProvider.cs @@ -0,0 +1,50 @@ +using MoonCore.Abstractions; +using MoonCore.Helpers; +using Moonlight.Core.Database.Entities; + +namespace Moonlight.Core.Helpers; + +public class AuthenticationStateProvider : MoonCore.Abstractions.AuthenticationStateProvider +{ + public override Task IsValidIdentifier(IServiceProvider provider, string identifier) + { + if(!int.TryParse(identifier, out int searchId)) + return Task.FromResult(false); + + var userRepo = provider.GetRequiredService>(); + var result = userRepo.Get().Any(x => x.Id == searchId); + + return Task.FromResult(result); + } + + public override Task LoadFromIdentifier(IServiceProvider provider, string identifier, DynamicStorage storage) + { + if(!int.TryParse(identifier, out int searchId)) + return Task.CompletedTask; + + var userRepo = provider.GetRequiredService>(); + var user = userRepo.Get().FirstOrDefault(x => x.Id == searchId); + + if(user == null) + return Task.CompletedTask; + + storage.Set("User", user); + storage.Set("ServiceProvider", provider); + + return Task.CompletedTask; + } + + public override Task DetermineTokenValidTimestamp(IServiceProvider provider, string identifier) + { + if(!int.TryParse(identifier, out int searchId)) + return Task.FromResult(DateTime.MaxValue); + + var userRepo = provider.GetRequiredService>(); + var user = userRepo.Get().FirstOrDefault(x => x.Id == searchId); + + if(user == null) + return Task.FromResult(DateTime.MaxValue); + + return Task.FromResult(user.TokenValidTimestamp); + } +} \ No newline at end of file diff --git a/Moonlight/Core/Http/Controllers/AvatarController.cs b/Moonlight/Core/Http/Controllers/AvatarController.cs index 530199f2..696463cf 100644 --- a/Moonlight/Core/Http/Controllers/AvatarController.cs +++ b/Moonlight/Core/Http/Controllers/AvatarController.cs @@ -2,13 +2,11 @@ using System.Text; using Microsoft.AspNetCore.Mvc; using MoonCore.Abstractions; -using MoonCore.Helpers; using MoonCore.Services; using Moonlight.Core.Attributes; using Moonlight.Core.Configuration; using Moonlight.Core.Database.Entities; -using Moonlight.Core.Services; -using IdentityService = Moonlight.Core.Services.IdentityService; +using Moonlight.Core.Extensions; namespace Moonlight.Core.Http.Controllers; @@ -42,10 +40,10 @@ public class AvatarController : Controller var token = Request.Cookies["token"]; await IdentityService.Authenticate(token!); - if (!IdentityService.IsLoggedIn) + if (!IdentityService.IsAuthenticated) return StatusCode(403); - return File(await GetAvatar(IdentityService.CurrentUser), "image/jpeg"); + return File(await GetAvatar(IdentityService.GetUser()), "image/jpeg"); } [HttpGet("{id:int}")] @@ -57,12 +55,12 @@ public class AvatarController : Controller var token = Request.Cookies["token"]; await IdentityService.Authenticate(token!); - if (!IdentityService.IsLoggedIn) + if (!IdentityService.IsAuthenticated) return StatusCode(403); if (ConfigService.Get().Security.EnforceAvatarPrivacy && // Do we need to enforce privacy? - id != IdentityService.CurrentUser.Id && // is the user not viewing his own image? - IdentityService.CurrentUser.Permissions < 1000) // and not an admin? + id != IdentityService.GetUser().Id && // is the user not viewing his own image? + IdentityService.GetUser().Permissions < 1000) // and not an admin? { return StatusCode(403); } diff --git a/Moonlight/Core/Models/Forms/UpdateAccountForm.cs b/Moonlight/Core/Models/Forms/UpdateAccountForm.cs index f5fdafc3..f3b6b54c 100644 --- a/Moonlight/Core/Models/Forms/UpdateAccountForm.cs +++ b/Moonlight/Core/Models/Forms/UpdateAccountForm.cs @@ -4,12 +4,6 @@ namespace Moonlight.Core.Models.Forms; public class UpdateAccountForm { - [Required(ErrorMessage = "You need to provide an username")] - [MinLength(6, ErrorMessage = "The username is too short")] - [MaxLength(20, ErrorMessage = "The username cannot be longer than 20 characters")] public string Username { get; set; } - - [Required(ErrorMessage = "You need to provide an email address")] - [EmailAddress(ErrorMessage = "You need to enter a valid email address")] public string Email { get; set; } = ""; } \ No newline at end of file diff --git a/Moonlight/Core/Models/Session.cs b/Moonlight/Core/Models/Session.cs index ba2670b0..0474e7f7 100644 --- a/Moonlight/Core/Models/Session.cs +++ b/Moonlight/Core/Models/Session.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Components; using MoonCore.Blazor.Services; -using Moonlight.Core.Services; +using MoonCore.Services; namespace Moonlight.Core.Models; diff --git a/Moonlight/Core/Services/IdentityService.cs b/Moonlight/Core/Services/IdentityService.cs deleted file mode 100644 index e6ea8cc2..00000000 --- a/Moonlight/Core/Services/IdentityService.cs +++ /dev/null @@ -1,147 +0,0 @@ -using MoonCore.Abstractions; -using MoonCore.Attributes; -using MoonCore.Exceptions; -using MoonCore.Helpers; -using MoonCore.Services; -using Moonlight.Core.Configuration; -using Moonlight.Core.Database.Entities; -using Moonlight.Core.Models.Enums; - -namespace Moonlight.Core.Services; - -[Scoped] -public class IdentityService : IDisposable -{ - public User? CurrentUserNullable { get; private set; } - public User CurrentUser => CurrentUserNullable!; - public bool IsLoggedIn => CurrentUserNullable != null; - public SmartEventHandler OnAuthenticationStateChanged { get; set; } - - private string Token = ""; - - private readonly JwtService JwtService; - private readonly ConfigService ConfigService; - private readonly Repository UserRepository; - - public IdentityService( - JwtService jwtService, - ConfigService configService, - Repository userRepository, - ILogger eventHandlerLogger) - { - JwtService = jwtService; - ConfigService = configService; - UserRepository = userRepository; - - OnAuthenticationStateChanged = new(eventHandlerLogger); - } - - public async Task Authenticate(User user) - { - var duration = TimeSpan.FromDays(ConfigService.Get().Authentication.TokenDuration); - - var token = await JwtService.Create(data => - { - data.Add("UserId", user.Id.ToString()); - data.Add("IssuedAt", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString()); - }, CoreJwtType.Login, duration); - - await Authenticate(token); - - return token; - } - - public async Task Authenticate(string token) - { - Token = token; - - await Authenticate(); - } - - public async Task Authenticate(bool forceStateChange = false) // Can be used for authentication of the token as well - { - var lastUserId = CurrentUserNullable?.Id ?? -1; - - await ProcessToken(); - - var currentUserId = CurrentUserNullable?.Id ?? -1; - - if (lastUserId != currentUserId || forceStateChange) - await OnAuthenticationStateChanged.Invoke(); - } - - private async Task ProcessToken() - { - CurrentUserNullable = null; - - // Check jwt signature - if (!await JwtService.Validate(Token, CoreJwtType.Login)) - return; - - var data = await JwtService.Decode(Token); - - // Check for missing content - if(!data.ContainsKey("UserId") || !data.ContainsKey("IssuedAt")) - return; - - // Load user - var userId = int.Parse(data["UserId"]); - - var user = UserRepository - .Get() - .FirstOrDefault(x => x.Id == userId); - - // Check if user was found - if(user == null) - return; - - // Check token valid time - var issuedAt = long.Parse(data["IssuedAt"]); - var issuedAtDateTime = DateTimeOffset.FromUnixTimeSeconds(issuedAt).DateTime; - - // If the valid time is newer then when the token was issued, the token is not longer valid - if (user.TokenValidTimestamp > issuedAtDateTime) - return; - - CurrentUserNullable = user; - } - - public Task HasFlag(string flag) - { - if (!IsLoggedIn) - return Task.FromResult(false); - - var flags = CurrentUser.Flags.Split(";"); - - return Task.FromResult(flags.Contains(flag)); - } - - public Task SetFlag(string flag, bool toggle) - { - if (!IsLoggedIn) - throw new DisplayException("Unable to set flag while not logged in"); - - var flags = CurrentUser.Flags.Split(";").ToList(); - - if (toggle) - { - if(!flags.Contains(flag)) - flags.Add(flag); - } - else - { - if (flags.Contains(flag)) - flags.Remove(flag); - } - - CurrentUser.Flags = string.Join(';', flags); - UserRepository.Update(CurrentUser); - - return Task.CompletedTask; - } - - public async void Dispose() - { - await OnAuthenticationStateChanged.ClearSubscribers(); - } -} \ No newline at end of file diff --git a/Moonlight/Core/UI/Components/Auth/Login.razor b/Moonlight/Core/UI/Components/Auth/Login.razor index 3402f97a..87587c40 100644 --- a/Moonlight/Core/UI/Components/Auth/Login.razor +++ b/Moonlight/Core/UI/Components/Auth/Login.razor @@ -3,13 +3,14 @@ @using Moonlight.Core.Models.Abstractions @using Moonlight.Core.Models.Forms -@using Moonlight.Core.Services @using MoonCore.Exceptions +@using Moonlight.Core.Configuration @inject IAuthenticationProvider AuthenticationProvider @inject IdentityService IdentityService @inject CookieService CookieService @inject NavigationManager Navigation +@inject ConfigService ConfigService
@@ -89,7 +90,10 @@ throw new DisplayException("A user with these credential combination was not found"); // Generate token and authenticate - var token = await IdentityService.Authenticate(user); + var token = await IdentityService.Login( + user.Id.ToString(), + TimeSpan.FromHours(ConfigService.Get().Authentication.TokenDuration) + ); // Save token for later use await CookieService.SetValue("token", token, 30); //TODO: Add days to config option diff --git a/Moonlight/Core/UI/Components/Auth/Register.razor b/Moonlight/Core/UI/Components/Auth/Register.razor index d7cb984c..849b170f 100644 --- a/Moonlight/Core/UI/Components/Auth/Register.razor +++ b/Moonlight/Core/UI/Components/Auth/Register.razor @@ -4,11 +4,8 @@ @using Moonlight.Core.Models.Abstractions @using Moonlight.Core.Models.Forms -@using Moonlight.Core.Services @using MoonCore.Exceptions -@using MoonCore.Services @using Moonlight.Core.Configuration -@using IdentityService = Moonlight.Core.Services.IdentityService @inject IAuthenticationProvider AuthenticationProvider @inject IdentityService IdentityService @@ -96,7 +93,10 @@ throw new DisplayException("Unable to create account"); // Generate token and authenticate - var token = await IdentityService.Authenticate(user); + var token = await IdentityService.Login( + user.Id.ToString(), + TimeSpan.FromHours(ConfigService.Get().Authentication.TokenDuration) + ); // Save token for later use await CookieService.SetValue("token", token, 30); // TODO: config diff --git a/Moonlight/Core/UI/Components/Auth/TwoFactorWizard.razor b/Moonlight/Core/UI/Components/Auth/TwoFactorWizard.razor index 4d4dc37a..1a9cda51 100644 --- a/Moonlight/Core/UI/Components/Auth/TwoFactorWizard.razor +++ b/Moonlight/Core/UI/Components/Auth/TwoFactorWizard.razor @@ -9,7 +9,7 @@ @inject AlertService AlertService @inject IAuthenticationProvider AuthenticationProvider -@if (IdentityService.CurrentUser.Totp) +@if (IdentityService.GetUser().Totp) {
@@ -43,7 +43,7 @@ else var qrCodeData = qrGenerator.CreateQrCode ( - $"otpauth://totp/{Uri.EscapeDataString(IdentityService.CurrentUser.Email)}?secret={Key}&issuer={Uri.EscapeDataString("Moonlight")}", + $"otpauth://totp/{Uri.EscapeDataString(IdentityService.GetUser().Email)}?secret={Key}&issuer={Uri.EscapeDataString("Moonlight")}", QRCodeGenerator.ECCLevel.Q ); @@ -142,8 +142,8 @@ else private async Task Disable(ConfirmButton _) { - await AuthenticationProvider.SetTwoFactorSecret(IdentityService.CurrentUser, ""); - await IdentityService.Authenticate(true); + await AuthenticationProvider.SetTwoFactorSecret(IdentityService.GetUser(), ""); + await IdentityService.Authenticate(); HasStarted = false; HasCompletedAppLinks = false; @@ -177,8 +177,8 @@ else } // Enable two factor auth for user - await AuthenticationProvider.SetTwoFactorSecret(IdentityService.CurrentUser, Key); - await IdentityService.Authenticate(true); + await AuthenticationProvider.SetTwoFactorSecret(IdentityService.GetUser(), Key); + await IdentityService.Authenticate(); HasStarted = false; HasCompletedAppLinks = false; diff --git a/Moonlight/Core/UI/Components/Cards/TimeBasedGreetingMessages.razor b/Moonlight/Core/UI/Components/Cards/TimeBasedGreetingMessages.razor index 5da4737f..c645228f 100644 --- a/Moonlight/Core/UI/Components/Cards/TimeBasedGreetingMessages.razor +++ b/Moonlight/Core/UI/Components/Cards/TimeBasedGreetingMessages.razor @@ -1,7 +1,6 @@ @using MoonCore.Services @using Moonlight.Core.Configuration -@using Moonlight.Core.Services -@using IdentityService = Moonlight.Core.Services.IdentityService +@using Moonlight.Core.Database.Entities @inject IdentityService IdentityService @inject ConfigService ConfigService @@ -13,7 +12,7 @@ var greeting = GetGreetingMessage(); } @greeting.Item1 - @IdentityService.CurrentUser.Username + @IdentityService.GetUser().Username @greeting.Item2
diff --git a/Moonlight/Core/UI/Components/Partials/AppHeader.razor b/Moonlight/Core/UI/Components/Partials/AppHeader.razor index 9fadd38f..cf2d4e2f 100644 --- a/Moonlight/Core/UI/Components/Partials/AppHeader.razor +++ b/Moonlight/Core/UI/Components/Partials/AppHeader.razor @@ -1,6 +1,4 @@ -@using Moonlight.Core.Services - -@inject IdentityService IdentityService +@inject IdentityService IdentityService @inject CookieService CookieService
@@ -24,13 +22,13 @@
- @if (IdentityService.IsLoggedIn) + @if (IdentityService.IsAuthenticated) {
@@ -80,7 +78,7 @@ protected override Task OnAfterRenderAsync(bool firstRender) { if (firstRender) - IdentityService.OnAuthenticationStateChanged += OnAuthenticationStateChanged; + IdentityService.OnStateChanged += OnAuthenticationStateChanged; return Task.CompletedTask; } @@ -96,6 +94,6 @@ await CookieService.SetValue("token", "", 30); // Reset token in identity service - await IdentityService.Authenticate(""); + await IdentityService.Logout(); } } \ No newline at end of file diff --git a/Moonlight/Core/UI/Components/Partials/AppSidebar.razor b/Moonlight/Core/UI/Components/Partials/AppSidebar.razor index ed251ff0..9341ed66 100644 --- a/Moonlight/Core/UI/Components/Partials/AppSidebar.razor +++ b/Moonlight/Core/UI/Components/Partials/AppSidebar.razor @@ -56,13 +56,13 @@ } } - @if (IdentityService.IsLoggedIn && IdentityService.CurrentUser.Permissions > 0) + @if (IdentityService.IsAuthenticated && IdentityService.GetUser().Permissions > 0) { - @foreach (var sidebarItem in FeatureService.UiContext.SidebarItems.Where(x => x.IsAdmin).OrderBy(x => x.Index).ToArray()) + foreach (var sidebarItem in FeatureService.UiContext.SidebarItems.Where(x => x.IsAdmin).OrderBy(x => x.Index).ToArray()) { if (IsMatch(sidebarItem)) { diff --git a/Moonlight/Core/UI/Components/Partials/CookieConsentBanner.razor b/Moonlight/Core/UI/Components/Partials/CookieConsentBanner.razor index 0989c9c8..c4885f78 100644 --- a/Moonlight/Core/UI/Components/Partials/CookieConsentBanner.razor +++ b/Moonlight/Core/UI/Components/Partials/CookieConsentBanner.razor @@ -1,8 +1,4 @@ -@using ApexCharts -@using MoonCore.Services -@using Moonlight.Core.Configuration -@using Moonlight.Core.Services -@using IdentityService = Moonlight.Core.Services.IdentityService +@using Moonlight.Core.Configuration @inject ConfigService ConfigService @inject IdentityService IdentityService @@ -13,17 +9,17 @@
-

@ConfigService.Get().Customisation.CookieConsentBanner.BannerTitle

+

@BannerTitle

- @ConfigService.Get().Customisation.CookieConsentBanner.BannerText + @BannerText

- - @ConfigService.Get().Customisation.CookieConsentBanner.ConsentText - - - @ConfigService.Get().Customisation.CookieConsentBanner.DeclineText - + + @ConsentText + + + @DeclineText +
@@ -31,16 +27,31 @@
} -@code { - +@code +{ private bool ShowBanner; + private string BannerTitle; + private string BannerText; + private string ConsentText; + private string DeclineText; + + protected override void OnInitialized() + { + var config = ConfigService.Get().Customisation.CookieConsentBanner; + + BannerTitle = config.BannerTitle; + BannerText = config.BannerText; + ConsentText = config.ConsentText; + DeclineText = config.DeclineText; + } + protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { var userWasAsked = await IdentityService.HasFlag("CookieAsked"); - + if (ConfigService.Get().Customisation.CookieConsentBanner.Enabled && !userWasAsked) ShowBanner = true; @@ -48,25 +59,16 @@ } } - private async Task Consent() + private async Task SetAnswer(bool answer) { - if (!IdentityService.IsLoggedIn) - return; - - await IdentityService.SetFlag("CookieAsked", true); - await IdentityService.SetFlag("CookieConsent", true); - - await InvokeAsync(StateHasChanged); - } - - private async Task Decline() - { - if (!IdentityService.IsLoggedIn) + if (!IdentityService.IsAuthenticated) return; await IdentityService.SetFlag("CookieAsked", true); - + + if (answer) + await IdentityService.SetFlag("CookieConsent", true); + await InvokeAsync(StateHasChanged); } - } \ No newline at end of file diff --git a/Moonlight/Core/UI/Components/Partials/PermissionChecker.razor b/Moonlight/Core/UI/Components/Partials/PermissionChecker.razor index ad21c235..ef404acf 100644 --- a/Moonlight/Core/UI/Components/Partials/PermissionChecker.razor +++ b/Moonlight/Core/UI/Components/Partials/PermissionChecker.razor @@ -52,7 +52,7 @@ else if(permissionRequired == null) continue; - if (IdentityService.CurrentUser.Permissions >= permissionRequired.Level) + if (IdentityService.GetUser().Permissions >= permissionRequired.Level) Allowed = true; } diff --git a/Moonlight/Core/UI/Components/Partials/SoftErrorHandler.razor b/Moonlight/Core/UI/Components/Partials/SoftErrorHandler.razor index 27858698..ff596554 100644 --- a/Moonlight/Core/UI/Components/Partials/SoftErrorHandler.razor +++ b/Moonlight/Core/UI/Components/Partials/SoftErrorHandler.razor @@ -10,7 +10,7 @@ @if (Crashed || Exception != null) { - if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" || (IdentityService.IsLoggedIn && IdentityService.CurrentUser.Permissions >= 9000)) + if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development" || (IdentityService.IsAuthenticated && IdentityService.GetUser().Permissions >= 9000)) { if (Exception != null) { @@ -75,7 +75,7 @@ else Exception = exception; Crashed = true; - var username = IdentityService.IsLoggedIn ? IdentityService.CurrentUser.Username : "Guest"; + var username = IdentityService.IsAuthenticated ? IdentityService.GetUser().Username : "Guest"; Logger.LogWarning("A crash occured in the view of '{username}': {exception}", username, exception); } diff --git a/Moonlight/Core/UI/Layouts/MainLayout.razor b/Moonlight/Core/UI/Layouts/MainLayout.razor index ab8dceb0..5ad40a44 100644 --- a/Moonlight/Core/UI/Layouts/MainLayout.razor +++ b/Moonlight/Core/UI/Layouts/MainLayout.razor @@ -1,9 +1,7 @@ @using Moonlight.Core.Services @using Moonlight.Core.UI.Components.Auth -@using MoonCore.Services @using Moonlight.Core.Configuration @using Moonlight.Core.Events -@using IdentityService = Moonlight.Core.Services.IdentityService @inherits LayoutComponentBase @@ -27,7 +25,7 @@
- @if (IdentityService.IsLoggedIn) + @if (IdentityService.IsAuthenticated) { } @@ -54,7 +52,7 @@ { if (IsInitialized) { - if (IdentityService.IsLoggedIn) + if (IdentityService.IsAuthenticated) { @Body @@ -115,7 +113,7 @@ // Base init await lazyLoader.SetText("Initializing"); - IdentityService.OnAuthenticationStateChanged += OnAuthenticationStateChanged; + IdentityService.OnStateChanged += OnAuthenticationStateChanged; CoreEvents.OnMoonlightRestart += async () => { diff --git a/Moonlight/Core/UI/Views/Account/Api.razor b/Moonlight/Core/UI/Views/Account/Api.razor index fb21b19d..cc5bbc81 100644 --- a/Moonlight/Core/UI/Views/Account/Api.razor +++ b/Moonlight/Core/UI/Views/Account/Api.razor @@ -10,7 +10,7 @@ @* the @@@ looks weird, ik that, it will result in @username *@ - @@@IdentityService.CurrentUser.Username + @@@IdentityService.GetUser().Username
diff --git a/Moonlight/Core/UI/Views/Account/Index.razor b/Moonlight/Core/UI/Views/Account/Index.razor index ed218f6c..73b39638 100644 --- a/Moonlight/Core/UI/Views/Account/Index.razor +++ b/Moonlight/Core/UI/Views/Account/Index.razor @@ -17,7 +17,7 @@ @* the @@@ looks weird, ik that, it will result in @username *@ - @@@IdentityService.CurrentUser.Username + @@@IdentityService.GetUser().Username
@@ -43,7 +43,7 @@
- +
@@ -112,9 +112,9 @@ if (PasswordModel.Password != PasswordModel.RepeatedPassword) throw new DisplayException("The passwords do not match"); - await AuthenticationProvider.ChangePassword(IdentityService.CurrentUser, PasswordModel.Password); + await AuthenticationProvider.ChangePassword(IdentityService.GetUser(), PasswordModel.Password); await ToastService.Success("Successfully changed password"); - await IdentityService.Authenticate(true); + await IdentityService.Authenticate(); } } \ No newline at end of file diff --git a/Moonlight/Core/UI/Views/Admin/Index.razor b/Moonlight/Core/UI/Views/Admin/Index.razor index 9d7d9a22..872cf906 100644 --- a/Moonlight/Core/UI/Views/Admin/Index.razor +++ b/Moonlight/Core/UI/Views/Admin/Index.razor @@ -12,7 +12,7 @@
@foreach (var column in Columns.OrderBy(x => x.Index)) { - if (column.RequiredPermissionLevel <= IdentityService.CurrentUser.Permissions) + if (column.RequiredPermissionLevel <= IdentityService.GetUser().Permissions) {
@column.Component @@ -22,7 +22,7 @@
@foreach (var component in Components.OrderBy(x => x.Index)) { - if (component.RequiredPermissionLevel <= IdentityService.CurrentUser.Permissions) + if (component.RequiredPermissionLevel <= IdentityService.GetUser().Permissions) {
@component.Component diff --git a/Moonlight/Core/UI/Views/Admin/Users/Sessions.razor b/Moonlight/Core/UI/Views/Admin/Users/Sessions.razor index 3f96fffe..faf93bad 100644 --- a/Moonlight/Core/UI/Views/Admin/Users/Sessions.razor +++ b/Moonlight/Core/UI/Views/Admin/Users/Sessions.razor @@ -29,10 +29,12 @@ PageSize="50">