Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor CSV import logic to utility class (#542)
Leendert de Borst3f6575dfe5d7
diff --git a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razorindex aeadad363..208724c2a 100644--- a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceCard.razor@@ -2,7 +2,7 @@@inject IJSRuntime JSRuntime@inject CredentialService CredentialService@inject DbService DbService-@using AliasVault.Client.Main.Pages.Settings.ImportExport.Models+@using AliasVault.ImportExport.Models<div class="flex flex-col p-4 bg-white border border-gray-200 rounded-lg shadow-sm dark:border-gray-700 dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700"><div class="flex items-center mb-3">@@ -97,13 +97,13 @@/// <summary>/// The imported credentials./// </summary>- private List<ImportCredential> ImportedCredentials { get; set; } = new();+ private List<ImportedCredential> ImportedCredentials { get; set; } = new();/// <summary>/// Sets the imported credentials./// </summary>/// <param name="importedCredentials">The imported credentials.</param>- public void SetImportedCredentials(List<ImportCredential> importedCredentials)+ public void SetImportedCredentials(List<ImportedCredential> importedCredentials){ImportedCredentials = importedCredentials;}diff --git a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razorindex 03ed233b8..26a912e21 100644--- a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor+++ b/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Components/ImportServiceKeePass.razor@@ -1,5 +1,5 @@@inject ILogger<ImportServiceKeePass> Logger-@using AliasVault.Client.Main.Pages.Settings.ImportExport.Models+@using AliasVault.ImportExport.Importers<ImportServiceCardServiceName="KeePass"@@ -20,65 +20,14 @@{Logger.LogInformation($"Processing KeePass file: {e.File.Name}");- var importCredentials = new List<ImportCredential>();-try{using var stream = e.File.OpenReadStream();using var reader = new StreamReader(stream);+ var fileContents = await reader.ReadToEndAsync();- // Read and parse header row- var headerLine = await reader.ReadLineAsync();- if (headerLine == null) {- throw new InvalidDataException("CSV file header not found");- }-- var headers = headerLine.Split(',')- .Select((header, index) => (header.Trim('"'), index))- .ToDictionary(h => h.Item1, h => h.index);-- // Validate required headers- var requiredHeaders = new[] { "Title", "Username", "Password" };- var missingHeaders = requiredHeaders.Where(h => !headers.ContainsKey(h)).ToList();- if (missingHeaders.Any())- {- throw new InvalidDataException(- $"Missing required headers: {string.Join(", ", missingHeaders)}");- }-- string? line;- while ((line = await reader.ReadLineAsync()) != null)- {- if (string.IsNullOrWhiteSpace(line)) {- continue;- }-- var values = line.Split(',').Select(v => v.Trim('"')).ToArray();- if (values.Length < headers.Count) {- continue;- }-- // TODO: check how TOTP code should be parsed: can we store the full otpauth:// string- // or do we need to extract the secret key only?- // TODO: currently the TOTP auth component errors with full otpauth:// string.- var credential = new ImportCredential- {- ServiceName = values[headers["Title"]],- ServiceUrl = headers.ContainsKey("URL") && !string.IsNullOrEmpty(values[headers["URL"]])- ? values[headers["URL"]]- : string.Empty,- Username = headers.ContainsKey("Email") && !string.IsNullOrEmpty(values[headers["Email"]])- ? values[headers["Email"]]- : values[headers["Username"]],- Password = values[headers["Password"]],- TwoFactorSecret = headers.ContainsKey("OTPAuth") && !string.IsNullOrEmpty(values[headers["OTPAuth"]])- ? values[headers["OTPAuth"]]- : string.Empty,- Notes = headers.ContainsKey("Notes") ? values[headers["Notes"]] : string.Empty- };-- importCredentials.Add(credential);- }+ var importCredentials = await KeePassImporter.ImportFromCsvAsync(fileContents);+ _importServiceCard.SetImportedCredentials(importCredentials);}catch (Exception ex){@@ -86,7 +35,6 @@throw;}- _importServiceCard.SetImportedCredentials(importCredentials);}private void RefreshVault()diff --git a/src/Utilities/AliasVault.ImportExport/Importers/KeePassImporter.cs b/src/Utilities/AliasVault.ImportExport/Importers/KeePassImporter.csnew file mode 100644index 000000000..59fd67551--- /dev/null+++ b/src/Utilities/AliasVault.ImportExport/Importers/KeePassImporter.cs@@ -0,0 +1,56 @@+//-----------------------------------------------------------------------+// <copyright file="CredentialCsvService.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.ImportExport.Importers;++using AliasVault.ImportExport.Models;+using AliasVault.ImportExport.Models.Imports;+using CsvHelper;+using CsvHelper.Configuration;+using System.Globalization;++/// <summary>+/// Imports credentials from KeePass.+/// </summary>+public static class KeePassImporter+{+ /// <summary>+ /// Imports KeePass CSV file and converts contents to list of ImportedCredential model objects.+ /// </summary>+ /// <param name="fileContent">The content of the CSV file.</param>+ /// <returns>The imported list of ImportedCredential objects.</returns>+ public static async Task<List<ImportedCredential>> ImportFromCsvAsync(string fileContent)+ {+ using var reader = new StringReader(fileContent);+ using var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture));++ var credentials = new List<ImportedCredential>();+ await foreach (var record in csv.GetRecordsAsync<KeePassCsvRecord>())+ {+ // TODO: OTPAuth should be converted from URL to a secret key during import or during+ // the actual creation of the imported credential object.+ var credential = new ImportedCredential+ {+ ServiceName = record.Title,+ ServiceUrl = record.URL,+ Username = record.Username,+ Password = record.Password,+ TwoFactorSecret = record.OTPAuth,+ Notes = record.Notes+ };++ credentials.Add(credential);+ }++ if (credentials.Count == 0)+ {+ throw new InvalidOperationException("No records found in the CSV file.");+ }++ return credentials;+ }+}\ No newline at end of filediff --git a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Models/ImportCredential.cs b/src/Utilities/AliasVault.ImportExport/Models/ImportedCredential.cssimilarity index 82%rename from src/AliasVault.Client/Main/Pages/Settings/ImportExport/Models/ImportCredential.csrename to src/Utilities/AliasVault.ImportExport/Models/ImportedCredential.csindex 3c279bdf1..96d240f31 100644--- a/src/AliasVault.Client/Main/Pages/Settings/ImportExport/Models/ImportCredential.cs+++ b/src/Utilities/AliasVault.ImportExport/Models/ImportedCredential.cs@@ -5,19 +5,19 @@// </copyright>//------------------------------------------------------------------------namespace AliasVault.Client.Main.Pages.Settings.ImportExport.Models;+namespace AliasVault.ImportExport.Models;/// <summary>-/// Represents a credential in an intermediary format for importing from various sources.+/// Represents a credential in an intermediary format that is imported from various sources./// This model is designed to be flexible enough to handle different import formats while/// maintaining all the essential fields needed for AliasVault credentials./// </summary>-public class ImportCredential+public class ImportedCredential{/// <summary>/// Gets or sets the service name (e.g., "Facebook", "Gmail")./// </summary>- public string ServiceName { get; set; } = string.Empty;+ public string? ServiceName { get; set; }/// <summary>/// Gets or sets the service URL.@@ -27,12 +27,12 @@ public class ImportCredential/// <summary>/// Gets or sets the username or email./// </summary>- public string Username { get; set; } = string.Empty;+ public string? Username { get; set; }/// <summary>/// Gets or sets the password./// </summary>- public string Password { get; set; } = string.Empty;+ public string? Password { get; set; }/// <summary>/// Gets or sets the email address.diff --git a/src/Utilities/AliasVault.ImportExport/Models/Imports/KeePassCsvRecord.cs b/src/Utilities/AliasVault.ImportExport/Models/Imports/KeePassCsvRecord.csnew file mode 100644index 000000000..a8b7c8d2f--- /dev/null+++ b/src/Utilities/AliasVault.ImportExport/Models/Imports/KeePassCsvRecord.cs@@ -0,0 +1,49 @@+//-----------------------------------------------------------------------+// <copyright file="KeePassCsvRecord.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.ImportExport.Models.Imports;++/// <summary>+/// Represents a KeePass CSV record that is being imported from a KeePass CSV export file.+/// </summary>+public class KeePassCsvRecord+{+ /// <summary>+ /// Gets or sets the title/service name (e.g., "Facebook", "Gmail").+ /// </summary>+ public string Title { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the username.+ /// </summary>+ public string? Username { get; set; }++ /// <summary>+ /// Gets or sets the email address.+ /// </summary>+ public string? Email { get; set; }++ /// <summary>+ /// Gets or sets the password.+ /// </summary>+ public string? Password { get; set; }++ /// <summary>+ /// Gets or sets the service URL.+ /// </summary>+ public string? URL { get; set; }++ /// <summary>+ /// Gets or sets the OTP (One-Time Password) authentication secret.+ /// </summary>+ public string? OTPAuth { get; set; }++ /// <summary>+ /// Gets or sets any additional notes.+ /// </summary>+ public string? Notes { get; set; }+}