Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Cleanup setup components (#306)
Leendert de Borstda5754d72094
diff --git a/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs b/src/AliasVault.Client/Auth/Pages/Base/LoginBase.csindex 707f5e7ac..3716b5fab 100644--- a/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs+++ b/src/AliasVault.Client/Auth/Pages/Base/LoginBase.cs@@ -27,6 +27,12 @@ public class LoginBase : OwningComponentBase[Inject]public required NavigationManager NavigationManager { get; set; }+ /// <summary>+ /// Gets or sets the UserRegistrationService.+ /// </summary>+ [Inject]+ public required UserRegistrationService UserRegistrationService { get; set; }+/// <summary>/// Gets or sets the HttpClient./// </summary>@@ -51,6 +57,12 @@ public class LoginBase : OwningComponentBase[Inject]public required IJSRuntime Js { get; set; }+ /// <summary>+ /// Gets or sets the JsInteropService.+ /// </summary>+ [Inject]+ public required JsInteropService JsInteropService { get; set; }+/// <summary>/// Gets or sets the DbService./// </summary>diff --git a/src/AliasVault.Client/Auth/Pages/Login.razor b/src/AliasVault.Client/Auth/Pages/Login.razorindex 24a89b279..4291e4f69 100644--- a/src/AliasVault.Client/Auth/Pages/Login.razor+++ b/src/AliasVault.Client/Auth/Pages/Login.razor@@ -2,7 +2,6 @@@inherits AliasVault.Client.Auth.Pages.Base.LoginBase@layout Auth.Layout.MainLayout@attribute [AllowAnonymous]-@inject JsInteropService JsInteropService@using System.Text.Json@using AliasVault.Shared.Models.WebApi.Auth@using AliasVault.Client.Auth.Components@@ -10,26 +9,26 @@@using AliasVault.Cryptography.Client@using SecureRemotePassword-@if (ShowTwoFactorAuthStep)+@if (_showTwoFactorAuthStep){<h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">Two-factor authentication</h2>- <ServerValidationErrors @ref="ServerValidationErrors" />+ <ServerValidationErrors @ref="_serverValidationErrors" /><p class="text-gray-700 dark:text-gray-300 mb-6">Your login is protected with an authenticator app. Enter your authenticator code below.</p><div class="w-full">- <EditForm Model="LoginModel2Fa" FormName="login-with-2fa" OnValidSubmit="Handle2Fa" method="post" class="space-y-6">+ <EditForm Model="_loginModel2Fa" FormName="login-with-2fa" OnValidSubmit="Handle2Fa" method="post" class="space-y-6"><DataAnnotationsValidator/><div><label for="two-factor-code" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Authenticator code</label>- <InputNumber @bind-Value="LoginModel2Fa.TwoFactorCode" id="two-factor-code" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" autocomplete="off"/>- <ValidationMessage For="() => LoginModel2Fa.TwoFactorCode" class="text-red-600 dark:text-red-400 text-sm mt-1"/>+ <InputNumber @bind-Value="_loginModel2Fa.TwoFactorCode" id="two-factor-code" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" autocomplete="off"/>+ <ValidationMessage For="() => _loginModel2Fa.TwoFactorCode" class="text-red-600 dark:text-red-400 text-sm mt-1"/></div><div class="flex items-start"><div class="flex items-center h-5">- <InputCheckbox @bind-Value="LoginModel2Fa.RememberMachine" id="remember-machine" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800"/>+ <InputCheckbox @bind-Value="_loginModel2Fa.RememberMachine" id="remember-machine" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-primary-600 dark:ring-offset-gray-800"/></div><div class="ml-3 text-sm"><label for="remember-machine" class="font-medium text-gray-900 dark:text-white">Remember this machine</label>@@ -43,25 +42,25 @@<button @onclick="LoginWithRecoveryCode" class="text-primary-600 hover:underline dark:text-primary-500">log in with a recovery code</button>.</p>}-else if (ShowLoginWithRecoveryCodeStep)+else if (_showLoginWithRecoveryCodeStep){<h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-4">Recovery code verification</h2>- <ServerValidationErrors @ref="ServerValidationErrors" />+ <ServerValidationErrors @ref="_serverValidationErrors" /><p class="text-gray-700 dark:text-gray-300 mb-6">You have requested to log in with a recovery code. A recovery code is a one-time code that can be used to log in to your account.Note that if you don't manually disable 2FA after login, you will be asked for an authenticator code again at the next login.</p><div class="w-full">- <EditForm Model="LoginModelRecoveryCode" FormName="login-with-recovery-code" OnValidSubmit="HandleRecoveryCode" method="post" class="space-y-6">+ <EditForm Model="_loginModelRecoveryCode" FormName="login-with-recovery-code" OnValidSubmit="HandleRecoveryCode" method="post" class="space-y-6"><DataAnnotationsValidator/><div><label for="two-factor-code" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Recovery Code</label>- <InputText @bind-Value="LoginModelRecoveryCode.RecoveryCode" id="recovery-code" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" autocomplete="off"/>- <ValidationMessage For="() => LoginModelRecoveryCode.RecoveryCode" class="text-red-600 dark:text-red-400 text-sm mt-1"/>+ <InputText @bind-Value="_loginModelRecoveryCode.RecoveryCode" id="recovery-code" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" autocomplete="off"/>+ <ValidationMessage For="() => _loginModelRecoveryCode.RecoveryCode" class="text-red-600 dark:text-red-400 text-sm mt-1"/></div><button type="submit" class="w-full text-white bg-primary-600 hover:bg-primary-700 focus:ring-4 focus:outline-none focus:ring-primary-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">Log in</button></EditForm>@@ -77,25 +76,25 @@ elseLog in to AliasVault</h2>- <FullScreenLoadingIndicator @ref="LoadingIndicator"/>- <ServerValidationErrors @ref="ServerValidationErrors"/>+ <FullScreenLoadingIndicator @ref="_loadingIndicator"/>+ <ServerValidationErrors @ref="_serverValidationErrors"/>- <EditForm Model="LoginModel" OnValidSubmit="HandleLogin" class="mt-8 space-y-6">+ <EditForm Model="_loginModel" OnValidSubmit="HandleLogin" class="mt-8 space-y-6"><DataAnnotationsValidator/><div><label asp-for="Input.Email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your username or email</label>- <InputTextField id="email" @bind-Value="LoginModel.Username" placeholder="name / [email protected]"/>- <ValidationMessage For="() => LoginModel.Username"/>+ <InputTextField id="email" @bind-Value="_loginModel.Username" placeholder="name / [email protected]"/>+ <ValidationMessage For="() => _loginModel.Username"/></div><div><label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>- <InputTextField id="password" @bind-Value="LoginModel.Password" type="password" placeholder="••••••••"/>- <ValidationMessage For="() => LoginModel.Password"/>+ <InputTextField id="password" @bind-Value="_loginModel.Password" type="password" placeholder="••••••••"/>+ <ValidationMessage For="() => _loginModel.Password"/></div><div class="flex items-start"><div class="flex items-center h-5">- <InputCheckbox @bind-Value="LoginModel.RememberMe" id="remember" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" />+ <InputCheckbox @bind-Value="_loginModel.RememberMe" id="remember" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" /></div><div class="ml-3 text-sm"><label for="remember" class="font-medium text-gray-900 dark:text-white">Remember me</label>@@ -111,17 +110,17 @@ else}@code {- private readonly LoginModel LoginModel = new();- private readonly LoginModel2Fa LoginModel2Fa = new();- private readonly LoginModelRecoveryCode LoginModelRecoveryCode = new();- private FullScreenLoadingIndicator LoadingIndicator = new();- private ServerValidationErrors ServerValidationErrors = new();- private bool ShowTwoFactorAuthStep;- private bool ShowLoginWithRecoveryCodeStep;-- private SrpEphemeral ClientEphemeral = new();- private SrpSession ClientSession = new();- private byte[] PasswordHash = [];+ private readonly LoginModel _loginModel = new();+ private readonly LoginModel2Fa _loginModel2Fa = new();+ private readonly LoginModelRecoveryCode _loginModelRecoveryCode = new();+ private FullScreenLoadingIndicator _loadingIndicator = new();+ private ServerValidationErrors _serverValidationErrors = new();+ private bool _showTwoFactorAuthStep;+ private bool _showLoginWithRecoveryCodeStep;++ private SrpEphemeral _clientEphemeral = new();+ private SrpSession _clientSession = new();+ private byte[] _passwordHash = [];/// <inheritdoc />protected override async Task OnInitializedAsync()@@ -134,6 +133,7 @@ else}}+ /// <inheritdoc />protected override async Task OnAfterRenderAsync(bool firstRender){if (firstRender)@@ -145,8 +145,8 @@ elseprivate async Task LoginWithAuthenticator(){- ShowLoginWithRecoveryCodeStep = false;- ShowTwoFactorAuthStep = true;+ _showLoginWithRecoveryCodeStep = false;+ _showTwoFactorAuthStep = true;StateHasChanged();await Task.Delay(100); // Give time for the DOM to update@@ -155,8 +155,8 @@ elseprivate void LoginWithRecoveryCode(){- ShowLoginWithRecoveryCodeStep = true;- ShowTwoFactorAuthStep = false;+ _showLoginWithRecoveryCodeStep = true;+ _showTwoFactorAuthStep = false;StateHasChanged();}@@ -165,22 +165,22 @@ else/// </summary>private async Task HandleLogin(){- LoadingIndicator.Show();- ServerValidationErrors.Clear();+ _loadingIndicator.Show();+ _serverValidationErrors.Clear();try{var errors = await ProcessLoginAsync();foreach (var error in errors){- ServerValidationErrors.AddError(error);+ _serverValidationErrors.AddError(error);}}#if DEBUGcatch (Exception ex){// If in debug mode show the actual exception.- ServerValidationErrors.AddError(ex.ToString());+ _serverValidationErrors.AddError(ex.ToString());}#elsecatch@@ -191,7 +191,7 @@ else#endiffinally{- LoadingIndicator.Hide();+ _loadingIndicator.Hide();}}@@ -199,12 +199,12 @@ else/// Process the login request using username and password./// </summary>/// <returns>List of errors if something went wrong.</returns>- protected async Task<List<string>> ProcessLoginAsync()+ private async Task<List<string>> ProcessLoginAsync(){GlobalNotificationService.ClearMessages();// Sanitize username- var username = LoginModel.Username.ToLowerInvariant().Trim();+ var username = _loginModel.Username.ToLowerInvariant().Trim();// Send request to server with username to get server ephemeral public key.var result = await Http.PostAsJsonAsync("api/v1/Auth/login", new LoginInitiateRequest(username));@@ -225,20 +225,20 @@ else}// 3. Client derives shared session key.- PasswordHash = await Encryption.DeriveKeyFromPasswordAsync(LoginModel.Password, loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);- var passwordHashString = BitConverter.ToString(PasswordHash).Replace("-", string.Empty);+ _passwordHash = await Encryption.DeriveKeyFromPasswordAsync(_loginModel.Password, loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);+ var passwordHashString = BitConverter.ToString(_passwordHash).Replace("-", string.Empty);- ClientEphemeral = Srp.GenerateEphemeralClient();+ _clientEphemeral = Srp.GenerateEphemeralClient();var privateKey = Srp.DerivePrivateKey(loginResponse.Salt, username, passwordHashString);- ClientSession = Srp.DeriveSessionClient(+ _clientSession = Srp.DeriveSessionClient(privateKey,- ClientEphemeral.Secret,+ _clientEphemeral.Secret,loginResponse.ServerEphemeral,loginResponse.Salt,username);// 4. Client sends proof of session key to server.- result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, LoginModel.RememberMe, ClientEphemeral.Public, ClientSession.Proof));+ result = await Http.PostAsJsonAsync("api/v1/Auth/validate", new ValidateLoginRequest(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof));responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode)@@ -271,23 +271,23 @@ else/// </summary>private async Task HandleRecoveryCode(){- LoadingIndicator.Show();- ServerValidationErrors.Clear();+ _loadingIndicator.Show();+ _serverValidationErrors.Clear();try{// Sanitize username- var username = LoginModel.Username.ToLowerInvariant().Trim();+ var username = _loginModel.Username.ToLowerInvariant().Trim();// Validate 2-factor auth code auth and login- var result = await Http.PostAsJsonAsync("api/v1/Auth/validate-recovery-code", new ValidateLoginRequestRecoveryCode(username, LoginModel.RememberMe, ClientEphemeral.Public, ClientSession.Proof, LoginModelRecoveryCode.RecoveryCode));+ var result = await Http.PostAsJsonAsync("api/v1/Auth/validate-recovery-code", new ValidateLoginRequestRecoveryCode(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModelRecoveryCode.RecoveryCode));var responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode){foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent)){- ServerValidationErrors.AddError(error);+ _serverValidationErrors.AddError(error);}return;}@@ -295,21 +295,21 @@ elsevar validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);if (validateLoginResponse == null){- ServerValidationErrors.AddError("An error occurred while processing the login request.");+ _serverValidationErrors.AddError("An error occurred while processing the login request.");return;}var errors = await ProcessLoginVerify(validateLoginResponse);foreach (var error in errors){- ServerValidationErrors.AddError(error);+ _serverValidationErrors.AddError(error);}}#if DEBUGcatch (Exception ex){// If in debug mode show the actual exception.- ServerValidationErrors.AddError(ex.ToString());+ _serverValidationErrors.AddError(ex.ToString());}#elsecatch@@ -320,7 +320,7 @@ else#endiffinally{- LoadingIndicator.Hide();+ _loadingIndicator.Hide();}}@@ -329,23 +329,23 @@ else/// </summary>private async Task Handle2Fa(){- LoadingIndicator.Show();- ServerValidationErrors.Clear();+ _loadingIndicator.Show();+ _serverValidationErrors.Clear();try{// Sanitize username- var username = LoginModel.Username.ToLowerInvariant().Trim();+ var username = _loginModel.Username.ToLowerInvariant().Trim();// Validate 2-factor auth code auth and login- var result = await Http.PostAsJsonAsync("api/v1/Auth/validate-2fa", new ValidateLoginRequest2Fa(username, LoginModel.RememberMe, ClientEphemeral.Public, ClientSession.Proof, LoginModel2Fa.TwoFactorCode ?? 0));+ var result = await Http.PostAsJsonAsync("api/v1/Auth/validate-2fa", new ValidateLoginRequest2Fa(username, _loginModel.RememberMe, _clientEphemeral.Public, _clientSession.Proof, _loginModel2Fa.TwoFactorCode ?? 0));var responseContent = await result.Content.ReadAsStringAsync();if (!result.IsSuccessStatusCode){foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent)){- ServerValidationErrors.AddError(error);+ _serverValidationErrors.AddError(error);}return;}@@ -353,21 +353,21 @@ elsevar validateLoginResponse = JsonSerializer.Deserialize<ValidateLoginResponse>(responseContent);if (validateLoginResponse == null){- ServerValidationErrors.AddError("An error occurred while processing the login request.");+ _serverValidationErrors.AddError("An error occurred while processing the login request.");return;}var errors = await ProcessLoginVerify(validateLoginResponse);foreach (var error in errors){- ServerValidationErrors.AddError(error);+ _serverValidationErrors.AddError(error);}}#if DEBUGcatch (Exception ex){// If in debug mode show the actual exception.- ServerValidationErrors.AddError(ex.ToString());+ _serverValidationErrors.AddError(ex.ToString());}#elsecatch@@ -378,7 +378,7 @@ else#endiffinally{- LoadingIndicator.Hide();+ _loadingIndicator.Hide();}}@@ -388,14 +388,14 @@ elseprivate async Task<List<string>> ProcessLoginVerify(ValidateLoginResponse validateLoginResponse){// 5. Client verifies proof.- Srp.VerifySession(ClientEphemeral.Public, ClientSession, validateLoginResponse.ServerSessionProof);+ Srp.VerifySession(_clientEphemeral.Public, _clientSession, validateLoginResponse.ServerSessionProof);// Store the tokens in local storage.await AuthService.StoreAccessTokenAsync(validateLoginResponse.Token!.Token);await AuthService.StoreRefreshTokenAsync(validateLoginResponse.Token!.RefreshToken);// Store the encryption key in memory.- await AuthService.StoreEncryptionKeyAsync(PasswordHash);+ await AuthService.StoreEncryptionKeyAsync(_passwordHash);await AuthStateProvider.GetAuthenticationStateAsync();GlobalNotificationService.ClearMessages();diff --git a/src/AliasVault.Client/Auth/Pages/Register.razor b/src/AliasVault.Client/Auth/Pages/Register.razorindex 251034c67..4033dda18 100644--- a/src/AliasVault.Client/Auth/Pages/Register.razor+++ b/src/AliasVault.Client/Auth/Pages/Register.razor@@ -1,50 +1,42 @@@page "/user/register"+@inherits AliasVault.Client.Auth.Pages.Base.LoginBase@attribute [AllowAnonymous]@layout Auth.Layout.MainLayout-@inject HttpClient Http-@inject AuthenticationStateProvider AuthStateProvider-@inject NavigationManager NavigationManager-@inject AuthService AuthService-@inject IConfiguration Configuration-@using System.Text.Json@using AliasVault.Shared.Models.WebApi.Auth@using AliasVault.Client.Auth.Components-@using AliasVault.Client.Utilities-@using AliasVault.Cryptography.Client-@using SecureRemotePassword<h2 class="text-2xl font-bold text-gray-900 dark:text-white">Create a new AliasVault account</h2>-<FullScreenLoadingIndicator @ref="LoadingIndicator" />-<ServerValidationErrors @ref="ServerValidationErrors" />+<FullScreenLoadingIndicator @ref="_loadingIndicator" />+<ServerValidationErrors @ref="_serverValidationErrors" />-<EditForm Model="RegisterModel" OnValidSubmit="HandleRegister" class="mt-8 space-y-6">+<EditForm Model="_registerModel" OnValidSubmit="HandleRegister" class="mt-8 space-y-6"><DataAnnotationsValidator/><div><label asp-for="Input.Email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your username or email</label>- <InputTextField id="email" @bind-Value="RegisterModel.Username" placeholder="name / [email protected]" />- <ValidationMessage For="() => RegisterModel.Username"/>+ <InputTextField id="email" @bind-Value="_registerModel.Username" placeholder="name / [email protected]" />+ <ValidationMessage For="() => _registerModel.Username"/></div><div><label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Your password</label>- <InputTextField id="password" @bind-Value="RegisterModel.Password" type="password" placeholder="••••••••" />- <ValidationMessage For="() => RegisterModel.Password"/>+ <InputTextField id="password" @bind-Value="_registerModel.Password" type="password" placeholder="••••••••" />+ <ValidationMessage For="() => _registerModel.Password"/></div><div><label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Confirm password</label>- <InputTextField id="password2" @bind-Value="RegisterModel.PasswordConfirm" type="password" placeholder="••••••••" />- <ValidationMessage For="() => RegisterModel.PasswordConfirm"/>+ <InputTextField id="password2" @bind-Value="_registerModel.PasswordConfirm" type="password" placeholder="••••••••" />+ <ValidationMessage For="() => _registerModel.PasswordConfirm"/></div><div class="flex items-start"><div class="flex items-center h-5">- <InputCheckbox id="terms" @bind-Value="RegisterModel.AcceptTerms" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" />+ <InputCheckbox id="terms" @bind-Value="_registerModel.AcceptTerms" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" /></div><div class="ml-3 text-sm"><label for="terms" class="font-medium text-gray-900 dark:text-white">I accept the <a href="https://github.com/lanedirt/AliasVault/blob/main/LICENSE.md" target="_blank" class="text-primary-700 hover:underline dark:text-primary-500">Terms and Conditions</a></label>- <ValidationMessage For="() => RegisterModel.AcceptTerms"/>+ <ValidationMessage For="() => _registerModel.AcceptTerms"/></div></div>@@ -55,73 +47,27 @@</EditForm>@code {- private readonly RegisterModel RegisterModel = new();- private FullScreenLoadingIndicator LoadingIndicator = new();- private ServerValidationErrors ServerValidationErrors = new();+ private readonly RegisterModel _registerModel = new();+ private FullScreenLoadingIndicator _loadingIndicator = new();+ private ServerValidationErrors _serverValidationErrors = new();- async Task HandleRegister()+ private async Task HandleRegister(){- LoadingIndicator.Show();- ServerValidationErrors.Clear();+ _loadingIndicator.Show();+ _serverValidationErrors.Clear();- try- {- var client = new SrpClient();- var salt = client.GenerateSalt();-- byte[] passwordHash;- string encryptionType = Defaults.EncryptionType;- string encryptionSettings = Defaults.EncryptionSettings;- if (Configuration["CryptographyOverrideType"] is not null && Configuration["CryptographyOverrideSettings"] is not null) {- // If cryptography type and settings override are present in appsettings.json, use them instead of defaults- // declared in code. This is used in certain cases e.g. E2E tests to speed up the process.- encryptionType = Configuration["CryptographyOverrideType"]!;- encryptionSettings = Configuration["CryptographyOverrideSettings"]!;- }-- passwordHash = await Encryption.DeriveKeyFromPasswordAsync(RegisterModel.Password, salt, encryptionType, encryptionSettings);- var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);- var srpSignup = Srp.PasswordChangeAsync(client, salt, RegisterModel.Username, passwordHashString);-- var registerRequest = new RegisterRequest(srpSignup.Username, srpSignup.Salt, srpSignup.Verifier, encryptionType, encryptionSettings);- var result = await Http.PostAsJsonAsync("api/v1/Auth/register", registerRequest);- var responseContent = await result.Content.ReadAsStringAsync();-- if (!result.IsSuccessStatusCode)- {- foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent))- {- ServerValidationErrors.AddError(error);- }- StateHasChanged();- return;- }-- var tokenObject = JsonSerializer.Deserialize<TokenModel>(responseContent);-- if (tokenObject != null)- {- // Store the encryption key in memory.- await AuthService.StoreEncryptionKeyAsync(passwordHash);-- // Store the token as a plain string in local storage- await AuthService.StoreAccessTokenAsync(tokenObject.Token);- await AuthService.StoreRefreshTokenAsync(tokenObject.RefreshToken);- await AuthStateProvider.GetAuthenticationStateAsync();- }- else- {- // Handle the case where the token is not present in the response- ServerValidationErrors.AddError("An error occured during registration.");- StateHasChanged();- return;- }+ var (success, errorMessage) = await UserRegistrationService.RegisterUserAsync(_registerModel.Username, _registerModel.Password);+ if (success)+ {NavigationManager.NavigateTo("/");}- finally+ else{- LoadingIndicator.Hide();+ _serverValidationErrors.AddError(errorMessage ?? "An error occurred during registration.");+ StateHasChanged();}++ _loadingIndicator.Hide();}}diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Components/CreatingStep.razor b/src/AliasVault.Client/Auth/Pages/Setup/Components/CreatingStep.razorindex 37623d9b3..c09cd1562 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Components/CreatingStep.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Components/CreatingStep.razor@@ -21,8 +21,6 @@</div>@code {- private bool IsLoading { get; set; } = true;-/// <summary>/// The username to use for the new account./// </summary>@@ -35,6 +33,8 @@[Parameter]public string Password { get; set; } = string.Empty;+ private bool IsLoading { get; set; } = true;+/// <inheritdoc />protected override async Task OnAfterRenderAsync(bool firstRender){@@ -49,64 +49,16 @@{StateHasChanged();- try- {- var client = new SrpClient();- var salt = client.GenerateSalt();-- string encryptionType = Defaults.EncryptionType;- string encryptionSettings = Defaults.EncryptionSettings;- if (Configuration["CryptographyOverrideType"] is not null && Configuration["CryptographyOverrideSettings"] is not null)- {- encryptionType = Configuration["CryptographyOverrideType"]!;- encryptionSettings = Configuration["CryptographyOverrideSettings"]!;- }-- var passwordHash = await Encryption.DeriveKeyFromPasswordAsync(Password, salt, encryptionType, encryptionSettings);- var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);- var srpSignup = Srp.PasswordChangeAsync(client, salt, Username, passwordHashString);+ var (success, errorMessage) = await UserRegistrationService.RegisterUserAsync(Username, Password);- var registerRequest = new RegisterRequest(srpSignup.Username, srpSignup.Salt, srpSignup.Verifier, encryptionType, encryptionSettings);- var result = await Http.PostAsJsonAsync("api/v1/Auth/register", registerRequest);- var responseContent = await result.Content.ReadAsStringAsync();-- if (!result.IsSuccessStatusCode)- {- foreach (var error in ApiResponseUtility.ParseErrorResponse(responseContent))- {- GlobalNotificationService.AddErrorMessage(error, true);- }- IsLoading = false;- StateHasChanged();- return;- }-- var tokenObject = JsonSerializer.Deserialize<TokenModel>(responseContent);-- if (tokenObject != null)- {- await AuthService.StoreEncryptionKeyAsync(passwordHash);- await AuthService.StoreAccessTokenAsync(tokenObject.Token);- await AuthService.StoreRefreshTokenAsync(tokenObject.RefreshToken);- await AuthStateProvider.GetAuthenticationStateAsync();-- NavigationManager.NavigateTo("/");- }- else- {- IsLoading = false;- GlobalNotificationService.AddErrorMessage("An error occurred during registration.", true);- StateHasChanged();- }- }- catch (Exception ex)+ if (success){- GlobalNotificationService.AddErrorMessage($"An error occurred: {ex.Message}", true);+ NavigationManager.NavigateTo("/");}- finally+ else{IsLoading = false;-+ GlobalNotificationService.AddErrorMessage(errorMessage ?? "An error occurred during registration.", true);StateHasChanged();}}diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Components/PasswordStep.razor b/src/AliasVault.Client/Auth/Pages/Setup/Components/PasswordStep.razorindex 594e3f1b6..708c0faae 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Components/PasswordStep.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Components/PasswordStep.razor@@ -1,16 +1,15 @@-@using System.Timers-@using System.Net.Http.Json+@inherits AliasVault.Client.Auth.Pages.Base.LoginBase@implements IDisposable-@inject JsInteropService JsInteropService+@using System.Timers-<div class="w-full max-w-md mx-auto">- @if (isLoading)+<div class="w-full mx-auto">+ @if (_isLoading){<div class="absolute inset-0 flex justify-center items-center z-10"><div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary-500"></div></div>}- <div class="@(isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full">+ <div class="@(_isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full"><div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg lg:shadow-none p-6"><div class="flex items-start mb-4"><div class="flex-shrink-0">@@ -43,24 +42,24 @@<div class="mt-4"><EditFormRow Id="confirmPassword" Label="Confirm Master Password" @bind-Value="ConfirmPassword" Type="password" Placeholder="Confirm your master password" OnFocus="@OnPasswordInputFocus" /></div>- @if (isValidating)+ @if (_isValidating){<div class="mt-2 text-sm text-gray-600 dark:text-gray-400">Validating password...</div>}- else if (isValid)+ else if (_isValid){- @if (!string.IsNullOrEmpty(errorMessage))+ @if (!string.IsNullOrEmpty(_errorMessage)){- <div class="mt-2 text-sm text-yellow-600 dark:text-yellow-400">@errorMessage</div>+ <div class="mt-2 text-sm text-yellow-600 dark:text-yellow-400">@_errorMessage</div>}else{<div class="mt-2 text-sm text-green-600 dark:text-green-400">Password is valid and strong!</div>}}- else if (!string.IsNullOrEmpty(errorMessage))+ else if (!string.IsNullOrEmpty(_errorMessage)){- <div class="mt-2 text-sm text-red-600 dark:text-red-400">@errorMessage</div>+ <div class="mt-2 text-sm text-red-600 dark:text-red-400">@_errorMessage</div>}</div></div>@@ -68,20 +67,13 @@</div>@code {- private string _password = string.Empty;- private string _confirmPassword = string.Empty;- private bool isValid = false;- private bool isValidating = false;- private string errorMessage = string.Empty;- private Timer? debounceTimer;-- [Inject]- private HttpClient Http { get; set; } = null!;-+ /// <summary>+ /// The event callback for when the password changes.+ /// </summary>[Parameter]- public string Username { get; set; } = string.Empty;+ public EventCallback<string> OnPasswordChange { get; set; }- public string Password+ private string Password{get => _password;set@@ -94,7 +86,7 @@}}- public string ConfirmPassword+ private string ConfirmPassword{get => _confirmPassword;set@@ -107,24 +99,37 @@}}- [Parameter]- public EventCallback<string> OnPasswordChange { get; set; }+ private string _password = string.Empty;+ private string _confirmPassword = string.Empty;+ private bool _isValid = false;+ private bool _isValidating = false;+ private string _errorMessage = string.Empty;+ private Timer? _debounceTimer;++ private bool _isLoading = true;+ private Timer? _loadingTimer;- private bool isLoading = true;- private Timer? loadingTimer;+ /// <inheritdoc />+ public void Dispose()+ {+ _loadingTimer?.Dispose();+ _debounceTimer?.Dispose();+ }+ /// <inheritdoc />protected override void OnInitialized(){- loadingTimer = new Timer(300);- loadingTimer.Elapsed += (sender, e) => FinishLoading();- loadingTimer.AutoReset = false;- loadingTimer.Start();-- debounceTimer = new Timer(300);- debounceTimer.Elapsed += async (sender, e) => await ValidatePasswordDebounced();- debounceTimer.AutoReset = false;+ _loadingTimer = new Timer(300);+ _loadingTimer.Elapsed += (sender, e) => FinishLoading();+ _loadingTimer.AutoReset = false;+ _loadingTimer.Start();++ _debounceTimer = new Timer(300);+ _debounceTimer.Elapsed += async (sender, e) => await ValidatePasswordDebounced();+ _debounceTimer.AutoReset = false;}+ /// <inheritdoc />protected override async Task OnAfterRenderAsync(bool firstRender){await base.OnAfterRenderAsync(firstRender);@@ -135,32 +140,41 @@}}+ /// <summary>+ /// Finishes the loading animation.+ /// </summary>private void FinishLoading(){- isLoading = false;+ _isLoading = false;InvokeAsync(StateHasChanged);}+ /// <summary>+ /// Validates the password immediately.+ /// </summary>private void ValidatePassword(){- isValidating = true;- isValid = false;- errorMessage = string.Empty;+ _isValidating = true;+ _isValid = false;+ _errorMessage = string.Empty;StateHasChanged();- debounceTimer?.Stop();- debounceTimer?.Start();+ _debounceTimer?.Stop();+ _debounceTimer?.Start();}+ /// <summary>+ /// Validates the password after input has stopped.+ /// </summary>private async Task ValidatePasswordDebounced(){await InvokeAsync(async () =>{if (Password.Length < 10){- isValidating = false;- isValid = false;- errorMessage = "Master password must be at least 10 characters long.";+ _isValidating = false;+ _isValid = false;+ _errorMessage = "Master password must be at least 10 characters long.";await OnPasswordChange.InvokeAsync(string.Empty);StateHasChanged();return;@@ -168,9 +182,9 @@if (string.IsNullOrWhiteSpace(ConfirmPassword)){- isValidating = false;- isValid = false;- errorMessage = "Confirm your password by entering it again.";+ _isValidating = false;+ _isValid = false;+ _errorMessage = "Confirm your password by entering it again.";await OnPasswordChange.InvokeAsync(string.Empty);StateHasChanged();return;@@ -178,43 +192,40 @@if (Password != ConfirmPassword){- isValidating = false;- isValid = false;- errorMessage = "Passwords do not match.";+ _isValidating = false;+ _isValid = false;+ _errorMessage = "Passwords do not match.";await OnPasswordChange.InvokeAsync(string.Empty);StateHasChanged();return;}- // If password is valid- isValid = true;- errorMessage = string.Empty;+ // If password is valid.+ _isValid = true;+ _errorMessage = string.Empty;- // Show warning for passwords between 10 and 13 characters+ // Show warning for passwords between 10 and 13 characters.if (Password.Length < 14){- errorMessage = "Password is valid, but could be stronger if made longer.";+ _errorMessage = "Password is valid, but could be stronger if made longer.";}await OnPasswordChange.InvokeAsync(Password);- isValidating = false;+ _isValidating = false;StateHasChanged();});}+ /// <summary>+ /// Handles the password input focus.+ /// </summary>private void OnPasswordInputFocus(FocusEventArgs args){- // Reset validation state when the input is focused- isValid = false;- isValidating = false;- errorMessage = string.Empty;+ // Reset validation state when the input is focused.+ _isValid = false;+ _isValidating = false;+ _errorMessage = string.Empty;StateHasChanged();}-- public void Dispose()- {- loadingTimer?.Dispose();- debounceTimer?.Dispose();- }}diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Components/TermsAndConditionsStep.razor b/src/AliasVault.Client/Auth/Pages/Setup/Components/TermsAndConditionsStep.razorindex 23ab06e35..78347e277 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Components/TermsAndConditionsStep.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Components/TermsAndConditionsStep.razor@@ -1,13 +1,14 @@+@implements IDisposable@using System.Timers-<div class="w-full max-w-md mx-auto">- @if (isLoading)+<div class="w-full mx-auto">+ @if (_isLoading){<div class="absolute inset-0 flex justify-center items-center z-10"><div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary-500"></div></div>}- <div class="@(isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full">+ <div class="@(_isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full"><div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg lg:shadow-none p-6"><p class="text-sm text-gray-600 dark:text-gray-400 mb-4">Please read and agree to the following terms and conditions before proceeding.@@ -45,31 +46,42 @@[Parameter]public bool AgreedToTerms { get; set; }+ /// <summary>+ /// The event callback for when the user has agreed to the terms and conditions.+ /// </summary>[Parameter]public EventCallback<bool> OnAgreedToTermsChanged { get; set; }- private bool isLoading = true;- private Timer? loadingTimer;+ private bool _isLoading = true;+ private Timer? _loadingTimer;- protected override void OnInitialized()+ /// <inheritdoc />+ public void Dispose(){- loadingTimer = new Timer(300);- loadingTimer.Elapsed += (sender, e) => FinishLoading();- loadingTimer.AutoReset = false;- loadingTimer.Start();+ _loadingTimer?.Dispose();}- private void FinishLoading()+ /// <inheritdoc />+ protected override void OnInitialized(){- isLoading = false;- InvokeAsync(StateHasChanged);+ _loadingTimer = new Timer(300);+ _loadingTimer.Elapsed += (sender, e) => FinishLoading();+ _loadingTimer.AutoReset = false;+ _loadingTimer.Start();}- public void Dispose()+ /// <summary>+ /// Finishes the loading animation.+ /// </summary>+ private void FinishLoading(){- loadingTimer?.Dispose();+ _isLoading = false;+ InvokeAsync(StateHasChanged);}+ /// <summary>+ /// Handles the user agreeing to the terms and conditions.+ /// </summary>private async Task OnAgreedToTerms(){await OnAgreedToTermsChanged.InvokeAsync(AgreedToTerms);diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Components/UsernameStep.razor b/src/AliasVault.Client/Auth/Pages/Setup/Components/UsernameStep.razorindex d28401d09..eb18fa467 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Components/UsernameStep.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Components/UsernameStep.razor@@ -1,16 +1,15 @@-@using System.Timers-@using System.Net.Http.Json+@inherits AliasVault.Client.Auth.Pages.Base.LoginBase@implements IDisposable-@inject JsInteropService JsInteropService+@using System.Timers-<div class="w-full max-w-md mx-auto">- @if (isLoading)+<div class="w-full mx-auto">+ @if (_isLoading){<div class="absolute inset-0 flex justify-center items-center z-10"><div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary-500"></div></div>}- <div class="@(isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full">+ <div class="@(_isLoading ? "invisible opacity-0" : "opacity-100") transition-opacity duration-300 w-full"><div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg lg:shadow-none p-6 mb-6"><div class="flex items-start mb-4"><div class="flex-shrink-0">@@ -51,15 +50,6 @@</div>@code {- private string _username = string.Empty;- private bool _isValid = false;- private bool _isValidating = false;- private string _errorMessage = string.Empty;- private Timer? _debounceTimer;-- [Inject]- private HttpClient Http { get; set; } = null!;-/// <summary>/// The username that is previously entered by the user. When a user navigates with back/continue/// and entered a username already, the existing username might be provided by the parent component.@@ -67,10 +57,22 @@[Parameter]public string DefaultUsername { get; set; } = string.Empty;+ /// <summary>+ /// The event callback for when the username changes.+ /// </summary>+ [Parameter]+ public EventCallback<string> OnUsernameChange { get; set; }++ private string _username = string.Empty;+ private bool _isValid = false;+ private bool _isValidating = false;+ private string _errorMessage = string.Empty;+ private Timer? _debounceTimer;+/// <summary>/// The username that is entered by the user. This is the value that will be validated and sent to the parent component./// </summary>- public string Username+ private string Username{get => _username;set@@ -83,12 +85,17 @@}}- [Parameter]- public EventCallback<string> OnUsernameChange { get; set; }+ private bool _isLoading = true;+ private Timer? _loadingTimer;- private bool isLoading = true;- private Timer? loadingTimer;+ /// <inheritdoc />+ public void Dispose()+ {+ _loadingTimer?.Dispose();+ _debounceTimer?.Dispose();+ }+ /// <inheritdoc />protected override async Task OnInitializedAsync(){// Set the default username if provided.@@ -99,16 +106,17 @@await ValidateUsernameDebounced();}- loadingTimer = new Timer(300);- loadingTimer.Elapsed += (sender, e) => FinishLoading();- loadingTimer.AutoReset = false;- loadingTimer.Start();+ _loadingTimer = new Timer(300);+ _loadingTimer.Elapsed += (sender, e) => FinishLoading();+ _loadingTimer.AutoReset = false;+ _loadingTimer.Start();_debounceTimer = new Timer(300);_debounceTimer.Elapsed += async (sender, e) => await ValidateUsernameDebounced();_debounceTimer.AutoReset = false;}+ /// <inheritdoc />protected override async Task OnAfterRenderAsync(bool firstRender){await base.OnAfterRenderAsync(firstRender);@@ -119,12 +127,18 @@}}+ /// <summary>+ /// Finishes the loading animation.+ /// </summary>private void FinishLoading(){- isLoading = false;+ _isLoading = false;InvokeAsync(StateHasChanged);}+ /// <summary>+ /// Validates the username immediately.+ /// </summary>private void ValidateUsername(){_isValidating = true;@@ -136,6 +150,9 @@_debounceTimer?.Start();}+ /// <summary>+ /// Validates the username after input has stopped.+ /// </summary>private async Task ValidateUsernameDebounced(){await InvokeAsync(async () =>@@ -182,6 +199,9 @@});}+ /// <summary>+ /// Handles the username input focus.+ /// </summary>private void OnUsernameInputFocus(FocusEventArgs args){// Reset validation state when the input is focused@@ -190,10 +210,4 @@_errorMessage = string.Empty;StateHasChanged();}-- public void Dispose()- {- loadingTimer?.Dispose();- _debounceTimer?.Dispose();- }}diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Components/WelcomeStep.razor b/src/AliasVault.Client/Auth/Pages/Setup/Components/WelcomeStep.razorindex dd2b662ed..cbb291726 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Components/WelcomeStep.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Components/WelcomeStep.razor@@ -1,5 +1,5 @@<div class="w-full max-w-md mx-auto">- <p class="mt-16 text-gray-600 dark:text-gray-400 mb-8 text-center">+ <p class="mt-12 text-gray-600 dark:text-gray-400 mb-4 text-center">AliasVault is a secure app which help you manage your online identities and passwords.Let's get you set up with your new vault.</p>diff --git a/src/AliasVault.Client/Auth/Pages/Setup/Setup.razor b/src/AliasVault.Client/Auth/Pages/Setup/Setup.razorindex 6cc2a2bf9..eadbefd6a 100644--- a/src/AliasVault.Client/Auth/Pages/Setup/Setup.razor+++ b/src/AliasVault.Client/Auth/Pages/Setup/Setup.razor@@ -48,9 +48,7 @@OnUsernameChange="@((string username) => { setupData.Username = username; StateHasChanged(); })" />break;case SetupStep.Password:- <PasswordStep- Username="@setupData.Username"- OnPasswordChange="@((string pwd) => { setupData.Password = pwd; StateHasChanged(); })" />+ <PasswordStep OnPasswordChange="@((string pwd) => { setupData.Password = pwd; StateHasChanged(); })" />break;case SetupStep.Creating:<CreatingStep Username="@setupData.Username" Password="@setupData.Password" />diff --git a/src/AliasVault.Client/Auth/Pages/Start.razor b/src/AliasVault.Client/Auth/Pages/Start.razorindex 6faa07e1d..0f587682a 100644--- a/src/AliasVault.Client/Auth/Pages/Start.razor+++ b/src/AliasVault.Client/Auth/Pages/Start.razor@@ -6,15 +6,12 @@<div class="flex lg:min-h-screen bg-gray-50 dark:bg-gray-900"><div class="w-full max-w-7xl mx-auto flex flex-col lg:flex-row">- <!-- Left column with image placeholder --><div class="hidden lg:flex lg:w-1/2 items-center justify-center p-8"><div class="text-white text-4xl font-bold">- <!-- Replace this with an actual image --><img src="img/icon-500.png" alt="AliasVault" class="w-64 h-64" /></div></div>- <!-- Right column with text and buttons --><div class="w-full lg:w-1/2 flex items-center justify-center px-8 py-12"><div class="w-full max-w-xl p-6 space-y-4 sm:p-8"><Logo />@@ -25,12 +22,12 @@Your Privacy. Protected.</p><div class="space-y-4">- <button @onclick="NavigateToCreateAccount" class="w-full py-3 px-4 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out">+ <a href="/user/setup" class="block w-full py-3 px-4 bg-primary-600 hover:bg-primary-700 text-white font-semibold rounded-lg transition duration-300 ease-in-out text-center">Create new vault- </button>- <button @onclick="NavigateToLogin" class="w-full py-3 px-4 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-800 text-gray-800 dark:text-white font-semibold rounded-lg transition duration-300 ease-in-out">+ </a>+ <a href="/user/login" class="block w-full py-3 px-4 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-800 text-gray-800 dark:text-white font-semibold rounded-lg transition duration-300 ease-in-out text-center">Log in with existing account- </button>+ </a></div></div></div>@@ -50,14 +47,4 @@NavigationManager.NavigateTo("/");}}-- private void NavigateToLogin()- {- NavigationManager.NavigateTo("/user/login");- }-- private void NavigateToCreateAccount()- {- NavigationManager.NavigateTo("/user/setup");- }}diff --git a/src/AliasVault.Client/Program.cs b/src/AliasVault.Client/Program.csindex 544bf827c..ab8c4402c 100644--- a/src/AliasVault.Client/Program.cs+++ b/src/AliasVault.Client/Program.cs@@ -64,6 +64,7 @@ builder.Services.AddScoped(sp =>});builder.Services.AddTransient<AliasVaultApiHandlerService>();builder.Services.AddScoped<AuthService>();+builder.Services.AddScoped<UserRegistrationService>();builder.Services.AddScoped<AuthenticationStateProvider, AuthStateProvider>();builder.Services.AddScoped<CredentialService>();builder.Services.AddScoped<DbService>();diff --git a/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs b/src/AliasVault.Client/Services/Auth/UserRegistrationService.csnew file mode 100644index 000000000..9cc1d9aa4--- /dev/null+++ b/src/AliasVault.Client/Services/Auth/UserRegistrationService.cs@@ -0,0 +1,101 @@+//-----------------------------------------------------------------------+// <copyright file="UserRegistrationService.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.Client.Services.Auth;++using System.Net.Http.Json;+using System.Text.Json;+using AliasVault.Client.Utilities;+using AliasVault.Cryptography.Client;+using AliasVault.Shared.Models.WebApi.Auth;+using Microsoft.AspNetCore.Components.Authorization;+using SecureRemotePassword;++/// <summary>+/// This service is responsible for registering a new user.+/// </summary>+public class UserRegistrationService+{+ private readonly HttpClient _httpClient;+ private readonly AuthenticationStateProvider _authStateProvider;+ private readonly AuthService _authService;+ private readonly IConfiguration _configuration;++ /// <summary>+ /// Initializes a new instance of the <see cref="UserRegistrationService"/> class.+ /// </summary>+ /// <param name="httpClient">The HTTP client.</param>+ /// <param name="authStateProvider">The authentication state provider.</param>+ /// <param name="authService">The authentication service.</param>+ /// <param name="configuration">The configuration.</param>+ public UserRegistrationService(+ HttpClient httpClient,+ AuthenticationStateProvider authStateProvider,+ AuthService authService,+ IConfiguration configuration)+ {+ _httpClient = httpClient;+ _authStateProvider = authStateProvider;+ _authService = authService;+ _configuration = configuration;+ }++ /// <summary>+ /// Registers a new user asynchronously.+ /// </summary>+ /// <param name="username">The username.</param>+ /// <param name="password">The password.</param>+ /// <returns>A tuple indicating the success status and any error message.</returns>+ public async Task<(bool Success, string? ErrorMessage)> RegisterUserAsync(string username, string password)+ {+ try+ {+ var client = new SrpClient();+ var salt = client.GenerateSalt();++ string encryptionType = Defaults.EncryptionType;+ string encryptionSettings = Defaults.EncryptionSettings;+ if (_configuration["CryptographyOverrideType"] is not null && _configuration["CryptographyOverrideSettings"] is not null)+ {+ encryptionType = _configuration["CryptographyOverrideType"]!;+ encryptionSettings = _configuration["CryptographyOverrideSettings"]!;+ }++ var passwordHash = await Encryption.DeriveKeyFromPasswordAsync(password, salt, encryptionType, encryptionSettings);+ var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);+ var srpSignup = Srp.PasswordChangeAsync(client, salt, username, passwordHashString);++ var registerRequest = new RegisterRequest(srpSignup.Username, srpSignup.Salt, srpSignup.Verifier, encryptionType, encryptionSettings);+ var result = await _httpClient.PostAsJsonAsync("api/v1/Auth/register", registerRequest);+ var responseContent = await result.Content.ReadAsStringAsync();++ if (!result.IsSuccessStatusCode)+ {+ var errors = ApiResponseUtility.ParseErrorResponse(responseContent);+ return (false, string.Join(", ", errors));+ }++ var tokenObject = JsonSerializer.Deserialize<TokenModel>(responseContent);++ if (tokenObject == null)+ {+ return (false, "An error occurred during registration.");+ }++ await _authService.StoreEncryptionKeyAsync(passwordHash);+ await _authService.StoreAccessTokenAsync(tokenObject.Token);+ await _authService.StoreRefreshTokenAsync(tokenObject.RefreshToken);+ await _authStateProvider.GetAuthenticationStateAsync();++ return (true, null);+ }+ catch (Exception ex)+ {+ return (false, $"An error occurred: {ex.Message}");+ }+ }+}diff --git a/src/AliasVault.Client/wwwroot/css/tailwind.css b/src/AliasVault.Client/wwwroot/css/tailwind.cssindex ab332048d..747b5cf2a 100644--- a/src/AliasVault.Client/wwwroot/css/tailwind.css+++ b/src/AliasVault.Client/wwwroot/css/tailwind.css@@ -857,6 +857,10 @@ video {margin-top: 2.5rem;}+.mt-12 {+ margin-top: 3rem;+}+.line-clamp-2 {overflow: hidden;display: -webkit-box;