Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Refactor (#181)

Leendert de Borst2cbf234d05e0
diff --git a/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor
index 36dd69695..48abdd6e5 100644
--- a/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor
+++ b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor
@@ -4,7 +4,6 @@
@inject ConfirmModalService ConfirmModalService
@using AliasVault.RazorComponents.Services
@using TotpGenerator
-@implements IDisposable
<div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
<div class="flex justify-between">
@@ -14,18 +13,14 @@
@if (TotpCodeList.Where(t => !t.IsDeleted).Any() && !IsAddFormVisible)
{
<div>
- <button @onclick="ShowAddForm" type="button" class="text-blue-700 hover:text-white border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-2 text-center dark:border-blue-500 dark:text-blue-500 dark:hover:text-white dark:hover:bg-blue-600 dark:focus:ring-blue-800">
+ <button id="add-totp-code" @onclick="ShowAddForm" type="button" class="text-blue-700 hover:text-white border border-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-3 py-2 text-center dark:border-blue-500 dark:text-blue-500 dark:hover:text-white dark:hover:bg-blue-600 dark:focus:ring-blue-800">
Add TOTP Code
</button>
</div>
}
</div>
- @if (IsLoading)
- {
- <LoadingIndicator />
- }
- else if ((TotpCodeList.Count == 0 || TotpCodeList.All(t => t.IsDeleted)) && !IsAddFormVisible)
+ @if ((TotpCodeList.Count == 0 || TotpCodeList.All(t => t.IsDeleted)) && !IsAddFormVisible)
{
<div class="flex flex-col justify-center">
<p class="text-gray-500 dark:text-gray-400"><a @onclick="ShowAddForm" href="javascript:void(0)" class="text-blue-600 hover:text-blue-800 dark:text-blue-500 dark:hover:text-blue-400">Add a two-factor authenticator code</a></p>
@@ -77,23 +72,9 @@
</div>
<div class="flex items-center gap-4">
<div class="flex flex-col items-end">
- @if (OriginalTotpCodeIds.Contains(totpCode.Id))
- {
- <div class="text-2xl font-bold text-gray-900 dark:text-white">@GetTotpCode(totpCode.SecretKey)</div>
- <div class="text-xs text-gray-500 dark:text-gray-400">@GetRemainingSeconds()s</div>
- }
- else
- {
- <div class="text-sm text-gray-500 dark:text-gray-400">Save to view code</div>
- }
+ <div class="text-sm text-gray-500 dark:text-gray-400">Save to view code</div>
</div>
- <div class="w-1.5 h-8 bg-gray-200 rounded-full dark:bg-gray-600">
- @if (OriginalTotpCodeIds.Contains(totpCode.Id))
- {
- <div class="bg-blue-600 rounded-full transition-all" style="height: @(GetRemainingPercentage())%; width: 100%"></div>
- }
- </div>
- <button type="button" @onclick="() => DeleteTotpCode(totpCode)" class="text-red-600 hover:text-red-800 dark:text-red-500 dark:hover:text-red-400">
+ <button type="button" @onclick="() => DeleteTotpCode(totpCode)" class="delete-totp-code text-red-600 hover:text-red-800 dark:text-red-500 dark:hover:text-red-400">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"></path>
</svg>
@@ -119,27 +100,19 @@
[Parameter]
public EventCallback<List<TotpCode>> TotpCodesChanged { get; set; }
- private bool IsLoading { get; set; } = true;
+ /// <summary>
+ /// The dictionary of current cached TOTP codes.
+ /// </summary>
+ private Dictionary<string, string> _currentCodes = new();
+
private bool IsAddFormVisible { get; set; } = false;
private TotpCodeEdit NewTotpCode { get; set; } = new();
- private Timer? _refreshTimer;
- private Dictionary<string, string> _currentCodes = new();
private List<Guid> OriginalTotpCodeIds { get; set; } = [];
- /// <inheritdoc/>
- public void Dispose()
- {
- _refreshTimer?.Dispose();
- }
-
/// <inheritdoc/>
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
- LoadTotpCodes();
-
- // Start a timer to refresh the TOTP codes every second
- _refreshTimer = new Timer(async _ => await RefreshCodesAsync(), null, 0, 1000);
}
/// <inheritdoc/>
@@ -147,75 +120,30 @@
{
base.OnInitialized();
- // Keep track of the original TOTP codes
+ // Keep track of the original TOTP codes.
OriginalTotpCodeIds = TotpCodeList.Where(t => !t.IsDeleted).Select(t => t.Id).ToList();
}
- private void LoadTotpCodes()
- {
- IsLoading = true;
- StateHasChanged();
-
- // Generate initial codes
- foreach (var code in TotpCodeList.Where(t => !t.IsDeleted))
- {
- _currentCodes[code.SecretKey] = TotpGenerator.GenerateTotpCode(code.SecretKey);
- }
-
- IsLoading = false;
- StateHasChanged();
- }
-
- private async Task RefreshCodesAsync()
- {
- foreach (var code in TotpCodeList.Where(t => !t.IsDeleted))
- {
- var newCode = TotpGenerator.GenerateTotpCode(code.SecretKey);
- if (!_currentCodes.ContainsKey(code.SecretKey) || _currentCodes[code.SecretKey] != newCode)
- {
- _currentCodes[code.SecretKey] = newCode;
- }
- }
-
- // Always update the UI to refresh the progress bar
- await InvokeAsync(StateHasChanged);
- }
-
- private string GetTotpCode(string secretKey)
- {
- if (_currentCodes.TryGetValue(secretKey, out var code))
- {
- return code;
- }
-
- var newCode = TotpGenerator.GenerateTotpCode(secretKey);
- _currentCodes[secretKey] = newCode;
- return newCode;
- }
-
- private int GetRemainingSeconds()
- {
- return TotpCodeService.GetRemainingSeconds();
- }
-
- private int GetRemainingPercentage()
- {
- var remaining = GetRemainingSeconds();
- // Invert the percentage so it counts down instead of up
- return (int)(((30.0 - remaining) / 30.0) * 100);
- }
-
+ /// <summary>
+ /// Shows the add form.
+ /// </summary>
private void ShowAddForm()
{
NewTotpCode = new TotpCodeEdit();
IsAddFormVisible = true;
}
+ /// <summary>
+ /// Hides the add form.
+ /// </summary>
private void HideAddForm()
{
IsAddFormVisible = false;
}
+ /// <summary>
+ /// Adds a new TOTP code called from the add form.
+ /// </summary>
private async Task AddTotpCode()
{
string secretKey = NewTotpCode.SecretKey;
@@ -289,6 +217,10 @@
StateHasChanged();
}
+ /// <summary>
+ /// Deletes a TOTP code.
+ /// </summary>
+ /// <param name="totpCode">The TOTP code to delete.</param>
private async Task DeleteTotpCode(TotpCode totpCode)
{
// Show confirmation modal.
diff --git a/src/AliasVault.Client/Main/Components/TotpCodes/TotpViewer.razor b/src/AliasVault.Client/Main/Components/TotpCodes/TotpViewer.razor
index e5fbec2dc..8b0218e2a 100644
--- a/src/AliasVault.Client/Main/Components/TotpCodes/TotpViewer.razor
+++ b/src/AliasVault.Client/Main/Components/TotpCodes/TotpViewer.razor
@@ -66,9 +66,13 @@
[Parameter]
public required ICollection<TotpCode> TotpCodeList { get; set; }
+ /// <summary>
+ /// The dictionary of current cached TOTP codes.
+ /// </summary>
+ private Dictionary<string, string> _currentCodes = new();
+
private bool IsLoading { get; set; } = true;
private Timer? _refreshTimer;
- private Dictionary<string, string> _currentCodes = new();
/// <inheritdoc />
public void Dispose()
@@ -93,6 +97,9 @@
IsLoading = false;
}
+ /// <summary>
+ /// Refreshes the TOTP codes by generating new codes based on the secret keys.
+ /// </summary>
private async Task RefreshCodesAsync()
{
foreach (var code in TotpCodeList)
@@ -108,6 +115,11 @@
await InvokeAsync(StateHasChanged);
}
+ /// <summary>
+ /// Gets the TOTP code for a given secret key from the cached current codes dictionary.
+ /// </summary>
+ /// <param name="secretKey">The secret key to get the code for.</param>
+ /// <returns>The TOTP code.</returns>
private string GetTotpCode(string secretKey)
{
if (_currentCodes.TryGetValue(secretKey, out var code))
@@ -120,11 +132,19 @@
return newCode;
}
+ /// <summary>
+ /// Gets the remaining seconds for the TOTP code.
+ /// </summary>
+ /// <returns>The remaining seconds.</returns>
private int GetRemainingSeconds()
{
return TotpCodeService.GetRemainingSeconds();
}
+ /// <summary>
+ /// Gets the remaining percentage for the TOTP code.
+ /// </summary>
+ /// <returns>The remaining percentage.</returns>
private int GetRemainingPercentage()
{
var remaining = GetRemainingSeconds();
@@ -132,6 +152,10 @@
return (int)(((30.0 - remaining) / 30.0) * 100);
}
+ /// <summary>
+ /// Copies the TOTP code to the clipboard.
+ /// </summary>
+ /// <param name="totpCode">The TOTP code to copy.</param>
private async Task CopyToClipboard(TotpCode totpCode)
{
var code = GetTotpCode(totpCode.SecretKey);
@@ -148,5 +172,10 @@
StateHasChanged();
}
+ /// <summary>
+ /// Checks if the TOTP code was last copied.
+ /// </summary>
+ /// <param name="code">The TOTP code to check.</param>
+ /// <returns>True if the TOTP code was last copied, false otherwise.</returns>
private bool IsCopied(string code) => ClipboardCopyService.GetCopiedId() == code;
}
diff --git a/src/AliasVault.Client/Main/Models/CredentialEdit.cs b/src/AliasVault.Client/Main/Models/CredentialEdit.cs
index 3981003fc..9ec5c230d 100644
--- a/src/AliasVault.Client/Main/Models/CredentialEdit.cs
+++ b/src/AliasVault.Client/Main/Models/CredentialEdit.cs
@@ -10,6 +10,9 @@ namespace AliasVault.Client.Main.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
using AliasClientDb;
using AliasVault.Client.Main.Models.FormValidation;
@@ -85,4 +88,83 @@ public sealed class CredentialEdit
/// Gets or sets the TOTP codes list.
/// </summary>
public List<TotpCode> TotpCodes { get; set; } = [];
+
+ /// <summary>
+ /// Creates a CredentialEdit instance from a Credential entity.
+ /// </summary>
+ /// <param name="credential">The credential entity to convert.</param>
+ /// <returns>A new CredentialEdit instance.</returns>
+ public static CredentialEdit FromEntity(Credential credential)
+ {
+ // Create a deep copy of the credential object to prevent changes to the original object
+ var options = new JsonSerializerOptions
+ {
+ ReferenceHandler = ReferenceHandler.Preserve,
+ MaxDepth = 128,
+ };
+
+ // Create a deep copy of the credential object
+ var credentialJson = JsonSerializer.Serialize(credential, options);
+ var credentialCopy = JsonSerializer.Deserialize<Credential>(credentialJson, options)!;
+
+ return new CredentialEdit
+ {
+ Id = credentialCopy.Id,
+ Notes = credentialCopy.Notes ?? string.Empty,
+ Username = credentialCopy.Username ?? string.Empty,
+ ServiceName = credentialCopy.Service.Name ?? string.Empty,
+ ServiceUrl = credentialCopy.Service.Url,
+ ServiceLogo = credentialCopy.Service.Logo,
+ Password = credentialCopy.Passwords.FirstOrDefault() ?? new Password
+ {
+ Value = string.Empty,
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow,
+ },
+ Alias = credentialCopy.Alias,
+ AliasBirthDate = credentialCopy.Alias.BirthDate.ToString("yyyy-MM-dd"),
+ Attachments = credentialCopy.Attachments.ToList(),
+ TotpCodes = credentialCopy.TotpCodes.ToList(),
+ CreateDate = credentialCopy.CreatedAt,
+ LastUpdate = credentialCopy.UpdatedAt,
+ };
+ }
+
+ /// <summary>
+ /// Converts this CredentialEdit instance to a Credential entity.
+ /// </summary>
+ /// <returns>A new Credential entity.</returns>
+ public Credential ToEntity()
+ {
+ var credential = new Credential
+ {
+ Id = Id,
+ Notes = Notes,
+ Username = Username,
+ Service = new Service
+ {
+ Name = ServiceName,
+ Url = ServiceUrl,
+ Logo = ServiceLogo,
+ },
+ Passwords = new List<Password>
+ {
+ Password,
+ },
+ Alias = Alias,
+ Attachments = Attachments,
+ TotpCodes = TotpCodes,
+ };
+
+ if (string.IsNullOrWhiteSpace(AliasBirthDate))
+ {
+ credential.Alias.BirthDate = DateTime.MinValue;
+ }
+ else
+ {
+ credential.Alias.BirthDate = DateTime.Parse(AliasBirthDate, CultureInfo.InvariantCulture);
+ }
+
+ return credential;
+ }
}
diff --git a/src/AliasVault.Client/Main/Pages/Credentials/AddEdit.razor b/src/AliasVault.Client/Main/Pages/Credentials/AddEdit.razor
index 1a61ea1dd..380e66dff 100644
--- a/src/AliasVault.Client/Main/Pages/Credentials/AddEdit.razor
+++ b/src/AliasVault.Client/Main/Pages/Credentials/AddEdit.razor
@@ -217,7 +217,7 @@ else
return;
}
- Obj = CredentialToCredentialEdit(alias);
+ Obj = CredentialEdit.FromEntity(alias);
if (Obj.ServiceUrl is null)
{
Obj.ServiceUrl = CredentialService.DefaultServiceUrl;
@@ -233,7 +233,7 @@ else
alias.Passwords = new List<Password> { new Password() };
alias.TotpCodes = new List<TotpCode>();
- Obj = CredentialToCredentialEdit(alias);
+ Obj = CredentialEdit.FromEntity(alias);
Obj.ServiceUrl = CredentialService.DefaultServiceUrl;
}
@@ -282,7 +282,7 @@ else
GlobalLoadingSpinner.Show();
StateHasChanged();
- Obj = CredentialToCredentialEdit(await CredentialService.GenerateRandomIdentity(CredentialEditToCredential(Obj)));
+ Obj = CredentialEdit.FromEntity(await CredentialService.GenerateRandomIdentity(Obj.ToEntity()));
GlobalLoadingSpinner.Hide();
StateHasChanged();
@@ -325,84 +325,6 @@ else
Obj.Password.Value = CredentialService.GenerateRandomPassword();
}
- /// <summary>
- /// Helper method to convert a Credential object to a CredentialEdit object.
- /// </summary>
- private CredentialEdit CredentialToCredentialEdit(Credential alias)
- {
- // Create a deep copy of the alias object to prevent changes to the original object
- // when editing the alias in the form. We only want to save the changes when the user
- // clicks the save button.
- var options = new JsonSerializerOptions
- {
- ReferenceHandler = ReferenceHandler.Preserve,
- MaxDepth = 128 // Adjust this value as needed
- };
-
- // Create a deep copy of the credential object
- var aliasJson = JsonSerializer.Serialize(alias, options);
- var aliasCopy = JsonSerializer.Deserialize<Credential>(aliasJson, options)!;
-
- return new CredentialEdit
- {
- Id = aliasCopy.Id,
- Notes = aliasCopy.Notes ?? string.Empty,
- Username = aliasCopy.Username ?? string.Empty,
- ServiceName = aliasCopy.Service.Name ?? string.Empty,
- ServiceUrl = aliasCopy.Service.Url,
- ServiceLogo = aliasCopy.Service.Logo,
- Password = aliasCopy.Passwords.FirstOrDefault() ?? new Password
- {
- Value = string.Empty,
- CreatedAt = DateTime.UtcNow,
- UpdatedAt = DateTime.UtcNow,
- },
- Alias = aliasCopy.Alias,
- AliasBirthDate = aliasCopy.Alias.BirthDate.ToString("yyyy-MM-dd"),
- Attachments = aliasCopy.Attachments.ToList(),
- TotpCodes = aliasCopy.TotpCodes.ToList(),
- CreateDate = aliasCopy.CreatedAt,
- LastUpdate = aliasCopy.UpdatedAt
- };
- }
-
- /// <summary>
- /// Helper method to convert a CredentialEdit object to a Credential object.
- /// </summary>
- private Credential CredentialEditToCredential(CredentialEdit alias)
- {
- var credential = new Credential
- {
- Id = alias.Id,
- Notes = alias.Notes,
- Username = alias.Username,
- Service = new Service
- {
- Name = alias.ServiceName,
- Url = alias.ServiceUrl,
- Logo = alias.ServiceLogo,
- },
- Passwords = new List<Password>
- {
- alias.Password,
- },
- Alias = alias.Alias,
- Attachments = alias.Attachments,
- TotpCodes = alias.TotpCodes,
- };
-
- if (string.IsNullOrWhiteSpace(alias.AliasBirthDate))
- {
- credential.Alias.BirthDate = DateTime.MinValue;
- }
- else
- {
- credential.Alias.BirthDate = DateTime.Parse(alias.AliasBirthDate, CultureInfo.InvariantCulture);
- }
-
- return credential;
- }
-
/// <summary>
/// Cancel the edit operation and navigate back to the credentials view.
/// </summary>
@@ -436,12 +358,12 @@ else
{
if (Id is not null)
{
- Id = await CredentialService.UpdateEntryAsync(CredentialEditToCredential(Obj));
+ Id = await CredentialService.UpdateEntryAsync(Obj.ToEntity());
}
}
else
{
- Id = await CredentialService.InsertEntryAsync(CredentialEditToCredential(Obj));
+ Id = await CredentialService.InsertEntryAsync(Obj.ToEntity());
}
GlobalLoadingSpinner.Hide();