Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add credentials TOTP code scaffolding (#181)
Leendert de Borst61a88e671593
diff --git a/src/AliasVault.Client/AliasVault.Client.csproj b/src/AliasVault.Client/AliasVault.Client.csprojindex 48ef67ae3..d425b8257 100644--- a/src/AliasVault.Client/AliasVault.Client.csproj+++ b/src/AliasVault.Client/AliasVault.Client.csproj@@ -84,6 +84,7 @@<ProjectReference Include="..\Utilities\Cryptography\AliasVault.Cryptography.Client\AliasVault.Cryptography.Client.csproj" /><ProjectReference Include="..\Utilities\AliasVault.CsvImportExport\AliasVault.CsvImportExport.csproj" /><ProjectReference Include="..\Utilities\AliasVault.FaviconExtractor\AliasVault.FaviconExtractor.csproj" />+ <ProjectReference Include="..\Utilities\AliasVault.TotpGenerator\AliasVault.TotpGenerator.csproj" /><ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js" /><ServiceWorker Include="wwwroot\service-worker.published.js"><PublishedContent>wwwroot/service-worker.published.js</PublishedContent>diff --git a/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razornew file mode 100644index 000000000..20a5a18cc--- /dev/null+++ b/src/AliasVault.Client/Main/Components/TotpCodes/TotpCodes.razor@@ -0,0 +1,258 @@+@inherits ComponentBase+@inject TotpCodeService TotpCodeService+@inject GlobalNotificationService GlobalNotificationService+@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">+ <div>+ <h3 class="mb-4 text-xl font-semibold dark:text-white">Two-Factor Authentication</h3>+ </div>+ @if (TotpCodeList.Count > 0)+ {+ <div>+ <button @onclick="ShowAddTotpCodeModal" 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)+ {+ <div class="flex flex-col justify-center">+ <p class="mb-4 text-gray-500 dark:text-gray-400">No 2FA TOTP codes added yet.</p>+ <button @onclick="ShowAddTotpCodeModal" type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">+ Add 2FA TOTP Code+ </button>+ </div>+ }+ else+ {+ <div class="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">+ @foreach (var totpCode in TotpCodeList)+ {+ <div class="p-4 bg-gray-50 border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600">+ <div class="flex justify-between items-center mb-2">+ <h4 class="text-lg font-medium text-gray-900 dark:text-white">@totpCode.Name</h4>+ <button @onclick="() => DeleteTotpCode(totpCode.Id)" class="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>+ </button>+ </div>+ <div class="flex flex-col items-center">+ <div class="text-3xl font-bold text-gray-900 dark:text-white mb-2">@GetTotpCode(totpCode.SecretKey)</div>+ <div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mb-2">+ <div class="bg-blue-600 h-2.5 rounded-full" style="width: @(GetRemainingPercentage())%"></div>+ </div>+ <div class="text-sm text-gray-500 dark:text-gray-400">Refreshes in @GetRemainingSeconds() seconds</div>+ </div>+ </div>+ }+ </div>+ }+</div>++@if (IsAddTotpCodeModalVisible)+{+ <div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">+ <div class="relative p-4 w-full max-w-md max-h-full">+ <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">+ <div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t dark:border-gray-600">+ <h3 class="text-xl font-semibold text-gray-900 dark:text-white">+ Add 2FA TOTP Code+ </h3>+ <button @onclick="HideAddTotpCodeModal" type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white">+ <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">+ <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>+ </svg>+ <span class="sr-only">Close modal</span>+ </button>+ </div>+ <div class="p-4 md:p-5">+ <div class="mb-4">+ <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>+ <input type="text" id="name" @bind="NewTotpCode.Name" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="Service Name" required>+ </div>+ <div class="mb-4">+ <label for="secretKey" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Secret Key (32 characters)</label>+ <input type="text" id="secretKey" @bind="NewTotpCode.SecretKey" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white" placeholder="JBSWY3DPEHPK3PXP" required>+ <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Enter the secret key provided by the service.</p>+ </div>+ <button @onclick="AddTotpCode" class="w-full text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">+ Save+ </button>+ </div>+ </div>+ </div>+ </div>+}++@code {+ /// <summary>+ /// The credential ID.+ /// </summary>+ [Parameter]+ public Guid CredentialId { get; set; }++ /// <summary>+ /// The service name.+ /// </summary>+ [Parameter]+ public string ServiceName { get; set; } = string.Empty;++ private List<TotpCode> TotpCodeList { get; set; } = new();+ private bool IsLoading { get; set; } = true;+ private bool IsAddTotpCodeModalVisible { get; set; } = false;+ private TotpCode NewTotpCode { get; set; } = new();+ private Timer? _refreshTimer;+ private Dictionary<string, string> _currentCodes = new();++ /// <inheritdoc/>+ protected override async Task OnInitializedAsync()+ {+ await base.OnInitializedAsync();+ await LoadTotpCodesAsync();++ // Start a timer to refresh the TOTP codes every second+ _refreshTimer = new Timer(async _ => await RefreshCodesAsync(), null, 0, 1000);+ }++ private async Task LoadTotpCodesAsync()+ {+ IsLoading = true;+ StateHasChanged();++ TotpCodeList = await TotpCodeService.GetTotpCodesAsync(CredentialId);++ // Generate initial codes+ foreach (var code in TotpCodeList)+ {+ _currentCodes[code.SecretKey] = TotpCodeService.GenerateTotpCode(code.SecretKey);+ }++ IsLoading = false;+ StateHasChanged();+ }++ private async Task RefreshCodesAsync()+ {+ bool hasChanges = false;++ foreach (var code in TotpCodeList)+ {+ var newCode = TotpCodeService.GenerateTotpCode(code.SecretKey);+ if (!_currentCodes.ContainsKey(code.SecretKey) || _currentCodes[code.SecretKey] != newCode)+ {+ _currentCodes[code.SecretKey] = newCode;+ hasChanges = true;+ }+ }++ if (hasChanges)+ {+ await InvokeAsync(StateHasChanged);+ }+ }++ private string GetTotpCode(string secretKey)+ {+ if (_currentCodes.TryGetValue(secretKey, out var code))+ {+ return code;+ }++ var newCode = TotpCodeService.GenerateTotpCode(secretKey);+ _currentCodes[secretKey] = newCode;+ return newCode;+ }++ private int GetRemainingSeconds()+ {+ return TotpCodeService.GetRemainingSeconds();+ }++ private int GetRemainingPercentage()+ {+ var remaining = GetRemainingSeconds();+ return (int)((remaining / 30.0) * 100);+ }++ private void ShowAddTotpCodeModal()+ {+ NewTotpCode = new TotpCode+ {+ CredentialId = CredentialId,+ Name = ServiceName+ };+ IsAddTotpCodeModalVisible = true;+ }++ private void HideAddTotpCodeModal()+ {+ IsAddTotpCodeModalVisible = false;+ }++ private async Task AddTotpCode()+ {+ if (string.IsNullOrWhiteSpace(NewTotpCode.Name))+ {+ GlobalNotificationService.AddErrorMessage("Name is required.", true);+ return;+ }++ if (string.IsNullOrWhiteSpace(NewTotpCode.SecretKey))+ {+ GlobalNotificationService.AddErrorMessage("Secret key is required.", true);+ return;+ }++ try+ {+ // Validate the secret key by trying to generate a code+ TotpCodeService.GenerateTotpCode(NewTotpCode.SecretKey);+ }+ catch (Exception)+ {+ GlobalNotificationService.AddErrorMessage("Invalid secret key. Please check and try again.", true);+ return;+ }++ var result = await TotpCodeService.AddTotpCodeAsync(NewTotpCode);+ if (result != null)+ {+ GlobalNotificationService.AddSuccessMessage("TOTP code added successfully.", true);+ HideAddTotpCodeModal();+ await LoadTotpCodesAsync();+ }+ else+ {+ GlobalNotificationService.AddErrorMessage("Failed to add TOTP code. Please try again.", true);+ }+ }++ private async Task DeleteTotpCode(Guid totpCodeId)+ {+ var result = await TotpCodeService.DeleteTotpCodeAsync(totpCodeId);+ if (result)+ {+ GlobalNotificationService.AddSuccessMessage("TOTP code deleted successfully.", true);+ await LoadTotpCodesAsync();+ }+ else+ {+ GlobalNotificationService.AddErrorMessage("Failed to delete TOTP code. Please try again.", true);+ }+ }++ /// <inheritdoc/>+ public void Dispose()+ {+ _refreshTimer?.Dispose();+ }+}diff --git a/src/AliasVault.Client/Main/Pages/Credentials/View.razor b/src/AliasVault.Client/Main/Pages/Credentials/View.razorindex f502cb967..bdbc65a56 100644--- a/src/AliasVault.Client/Main/Pages/Credentials/View.razor+++ b/src/AliasVault.Client/Main/Pages/Credentials/View.razor@@ -44,6 +44,7 @@ else</div></div><RecentEmails EmailAddress="@Alias.Alias.Email" />+ <TotpCodes CredentialId="@Id" ServiceName="@Alias.Service.Name" />@if (Alias.Notes != null && Alias.Notes.Length > 0){<FormattedNote Notes="@Alias.Notes" />diff --git a/src/AliasVault.Client/Program.cs b/src/AliasVault.Client/Program.csindex 149a6dcea..b184b6c15 100644--- a/src/AliasVault.Client/Program.cs+++ b/src/AliasVault.Client/Program.cs@@ -74,6 +74,7 @@ builder.Services.AddScoped<GlobalLoadingService>();builder.Services.AddScoped<KeyboardShortcutService>();builder.Services.AddScoped<JsInteropService>();builder.Services.AddScoped<EmailService>();+builder.Services.AddScoped<TotpCodeService>();builder.Services.AddSingleton<ClipboardCopyService>();builder.Services.AddScoped<ConfirmModalService>();diff --git a/src/AliasVault.Client/Services/TotpCodeService.cs b/src/AliasVault.Client/Services/TotpCodeService.csnew file mode 100644index 000000000..c7c4c901c--- /dev/null+++ b/src/AliasVault.Client/Services/TotpCodeService.cs@@ -0,0 +1,123 @@+//-----------------------------------------------------------------------+// <copyright file="TotpCodeService.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;++using AliasClientDb;+using AliasVault.Client.Services.Database;+using AliasVault.TotpGenerator;+using Microsoft.EntityFrameworkCore;++/// <summary>+/// Service for managing TOTP codes.+/// </summary>+public class TotpCodeService+{+ private readonly DbService _dbService;+ private readonly ILogger<TotpCodeService> _logger;++ /// <summary>+ /// Initializes a new instance of the <see cref="TotpCodeService"/> class.+ /// </summary>+ /// <param name="dbService">The database service.</param>+ /// <param name="logger">The logger.</param>+ public TotpCodeService(DbService dbService, ILogger<TotpCodeService> logger)+ {+ _dbService = dbService;+ _logger = logger;+ }++ /// <summary>+ /// Gets all TOTP codes for a credential.+ /// </summary>+ /// <param name="credentialId">The credential ID.</param>+ /// <returns>A list of TOTP codes.</returns>+ public async Task<List<TotpCode>> GetTotpCodesAsync(Guid credentialId)+ {+ try+ {+ var dbContext = await _dbService.GetDbContextAsync();+ return await dbContext.TotpCodes+ .Where(t => t.CredentialId == credentialId)+ .ToListAsync();+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error getting TOTP codes for credential {CredentialId}", credentialId);+ return new List<TotpCode>();+ }+ }++ /// <summary>+ /// Adds a new TOTP code.+ /// </summary>+ /// <param name="totpCode">The TOTP code to add.</param>+ /// <returns>The added TOTP code.</returns>+ public async Task<TotpCode?> AddTotpCodeAsync(TotpCode totpCode)+ {+ try+ {+ var dbContext = await _dbService.GetDbContextAsync();+ dbContext.TotpCodes.Add(totpCode);+ await dbContext.SaveChangesAsync();+ return totpCode;+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error adding TOTP code for credential {CredentialId}", totpCode.CredentialId);+ return null;+ }+ }++ /// <summary>+ /// Deletes a TOTP code.+ /// </summary>+ /// <param name="totpCodeId">The TOTP code ID.</param>+ /// <returns>True if the TOTP code was deleted, false otherwise.</returns>+ public async Task<bool> DeleteTotpCodeAsync(Guid totpCodeId)+ {+ try+ {+ var dbContext = await _dbService.GetDbContextAsync();+ var totpCode = await dbContext.TotpCodes.FindAsync(totpCodeId);+ if (totpCode == null)+ {+ return false;+ }++ dbContext.TotpCodes.Remove(totpCode);+ await dbContext.SaveChangesAsync();+ return true;+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error deleting TOTP code {TotpCodeId}", totpCodeId);+ return false;+ }+ }++ /// <summary>+ /// Generates a TOTP code for a given secret key.+ /// </summary>+ /// <param name="secretKey">The secret key.</param>+ /// <returns>The generated TOTP code.</returns>+ public string GenerateTotpCode(string secretKey)+ {+ return TotpGenerator.GenerateTotpCode(secretKey);+ }++ /// <summary>+ /// Gets the remaining seconds until the TOTP code expires.+ /// </summary>+ /// <param name="step">The time step in seconds. Default is 30.</param>+ /// <returns>The remaining seconds.</returns>+ public int GetRemainingSeconds(int step = 30)+ {+ var unixTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();+ return step - (int)(unixTimestamp % step);+ }+}diff --git a/src/AliasVault.Client/_Imports.razor b/src/AliasVault.Client/_Imports.razorindex c52d02bb5..12334b443 100644--- a/src/AliasVault.Client/_Imports.razor+++ b/src/AliasVault.Client/_Imports.razor@@ -19,6 +19,7 @@@using AliasVault.Client.Main.Components.Forms@using AliasVault.Client.Main.Components.Layout@using AliasVault.Client.Main.Components.Loading+@using AliasVault.Client.Main.Components.TotpCodes@using AliasVault.Client.Main.Components.Widgets@using AliasVault.Client.Main.Models@using AliasVault.Client.Servicesdiff --git a/src/AliasVault.Client/wwwroot/css/tailwind.css b/src/AliasVault.Client/wwwroot/css/tailwind.cssindex 7d1972afc..f3b83fc9f 100644--- a/src/AliasVault.Client/wwwroot/css/tailwind.css+++ b/src/AliasVault.Client/wwwroot/css/tailwind.css@@ -833,6 +833,10 @@ video {margin-top: 2rem;}+.ms-auto {+ margin-inline-start: auto;+}+.line-clamp-2 {overflow: hidden;display: -webkit-box;@@ -936,6 +940,10 @@ video {max-height: 90vh;}+.max-h-full {+ max-height: 100%;+}+.min-h-\[250px\] {min-height: 250px;}@@ -1317,6 +1325,11 @@ video {border-bottom-right-radius: 0.5rem;}+.rounded-t {+ border-top-left-radius: 0.25rem;+ border-top-right-radius: 0.25rem;+}+.border {border-width: 1px;}@@ -1549,6 +1562,25 @@ video {background-color: rgb(254 252 232 / var(--tw-bg-opacity));}+.bg-black {+ --tw-bg-opacity: 1;+ background-color: rgb(0 0 0 / var(--tw-bg-opacity));+}++.bg-blue-600 {+ --tw-bg-opacity: 1;+ background-color: rgb(37 99 235 / var(--tw-bg-opacity));+}++.bg-blue-700 {+ --tw-bg-opacity: 1;+ background-color: rgb(29 78 216 / var(--tw-bg-opacity));+}++.bg-transparent {+ background-color: transparent;+}+.bg-opacity-50 {--tw-bg-opacity: 0.5;}@@ -2149,6 +2181,11 @@ video {background-color: rgb(153 27 27 / var(--tw-bg-opacity));}+.hover\:bg-blue-800:hover {+ --tw-bg-opacity: 1;+ background-color: rgb(30 64 175 / var(--tw-bg-opacity));+}+.hover\:from-primary-600:hover {--tw-gradient-from: #d68338 var(--tw-gradient-from-position);--tw-gradient-to: rgb(214 131 56 / 0) var(--tw-gradient-to-position);@@ -2209,6 +2246,11 @@ video {color: rgb(255 255 255 / var(--tw-text-opacity));}+.hover\:text-red-800:hover {+ --tw-text-opacity: 1;+ color: rgb(153 27 27 / var(--tw-text-opacity));+}+.hover\:underline:hover {text-decoration-line: underline;}@@ -2379,6 +2421,11 @@ video {border-color: rgb(234 179 8 / var(--tw-border-opacity));}+.dark\:border-gray-500:is(.dark *) {+ --tw-border-opacity: 1;+ border-color: rgb(107 114 128 / var(--tw-border-opacity));+}+.dark\:bg-blue-800:is(.dark *) {--tw-bg-opacity: 1;background-color: rgb(30 64 175 / var(--tw-bg-opacity));@@ -2477,6 +2524,11 @@ video {background-color: rgb(113 63 18 / var(--tw-bg-opacity));}+.dark\:bg-blue-600:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(37 99 235 / var(--tw-bg-opacity));+}+.dark\:bg-opacity-80:is(.dark *) {--tw-bg-opacity: 0.8;}@@ -2571,6 +2623,11 @@ video {color: rgb(250 204 21 / var(--tw-text-opacity));}+.dark\:text-red-500:is(.dark *) {+ --tw-text-opacity: 1;+ color: rgb(239 68 68 / var(--tw-text-opacity));+}+.dark\:placeholder-gray-400:is(.dark *)::-moz-placeholder {--tw-placeholder-opacity: 1;color: rgb(156 163 175 / var(--tw-placeholder-opacity));@@ -2630,6 +2687,16 @@ video {background-color: rgb(185 28 28 / var(--tw-bg-opacity));}+.dark\:hover\:bg-blue-600:hover:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(37 99 235 / var(--tw-bg-opacity));+}++.dark\:hover\:bg-blue-700:hover:is(.dark *) {+ --tw-bg-opacity: 1;+ background-color: rgb(29 78 216 / var(--tw-bg-opacity));+}+.dark\:hover\:from-primary-500:hover:is(.dark *) {--tw-gradient-from: #f49541 var(--tw-gradient-from-position);--tw-gradient-to: rgb(244 149 65 / 0) var(--tw-gradient-to-position);@@ -2665,6 +2732,11 @@ video {color: rgb(255 255 255 / var(--tw-text-opacity));}+.dark\:hover\:text-red-400:hover:is(.dark *) {+ --tw-text-opacity: 1;+ color: rgb(248 113 113 / var(--tw-text-opacity));+}+.dark\:focus\:border-blue-500:focus:is(.dark *) {--tw-border-opacity: 1;border-color: rgb(59 130 246 / var(--tw-border-opacity));@@ -2880,6 +2952,10 @@ video {margin-right: calc(0.5rem * var(--tw-space-x-reverse));margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse)));}++ .md\:p-5 {+ padding: 1.25rem;+ }}@media (min-width: 1024px) {diff --git a/src/Databases/AliasClientDb/AliasClientDbContext.cs b/src/Databases/AliasClientDb/AliasClientDbContext.csindex e9fd71d0b..13e248f83 100644--- a/src/Databases/AliasClientDb/AliasClientDbContext.cs+++ b/src/Databases/AliasClientDb/AliasClientDbContext.cs@@ -10,7 +10,6 @@ namespace AliasClientDb;using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.Configuration;-using Microsoft.Extensions.Logging;/// <summary>/// The AliasClientDbContext class.@@ -78,6 +77,11 @@ public class AliasClientDbContext : DbContext/// </summary>public DbSet<Setting> Settings { get; set; }+ /// <summary>+ /// Gets or sets the TotpCodes DbSet.+ /// </summary>+ public DbSet<TotpCode> TotpCodes { get; set; }+/// <summary>/// The OnModelCreating method./// </summary>@@ -125,6 +129,13 @@ public class AliasClientDbContext : DbContext.WithMany(c => c.Passwords).HasForeignKey(l => l.CredentialId).OnDelete(DeleteBehavior.Cascade);++ // Configure TotpCode - Credential relationship+ modelBuilder.Entity<TotpCode>()+ .HasOne(l => l.Credential)+ .WithMany(c => c.TotpCodes)+ .HasForeignKey(l => l.CredentialId)+ .OnDelete(DeleteBehavior.Cascade);}/// <summary>diff --git a/src/Databases/AliasClientDb/Credential.cs b/src/Databases/AliasClientDb/Credential.csindex cfc7f1b07..27a4db461 100644--- a/src/Databases/AliasClientDb/Credential.cs+++ b/src/Databases/AliasClientDb/Credential.cs@@ -53,6 +53,11 @@ public class Credential : SyncableEntity/// </summary>public virtual ICollection<Attachment> Attachments { get; set; } = [];+ /// <summary>+ /// Gets or sets the TOTP code objects.+ /// </summary>+ public virtual ICollection<TotpCode> TotpCodes { get; set; } = [];+/// <summary>/// Gets or sets the service ID foreign key./// </summary>diff --git a/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.Designer.cs b/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.Designer.csnew file mode 100644index 000000000..ae320ee3e--- /dev/null+++ b/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.Designer.cs@@ -0,0 +1,364 @@+// <auto-generated />+using System;+using AliasClientDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;++#nullable disable++namespace AliasClientDb.Migrations+{+ [DbContext(typeof(AliasClientDbContext))]+ [Migration("20250310131554_1.5.0-AddTotpCodes")]+ partial class _150AddTotpCodes+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "9.0.2")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true);++ modelBuilder.Entity("AliasClientDb.Alias", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("BirthDate")+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Email")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("FirstName")+ .HasMaxLength(255)+ .HasColumnType("VARCHAR");++ b.Property<string>("Gender")+ .HasMaxLength(255)+ .HasColumnType("VARCHAR");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<string>("LastName")+ .HasMaxLength(255)+ .HasColumnType("VARCHAR");++ b.Property<string>("NickName")+ .HasMaxLength(255)+ .HasColumnType("VARCHAR");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("Aliases");+ });++ modelBuilder.Entity("AliasClientDb.Attachment", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<byte[]>("Blob")+ .IsRequired()+ .HasColumnType("BLOB");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<Guid>("CredentialId")+ .HasColumnType("TEXT");++ b.Property<string>("Filename")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("CredentialId");++ b.ToTable("Attachments");+ });++ modelBuilder.Entity("AliasClientDb.Credential", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<Guid>("AliasId")+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<string>("Notes")+ .HasColumnType("TEXT");++ b.Property<Guid>("ServiceId")+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Username")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("AliasId");++ b.HasIndex("ServiceId");++ b.ToTable("Credentials");+ });++ modelBuilder.Entity("AliasClientDb.EncryptionKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<bool>("IsPrimary")+ .HasColumnType("INTEGER");++ b.Property<string>("PrivateKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("TEXT");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("EncryptionKeys");+ });++ modelBuilder.Entity("AliasClientDb.Password", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<Guid>("CredentialId")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Value")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("CredentialId");++ b.ToTable("Passwords");+ });++ modelBuilder.Entity("AliasClientDb.Service", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<byte[]>("Logo")+ .HasColumnType("BLOB");++ b.Property<string>("Name")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Url")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.ToTable("Services");+ });++ modelBuilder.Entity("AliasClientDb.Setting", b =>+ {+ b.Property<string>("Key")+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.Property<string>("Value")+ .HasColumnType("TEXT");++ b.HasKey("Key");++ b.ToTable("Settings");+ });++ modelBuilder.Entity("AliasClientDb.TotpCode", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<Guid>("CredentialId")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("SecretKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("CredentialId");++ b.ToTable("TotpCodes");+ });++ modelBuilder.Entity("AliasClientDb.Attachment", b =>+ {+ b.HasOne("AliasClientDb.Credential", "Credential")+ .WithMany("Attachments")+ .HasForeignKey("CredentialId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Credential");+ });++ modelBuilder.Entity("AliasClientDb.Credential", b =>+ {+ b.HasOne("AliasClientDb.Alias", "Alias")+ .WithMany("Credentials")+ .HasForeignKey("AliasId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasClientDb.Service", "Service")+ .WithMany("Credentials")+ .HasForeignKey("ServiceId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Alias");++ b.Navigation("Service");+ });++ modelBuilder.Entity("AliasClientDb.Password", b =>+ {+ b.HasOne("AliasClientDb.Credential", "Credential")+ .WithMany("Passwords")+ .HasForeignKey("CredentialId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Credential");+ });++ modelBuilder.Entity("AliasClientDb.TotpCode", b =>+ {+ b.HasOne("AliasClientDb.Credential", "Credential")+ .WithMany("TotpCodes")+ .HasForeignKey("CredentialId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Credential");+ });++ modelBuilder.Entity("AliasClientDb.Alias", b =>+ {+ b.Navigation("Credentials");+ });++ modelBuilder.Entity("AliasClientDb.Credential", b =>+ {+ b.Navigation("Attachments");++ b.Navigation("Passwords");++ b.Navigation("TotpCodes");+ });++ modelBuilder.Entity("AliasClientDb.Service", b =>+ {+ b.Navigation("Credentials");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.cs b/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.csnew file mode 100644index 000000000..bd56711f3--- /dev/null+++ b/src/Databases/AliasClientDb/Migrations/20250310131554_1.5.0-AddTotpCodes.cs@@ -0,0 +1,51 @@+// <auto-generated />+using System;+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++namespace AliasClientDb.Migrations+{+ /// <inheritdoc />+ public partial class _150AddTotpCodes : Migration+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.CreateTable(+ name: "TotpCodes",+ columns: table => new+ {+ Id = table.Column<Guid>(type: "TEXT", nullable: false),+ Name = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),+ SecretKey = table.Column<string>(type: "TEXT", maxLength: 255, nullable: false),+ CredentialId = table.Column<Guid>(type: "TEXT", nullable: false),+ CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),+ UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),+ IsDeleted = table.Column<bool>(type: "INTEGER", nullable: false)+ },+ constraints: table =>+ {+ table.PrimaryKey("PK_TotpCodes", x => x.Id);+ table.ForeignKey(+ name: "FK_TotpCodes_Credentials_CredentialId",+ column: x => x.CredentialId,+ principalTable: "Credentials",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ });++ migrationBuilder.CreateIndex(+ name: "IX_TotpCodes_CredentialId",+ table: "TotpCodes",+ column: "CredentialId");+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.DropTable(+ name: "TotpCodes");+ }+ }+}diff --git a/src/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs b/src/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.csindex 9d854e1ef..5b4dab588 100644--- a/src/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs+++ b/src/Databases/AliasClientDb/Migrations/AliasClientDbContextModelSnapshot.cs@@ -16,7 +16,7 @@ namespace AliasClientDb.Migrations{#pragma warning disable 612, 618modelBuilder- .HasAnnotation("ProductVersion", "8.0.8")+ .HasAnnotation("ProductVersion", "9.0.2").HasAnnotation("Proxies:ChangeTracking", false).HasAnnotation("Proxies:CheckEquality", false).HasAnnotation("Proxies:LazyLoading", true);@@ -250,6 +250,41 @@ namespace AliasClientDb.Migrationsb.ToTable("Settings");});+ modelBuilder.Entity("AliasClientDb.TotpCode", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("TEXT");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("TEXT");++ b.Property<Guid>("CredentialId")+ .HasColumnType("TEXT");++ b.Property<bool>("IsDeleted")+ .HasColumnType("INTEGER");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<string>("SecretKey")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("TEXT");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("TEXT");++ b.HasKey("Id");++ b.HasIndex("CredentialId");++ b.ToTable("TotpCodes");+ });+modelBuilder.Entity("AliasClientDb.Attachment", b =>{b.HasOne("AliasClientDb.Credential", "Credential")@@ -291,6 +326,17 @@ namespace AliasClientDb.Migrationsb.Navigation("Credential");});+ modelBuilder.Entity("AliasClientDb.TotpCode", b =>+ {+ b.HasOne("AliasClientDb.Credential", "Credential")+ .WithMany("TotpCodes")+ .HasForeignKey("CredentialId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Credential");+ });+modelBuilder.Entity("AliasClientDb.Alias", b =>{b.Navigation("Credentials");@@ -301,6 +347,8 @@ namespace AliasClientDb.Migrationsb.Navigation("Attachments");b.Navigation("Passwords");++ b.Navigation("TotpCodes");});modelBuilder.Entity("AliasClientDb.Service", b =>diff --git a/src/Databases/AliasClientDb/TotpCode.cs b/src/Databases/AliasClientDb/TotpCode.csnew file mode 100644index 000000000..e36e23e5a--- /dev/null+++ b/src/Databases/AliasClientDb/TotpCode.cs@@ -0,0 +1,48 @@+//-----------------------------------------------------------------------+// <copyright file="TotpCode.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 AliasClientDb;++using System.ComponentModel.DataAnnotations;+using System.ComponentModel.DataAnnotations.Schema;+using AliasClientDb.Abstracts;++/// <summary>+/// The TotpCode class that stores 2FA information associated with a credential.+/// </summary>+public class TotpCode : SyncableEntity+{+ /// <summary>+ /// Gets or sets the ID.+ /// </summary>+ [Key]+ [DatabaseGenerated(DatabaseGeneratedOption.Identity)]+ public Guid Id { get; set; }++ /// <summary>+ /// Gets or sets the name of the TOTP code.+ /// </summary>+ [MaxLength(255)]+ public string Name { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the secret key for the TOTP code.+ /// </summary>+ [MaxLength(255)]+ public string SecretKey { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the credential ID.+ /// </summary>+ public Guid CredentialId { get; set; }++ /// <summary>+ /// Gets or sets the credential.+ /// </summary>+ [ForeignKey("CredentialId")]+ public virtual Credential? Credential { get; set; }+}