Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Code style refactor (#11)
Leendert de Borstbcb432adec2f
diff --git a/src/AliasVault.WebApp/CustomAuthStateProvider.cs b/src/AliasVault.WebApp/Auth/Providers/AuthStateProvider.cssimilarity index 50%rename from src/AliasVault.WebApp/CustomAuthStateProvider.csrename to src/AliasVault.WebApp/Auth/Providers/AuthStateProvider.csindex 4bac47c95..e13fc7d27 100644--- a/src/AliasVault.WebApp/CustomAuthStateProvider.cs+++ b/src/AliasVault.WebApp/Auth/Providers/AuthStateProvider.cs@@ -1,24 +1,49 @@+//-----------------------------------------------------------------------+// <copyright file="AuthStateProvider.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------+using AliasVault.WebApp.Auth.Services;-using Blazored.LocalStorage;-namespace AliasVault.WebApp;+namespace AliasVault.WebApp.Auth.Providers;using System.Security.Claims;using System.Text.Json;using Microsoft.AspNetCore.Components.Authorization;-public class CustomAuthStateProvider : AuthenticationStateProvider+/// <summary>+/// Custom authentication state provider for the application.+/// </summary>+public class AuthStateProvider(AuthService authService) : AuthenticationStateProvider{- private readonly AuthService _authService;-- public CustomAuthStateProvider(AuthService authService)+ /// <summary>+ /// Parses the claims from the JWT token.+ /// </summary>+ /// <param name="jwt">The JWT token.</param>+ /// <returns>The claims parsed from the JWT token.</returns>+ public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt){- _authService = authService;+ var payload = jwt.Split('.')[1];+ var jsonBytes = ParseBase64WithoutPadding(payload);+ var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);++ if (keyValuePairs == null)+ {+ throw new InvalidOperationException("Failed to parse JWT token.");+ }++ return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString() ?? string.Empty));}+ /// <summary>+ /// Gets the authentication state asynchronously.+ /// </summary>+ /// <returns>The authentication state.</returns>public override async Task<AuthenticationState> GetAuthenticationStateAsync(){- string token = await _authService.GetAccessTokenAsync();+ string token = await authService.GetAccessTokenAsync();var identity = new ClaimsIdentity();@@ -31,7 +56,7 @@ public class CustomAuthStateProvider : AuthenticationStateProvidercatch (Exception){Console.WriteLine("Invalid JWT token. Removing...");- await _authService.RemoveTokensAsync();+ await authService.RemoveTokensAsync();identity = new ClaimsIdentity();}}@@ -44,14 +69,11 @@ public class CustomAuthStateProvider : AuthenticationStateProviderreturn state;}- public static IEnumerable<Claim> ParseClaimsFromJwt(string jwt)- {- var payload = jwt.Split('.')[1];- var jsonBytes = ParseBase64WithoutPadding(payload);- var keyValuePairs = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonBytes);- return keyValuePairs.Select(kvp => new Claim(kvp.Key, kvp.Value.ToString()));- }-+ /// <summary>+ /// Parses the base64 string without padding.+ /// </summary>+ /// <param name="base64">The base64 string.</param>+ /// <returns>The byte array parsed from the base64 string.</returns>private static byte[] ParseBase64WithoutPadding(string base64){switch (base64.Length % 4)@@ -59,6 +81,7 @@ public class CustomAuthStateProvider : AuthenticationStateProvidercase 2: base64 += "=="; break;case 3: base64 += "="; break;}+return Convert.FromBase64String(base64);}}diff --git a/src/AliasVault.WebApp/Auth/Services/AuthService.cs b/src/AliasVault.WebApp/Auth/Services/AuthService.csindex ff7d00761..f4c6a0304 100644--- a/src/AliasVault.WebApp/Auth/Services/AuthService.cs+++ b/src/AliasVault.WebApp/Auth/Services/AuthService.cs@@ -136,7 +136,8 @@ public class AuthService/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>private async Task RevokeTokenAsync(){- var tokenInput = new TokenModel {+ var tokenInput = new TokenModel+ {Token = await GetAccessTokenAsync(),RefreshToken = await GetRefreshTokenAsync(),};diff --git a/src/AliasVault.WebApp/Components/Email/RecentEmails.razor b/src/AliasVault.WebApp/Components/Email/RecentEmails.razorindex ad270809e..b39067ed6 100644--- a/src/AliasVault.WebApp/Components/Email/RecentEmails.razor+++ b/src/AliasVault.WebApp/Components/Email/RecentEmails.razor@@ -1,4 +1,5 @@-@using BlazorServer.Models.Spamok+@using AliasVault.WebApp.Pages.Aliases.Models.Spamok+@using BlazorServer.Models.Spamok@inherits ComponentBase@inject IHttpClientFactory HttpClientFactory@@ -79,9 +80,9 @@ elseStateHasChanged();var client = HttpClientFactory.CreateClient("EmailClient");- MailboxApiModel mailbox = await client.GetFromJsonAsync<MailboxApiModel>($"https://api.spamok.com/v2/EmailBox/{EmailPrefix}");+ MailboxApiModel? mailbox = await client.GetFromJsonAsync<MailboxApiModel>($"https://api.spamok.com/v2/EmailBox/{EmailPrefix}");- if (mailbox.Mails != null)+ if (mailbox?.Mails != null){MailboxEmails = mailbox.Mails;}diff --git a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razorindex 02695c6a9..aec47cc17 100644--- a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor+++ b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor@@ -173,7 +173,7 @@ elseprotected override async Task OnInitializedAsync(){- await Task.Yield();+ await base.OnInitializedAsync();if (EditMode){@@ -191,8 +191,21 @@ else{if (EditMode){+ if (Id is null)+ {+ Navigation.NavigateTo("/404");+ return;+ }+// Load existing obj, retrieve from service- obj = await AliasService.LoadAliasAsync(Id.Value);+ var alias = await AliasService.LoadAliasAsync(Id.Value);+ if (alias is null)+ {+ Navigation.NavigateTo("/404");+ return;+ }++ alias = obj;}else{@@ -257,7 +270,7 @@ else// Try to extract favicon from service URL// TODO: Fix favicon extraction/*if (obj.Service.Url != null && !string.IsNullOrEmpty(obj.Service.Url))- {+ {obj.Service.Logo = await FaviconExtractor.FaviconService.GetFaviconAsync(obj.Service.Url);} */@@ -277,7 +290,10 @@ elseif (EditMode){- await AliasService.UpdateAliasAsync(obj, Id.Value);+ if (Id is not null)+ {+ await AliasService.UpdateAliasAsync(obj, Id.Value);+ }}else{diff --git a/src/AliasVault.WebApp/Pages/Aliases/Delete.razor b/src/AliasVault.WebApp/Pages/Aliases/Delete.razorindex 79ce4bd7c..de8bcf171 100644--- a/src/AliasVault.WebApp/Pages/Aliases/Delete.razor+++ b/src/AliasVault.WebApp/Pages/Aliases/Delete.razor@@ -53,6 +53,7 @@ elseprotected override async Task OnInitializedAsync(){+ await base.OnInitializedAsync();BreadcrumbItems.Add(new BreadcrumbItem { Url = "alias/" + Id, DisplayName = "View Alias" });BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Delete alias" });}diff --git a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.csindex 82305d79f..45ba35741 100644--- a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs+++ b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs@@ -5,7 +5,7 @@// </copyright>//------------------------------------------------------------------------namespace BlazorServer.Models.Spamok;+namespace AliasVault.WebApp.Pages.Aliases.Models.Spamok;/// <summary>/// Represents a mailbox API model.diff --git a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxEmailApiModel.cs b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxEmailApiModel.csindex 7da7477cb..9a40df224 100644--- a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxEmailApiModel.cs+++ b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxEmailApiModel.cs@@ -1,16 +1,69 @@-namespace BlazorServer.Models.Spamok;+//-----------------------------------------------------------------------+// <copyright file="MailboxEmailApiModel.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------+namespace AliasVault.WebApp.Pages.Aliases.Models.Spamok;++/// <summary>+/// Represents a mailbox email API model.+/// </summary>public class MailboxEmailApiModel{+ /// <summary>+ /// Gets or sets the ID of the email.+ /// </summary>public int Id { get; set; }- public string Subject { get; set; }- public string FromDisplay { get; set; }- public string FromDomain { get; set; }- public string FromLocal { get; set; }- public string ToDomain { get; set; }- public string ToLocal { get; set; }++ /// <summary>+ /// Gets or sets the subject of the email.+ /// </summary>+ public string Subject { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the display name of the sender.+ /// </summary>+ public string FromDisplay { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the domain of the sender's email address.+ /// </summary>+ public string FromDomain { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the local part of the sender's email address.+ /// </summary>+ public string FromLocal { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the domain of the recipient's email address.+ /// </summary>+ public string ToDomain { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the local part of the recipient's email address.+ /// </summary>+ public string ToLocal { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the date of the email.+ /// </summary>public DateTime Date { get; set; }++ /// <summary>+ /// Gets or sets the system date of the email.+ /// </summary>public DateTime DateSystem { get; set; }- public string MessagePreview { get; set; }++ /// <summary>+ /// Gets or sets the preview of the email message.+ /// </summary>+ public string MessagePreview { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the number of seconds ago the email was received.+ /// </summary>public double SecondsAgo { get; set; }-}\ No newline at end of file+}diff --git a/src/AliasVault.WebApp/Pages/Base/PageBase.cs b/src/AliasVault.WebApp/Pages/Base/PageBase.csindex 043678d27..fe2f2baaa 100644--- a/src/AliasVault.WebApp/Pages/Base/PageBase.cs+++ b/src/AliasVault.WebApp/Pages/Base/PageBase.cs@@ -1,10 +1,17 @@-using AliasVault.WebApp.Components.Models;+//-----------------------------------------------------------------------+// <copyright file="PageBase.cs" company="lanedirt">+// Copyright (c) lanedirt. All rights reserved.+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.+// </copyright>+//-----------------------------------------------------------------------++namespace AliasVault.WebApp.Pages.Base;++using AliasVault.WebApp.Components.Models;using Microsoft.AspNetCore.Components;using Microsoft.AspNetCore.Components.Authorization;using Microsoft.JSInterop;-namespace AliasVault.WebApp.Pages.Base;-/// <summary>/// Base authorize page that all pages that are part of the logged in website should inherit from./// All pages that inherit from this class will require the user to be logged in and have a confirmed email.@@ -12,22 +19,35 @@ namespace AliasVault.WebApp.Pages.Base;/// </summary>public class PageBase : OwningComponentBase{+ private bool _parametersInitialSet;++ /// <summary>+ /// Gets or sets the NavigationManager.+ /// </summary>[Inject]public NavigationManager NavigationManager { get; set; } = null!;+ /// <summary>+ /// Gets or sets the AuthenticationStateProvider.+ /// </summary>[Inject]public AuthenticationStateProvider AuthStateProvider { get; set; } = null!;+ /// <summary>+ /// Gets or sets the IJSRuntime.+ /// </summary>[Inject]public IJSRuntime Js { get; set; } = null!;/// <summary>- /// Contains the breadcrumb items for the page. A default set of breadcrumbs is added in the parent OnInitialized method.+ /// Gets or sets the breadcrumb items for the page. A default set of breadcrumbs is added in the parent OnInitialized method./// </summary>protected List<BreadcrumbItem> BreadcrumbItems { get; set; } = new List<BreadcrumbItem>();- private bool _parametersInitialSet;-+ /// <summary>+ /// Initializes the component asynchronously.+ /// </summary>+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>protected override async Task OnInitializedAsync(){await base.OnInitializedAsync();@@ -37,28 +57,32 @@ public class PageBase : OwningComponentBaseBreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Home", Url = NavigationManager.BaseUri });// Detect success messages in query string and add them to the SuccessMessages list+ // TODO: Implement this with example for default add/edit update action...var uri = new Uri(NavigationManager.Uri);}/// <summary>- /// Get username from the authentication state.+ /// Gets the username from the authentication state asynchronously./// </summary>- /// <returns></returns>+ /// <returns>The username.</returns>protected async Task<string> GetUsernameAsync(){var authState = await AuthStateProvider.GetAuthenticationStateAsync();return authState.User?.Identity?.Name ?? "[Unknown]";}+ /// <summary>+ /// Sets the parameters asynchronously.+ /// </summary>+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>protected override async Task OnParametersSetAsync(){await base.OnParametersSetAsync();- // This is needed to prevent the OnParametersSetAsync method from running together with OnInitialized on initial page load.+ // This is to prevent the OnParametersSetAsync method from running together with OnInitialized on initial page load.if (!_parametersInitialSet){_parametersInitialSet = true;- return;}}}diff --git a/src/AliasVault.WebApp/Program.cs b/src/AliasVault.WebApp/Program.csindex 35c7a3b2c..aa0ff9208 100644--- a/src/AliasVault.WebApp/Program.cs+++ b/src/AliasVault.WebApp/Program.cs@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Components.Authorization;using AliasVault.WebApp;using AliasVault.WebApp.Services;using AliasVault.WebApp.Auth.Services;+using AliasVault.WebApp.Auth.Providers;var builder = WebAssemblyHostBuilder.CreateDefault(args);@@ -26,7 +27,7 @@ builder.Services.AddScoped(sp =>return httpClient;});-builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();+builder.Services.AddScoped<AuthenticationStateProvider, AuthStateProvider>();builder.Services.AddScoped<AliasService>();builder.Services.AddSingleton<ClipboardCopyService>();