Skip to content

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

Refactor (#233)

Leendert de Borst21e8171355e5
diff --git a/src/AliasVault.Admin/Services/GlobalNotificationService.cs b/src/AliasVault.Admin/Services/GlobalNotificationService.cs
index fe9c68c54..f7f626b6f 100644
--- a/src/AliasVault.Admin/Services/GlobalNotificationService.cs
+++ b/src/AliasVault.Admin/Services/GlobalNotificationService.cs
@@ -22,22 +22,22 @@ public class GlobalNotificationService
/// <summary>
/// Gets or sets success messages that should be displayed to the user.
/// </summary>
- protected List<string> SuccessMessages { get; set; } = [];
+ private List<string> SuccessMessages { get; set; } = [];
/// <summary>
/// Gets or sets info messages that should be displayed to the user.
/// </summary>
- protected List<string> InfoMessages { get; set; } = [];
+ private List<string> InfoMessages { get; set; } = [];
/// <summary>
/// Gets or sets warning messages that should be displayed to the user.
/// </summary>
- protected List<string> WarningMessages { get; set; } = [];
+ private List<string> WarningMessages { get; set; } = [];
/// <summary>
/// Gets or sets error messages that should be displayed to the user.
/// </summary>
- protected List<string> ErrorMessages { get; set; } = [];
+ private List<string> ErrorMessages { get; set; } = [];
/// <summary>
/// Adds a success message to the list of messages that should be displayed to the user.
diff --git a/src/AliasVault.Admin/Services/UserService.cs b/src/AliasVault.Admin/Services/UserService.cs
index 365273e9a..8436cb048 100644
--- a/src/AliasVault.Admin/Services/UserService.cs
+++ b/src/AliasVault.Admin/Services/UserService.cs
@@ -102,7 +102,7 @@ public class UserService(AliasServerDbContext dbContext, UserManager<AdminUser>
if (httpContextAccessor.HttpContext != null)
{
// Load user from database. Use a new context everytime to ensure we get the latest data.
- var userName = httpContextAccessor.HttpContext?.User?.Identity?.Name ?? string.Empty;
+ var userName = httpContextAccessor.HttpContext?.User.Identity?.Name ?? string.Empty;
var user = await dbContext.AdminUsers.FirstOrDefaultAsync(u => u.UserName == userName);
if (user != null)
@@ -228,13 +228,29 @@ public class UserService(AliasServerDbContext dbContext, UserManager<AdminUser>
return errors;
}
+ /// <summary>
+ /// Checks if supplied password is correct for the user.
+ /// </summary>
+ /// <param name="user">User object.</param>
+ /// <param name="password">The password to check.</param>
+ /// <returns>Boolean indicating whether supplied password is valid and matches what is stored in the database.</returns>
+ public async Task<bool> CheckPasswordAsync(AdminUser user, string password)
+ {
+ if (password.Length == 0)
+ {
+ return false;
+ }
+
+ return await userManager.CheckPasswordAsync(user, password);
+ }
+
/// <summary>
/// Update user roles. This is a separate method because it is called from both CreateUserAsync and UpdateUserAsync.
/// </summary>
/// <param name="user">User object.</param>
/// <param name="roles">New roles for the user.</param>
/// <returns>List of errors if any.</returns>
- public async Task<List<string>> UpdateUserRolesAsync(AdminUser user, List<string> roles)
+ private async Task<List<string>> UpdateUserRolesAsync(AdminUser user, List<string> roles)
{
List<string> errors = new();
@@ -254,22 +270,6 @@ public class UserService(AliasServerDbContext dbContext, UserManager<AdminUser>
return errors;
}
- /// <summary>
- /// Checks if supplied password is correct for the user.
- /// </summary>
- /// <param name="user">User object.</param>
- /// <param name="password">The password to check.</param>
- /// <returns>Boolean indicating whether supplied password is valid and matches what is stored in the database..</returns>
- public async Task<bool> CheckPasswordAsync(AdminUser user, string password)
- {
- if (password.Length == 0)
- {
- return false;
- }
-
- return await userManager.CheckPasswordAsync(user, password);
- }
-
/// <summary>
/// Validate if user object contents conform to the requirements.
/// </summary>
diff --git a/src/AliasVault.Api/Controllers/Abstracts/AuthenticatedRequestController.cs b/src/AliasVault.Api/Controllers/Abstracts/AuthenticatedRequestController.cs
index 62ec18bb6..35d6b0f0c 100644
--- a/src/AliasVault.Api/Controllers/Abstracts/AuthenticatedRequestController.cs
+++ b/src/AliasVault.Api/Controllers/Abstracts/AuthenticatedRequestController.cs
@@ -14,7 +14,7 @@ using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
/// <summary>
-/// Base controller for requests that require authentication.
+/// Base controller that concrete controllers can extend from if all requests require authentication.
/// </summary>
/// <param name="userManager">UserManager instance.</param>
[Route("api/v{version:apiVersion}/[controller]")]
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index b47a35ecd..53d8591f9 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -36,7 +36,7 @@ using SecureRemotePassword;
/// <param name="userManager">UserManager instance.</param>
/// <param name="signInManager">SignInManager instance.</param>
/// <param name="configuration">IConfiguration instance.</param>
-/// <param name="cache">IMemoryCache instance for persisting SRP values during multi-step login process.</param>
+/// <param name="cache">IMemoryCache instance for persisting SRP values during multistep login process.</param>
/// <param name="timeProvider">ITimeProvider instance. This returns the time which can be mutated for testing.</param>
/// <param name="authLoggingService">AuthLoggingService instance. This is used to log auth attempts to the database.</param>
[Route("api/v{version:apiVersion}/[controller]")]
@@ -67,7 +67,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
/// <summary>
/// Semaphore to prevent concurrent access to the database when generating new tokens for a user.
/// </summary>
- private static readonly SemaphoreSlim _semaphore = new(1, 1);
+ private static readonly SemaphoreSlim Semaphore = new(1, 1);
/// <summary>
/// Status endpoint called by client to check if user is still authenticated.
@@ -140,7 +140,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
// If 2FA is not required, then it means the user is successfully authenticated at this point.
// Reset failed login attempts.
- await userManager.ResetAccessFailedCountAsync(user!);
+ await userManager.ResetAccessFailedCountAsync(user);
var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
@@ -186,7 +186,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
// Generate and return the JWT token.
var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: model.RememberMe);
- return Ok(new ValidateLoginResponse(false, serverSession!.Proof, tokenModel));
+ return Ok(new ValidateLoginResponse(false, serverSession.Proof, tokenModel));
}
/// <summary>
@@ -526,14 +526,14 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetJwtKey()));
- var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
+ var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: configuration["Jwt:Issuer"] ?? string.Empty,
audience: configuration["Jwt:Issuer"] ?? string.Empty,
claims: claims,
expires: timeProvider.UtcNow.AddMinutes(10),
- signingCredentials: creds);
+ signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
@@ -548,7 +548,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- await _semaphore.WaitAsync();
+ await Semaphore.WaitAsync();
try
{
// Determine the refresh token lifetime.
@@ -565,7 +565,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
}
finally
{
- _semaphore.Release();
+ Semaphore.Release();
}
}
@@ -579,7 +579,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
private async Task<TokenModel> GenerateNewTokensForUser(AliasVaultUser user, AliasVaultUserRefreshToken existingToken)
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- await _semaphore.WaitAsync();
+ await Semaphore.WaitAsync();
try
{
@@ -618,7 +618,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
}
finally
{
- _semaphore.Release();
+ Semaphore.Release();
}
}
diff --git a/src/AliasVault.Api/Controllers/Email/EmailBoxController.cs b/src/AliasVault.Api/Controllers/Email/EmailBoxController.cs
index 9ff1a2662..3464048a5 100644
--- a/src/AliasVault.Api/Controllers/Email/EmailBoxController.cs
+++ b/src/AliasVault.Api/Controllers/Email/EmailBoxController.cs
@@ -9,7 +9,6 @@ namespace AliasVault.Api.Controllers.Email;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
-using AliasVault.Api.Helpers;
using AliasVault.Shared.Models.Spamok;
using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Models.WebApi.Email;
@@ -19,7 +18,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// Email controller for retrieving emails from the database.
+/// Email controller for retrieving emailboxes from the database.
/// </summary>
/// <param name="dbContextFactory">DbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
@@ -93,10 +92,12 @@ public class EmailBoxController(IDbContextFactory<AliasServerDbContext> dbContex
.Take(50)
.ToListAsync();
- MailboxApiModel returnValue = new MailboxApiModel();
- returnValue.Address = to;
- returnValue.Subscribed = false;
- returnValue.Mails = emails;
+ var returnValue = new MailboxApiModel
+ {
+ Address = to,
+ Subscribed = false,
+ Mails = emails,
+ };
return Ok(returnValue);
}
diff --git a/src/AliasVault.Api/Controllers/Email/EmailController.cs b/src/AliasVault.Api/Controllers/Email/EmailController.cs
index 0022e662b..2c7115755 100644
--- a/src/AliasVault.Api/Controllers/Email/EmailController.cs
+++ b/src/AliasVault.Api/Controllers/Email/EmailController.cs
@@ -9,7 +9,6 @@ namespace AliasVault.Api.Controllers.Email;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
-using AliasVault.Api.Helpers;
using AliasVault.Shared.Models.Spamok;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
diff --git a/src/AliasVault.Api/Controllers/RootController.cs b/src/AliasVault.Api/Controllers/RootController.cs
index 9897be395..2244698cf 100644
--- a/src/AliasVault.Api/Controllers/RootController.cs
+++ b/src/AliasVault.Api/Controllers/RootController.cs
@@ -41,7 +41,7 @@ public class RootController(IDbContextFactory<AliasServerDbContext> dbContextFac
return StatusCode(500, "There are pending migrations. Please run 'dotnet ef database update' to apply them.");
}
- // Database is up to date
+ // Database is up-to-date
return Ok("OK");
}
catch
diff --git a/src/AliasVault.Api/Controllers/Security/TwoFactorAuthController.cs b/src/AliasVault.Api/Controllers/Security/TwoFactorAuthController.cs
index 71de34948..8e978326e 100644
--- a/src/AliasVault.Api/Controllers/Security/TwoFactorAuthController.cs
+++ b/src/AliasVault.Api/Controllers/Security/TwoFactorAuthController.cs
@@ -18,7 +18,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// Auth controller for handling authentication.
+/// Two-factor authentication controller for handling two-factor authentication related actions.
/// </summary>
/// <param name="dbContextFactory">AliasServerDbContext instance.</param>
/// <param name="urlEncoder">UrlEncoder instance.</param>
diff --git a/src/AliasVault.Api/Vault/RetentionPolicy.cs b/src/AliasVault.Api/Vault/RetentionPolicy.cs
index 4799fcd67..74e682eae 100644
--- a/src/AliasVault.Api/Vault/RetentionPolicy.cs
+++ b/src/AliasVault.Api/Vault/RetentionPolicy.cs
@@ -15,7 +15,7 @@ using AliasVault.Api.Vault.RetentionRules;
public class RetentionPolicy
{
/// <summary>
- /// Gets or sets the rules that this policy consists of.
+ /// Gets the rules that this policy consists of.
/// </summary>
- public List<IRetentionRule> Rules { get; set; } = new();
+ public List<IRetentionRule> Rules { get; init; } = [];
}
diff --git a/src/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs
index f0364ef2d..fbfbc0076 100644
--- a/src/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs
+++ b/src/AliasVault.Api/Vault/RetentionRules/DailyRetentionRule.cs
@@ -15,9 +15,9 @@ using AliasServerDb;
public class DailyRetentionRule : IRetentionRule
{
/// <summary>
- /// Gets or sets amount of days to keep vault.
+ /// Gets the amount of days to keep vault.
/// </summary>
- public int DaysToKeep { get; set; }
+ public int DaysToKeep { get; init; }
/// <inheritdoc cref="IRetentionRule.ApplyRule"/>
public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
diff --git a/src/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs
index 5c4390c8c..c660f9823 100644
--- a/src/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs
+++ b/src/AliasVault.Api/Vault/RetentionRules/DbVersionRetentionRule.cs
@@ -15,9 +15,9 @@ using AliasServerDb;
public class DbVersionRetentionRule : IRetentionRule
{
/// <summary>
- /// Gets or sets amount of db versions to keep the vault.
+ /// Gets the amount of db versions to keep the vault.
/// </summary>
- public int VersionsToKeep { get; set; }
+ public int VersionsToKeep { get; init; }
/// <inheritdoc cref="IRetentionRule.ApplyRule"/>
public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
diff --git a/src/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs
index 631be2ee1..8ae9ca0a5 100644
--- a/src/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs
+++ b/src/AliasVault.Api/Vault/RetentionRules/MonthlyRetentionRule.cs
@@ -15,9 +15,9 @@ using AliasServerDb;
public class MonthlyRetentionRule : IRetentionRule
{
/// <summary>
- /// Gets or sets amount of months to keep vault.
+ /// Gets the amount of months to keep vault.
/// </summary>
- public int MonthsToKeep { get; set; }
+ public int MonthsToKeep { get; init; }
/// <inheritdoc cref="IRetentionRule.ApplyRule"/>
public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
diff --git a/src/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs
index eef5081df..e9ce0f16e 100644
--- a/src/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs
+++ b/src/AliasVault.Api/Vault/RetentionRules/RevisionRetentionRule.cs
@@ -15,9 +15,9 @@ using AliasServerDb;
public class RevisionRetentionRule : IRetentionRule
{
/// <summary>
- /// Gets or sets amount of revisions to keep the vault.
+ /// Gets the amount of revisions to keep the vault.
/// </summary>
- public int RevisionsToKeep { get; set; }
+ public int RevisionsToKeep { get; init; }
/// <inheritdoc cref="IRetentionRule.ApplyRule"/>
public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
diff --git a/src/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs b/src/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs
index 7ce82d44a..f1ad6d79d 100644
--- a/src/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs
+++ b/src/AliasVault.Api/Vault/RetentionRules/WeeklyRetentionRule.cs
@@ -15,9 +15,9 @@ using AliasServerDb;
public class WeeklyRetentionRule : IRetentionRule
{
/// <summary>
- /// Gets or sets amount of weeks to keep vault.
+ /// Gets the amount of weeks to keep vault.
/// </summary>
- public int WeeksToKeep { get; set; }
+ public int WeeksToKeep { get; init; }
/// <inheritdoc cref="IRetentionRule.ApplyRule"/>
public IEnumerable<Vault> ApplyRule(List<Vault> vaults, DateTime now)
diff --git a/src/AliasVault.Api/Vault/VaultRetentionManager.cs b/src/AliasVault.Api/Vault/VaultRetentionManager.cs
index f8ae0cb58..050f453ce 100644
--- a/src/AliasVault.Api/Vault/VaultRetentionManager.cs
+++ b/src/AliasVault.Api/Vault/VaultRetentionManager.cs
@@ -14,7 +14,7 @@ using AliasServerDb;
/// <summary>
/// History manager for vaults that keeps track of vault history and applies retention rules to
-/// determine how many vaults to keep as backups and automatically deletes vaults that do no
+/// determine how many vaults to keep as backups and automatically deletes vaults that do not
/// match the applied retention policies.
/// </summary>
public static class VaultRetentionManager
@@ -51,7 +51,7 @@ public static class VaultRetentionManager
}
// Always keep the most recent vault
- if (existingVaults.Count > 0 && !vaultsToKeep.Contains(existingVaults[0]))
+ if (existingVaults.Count > 0)
{
vaultsToKeep.Add(existingVaults[0]);
}
diff --git a/src/AliasVault.Client/Services/Auth/AuthService.cs b/src/AliasVault.Client/Services/Auth/AuthService.cs
index 7c505c36f..456e53b3e 100644
--- a/src/AliasVault.Client/Services/Auth/AuthService.cs
+++ b/src/AliasVault.Client/Services/Auth/AuthService.cs
@@ -91,15 +91,6 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
await localStorage.SetItemAsStringAsync(AccessTokenKey, newToken);
}
- /// <summary>
- /// Retrieves the stored refresh token asynchronously.
- /// </summary>
- /// <returns>The stored refresh token.</returns>
- public async Task<string> GetRefreshTokenAsync()
- {
- return await localStorage.GetItemAsStringAsync(RefreshTokenKey) ?? string.Empty;
- }
-
/// <summary>
/// Get encryption key.
/// </summary>
@@ -162,8 +153,8 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
/// <summary>
/// Check if the encryption test string is stored in local storage which is used to validate
- /// the encryption key locally during future vault unlocks. If its not stored the unlock
- /// attempts will fail and user should login again instead.
+ /// the encryption key locally during future vault unlocks. If it's not stored the unlock
+ /// attempts will fail and user should log in again instead.
/// </summary>
/// <returns>Task.</returns>
public async Task<bool> HasEncryptionKeyTestStringAsync()
@@ -262,4 +253,13 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca
request.Headers.Add("X-Ignore-Failure", "true");
await httpClient.SendAsync(request);
}
+
+ /// <summary>
+ /// Retrieves the stored refresh token asynchronously.
+ /// </summary>
+ /// <returns>The stored refresh token.</returns>
+ private async Task<string> GetRefreshTokenAsync()
+ {
+ return await localStorage.GetItemAsStringAsync(RefreshTokenKey) ?? string.Empty;
+ }
}
diff --git a/src/AliasVault.Client/Services/ClipboardCopyService.cs b/src/AliasVault.Client/Services/ClipboardCopyService.cs
index ea421e995..8b69965dd 100644
--- a/src/AliasVault.Client/Services/ClipboardCopyService.cs
+++ b/src/AliasVault.Client/Services/ClipboardCopyService.cs
@@ -17,7 +17,7 @@ public sealed class ClipboardCopyService
/// <summary>
/// Event to notify the application that an item has been copied.
/// </summary>
- public event Action<string> OnCopy = null!;
+ public event Action<string>? OnCopy;
/// <summary>
/// Keep track of the last copied item.
diff --git a/src/AliasVault.Client/Services/CredentialService.cs b/src/AliasVault.Client/Services/CredentialService.cs
index df78395ab..23adaac54 100644
--- a/src/AliasVault.Client/Services/CredentialService.cs
+++ b/src/AliasVault.Client/Services/CredentialService.cs
@@ -21,7 +21,7 @@ using AliasVault.Shared.Models.WebApi.Favicon;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// Service class for alias operations.
+/// Service class for credential operations.
/// </summary>
public sealed class CredentialService(HttpClient httpClient, DbService dbService, Config config)
{
@@ -366,12 +366,12 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
var url = credentialObject.Service.Url;
if (url != null && !string.IsNullOrEmpty(url) && url.Contains("http"))
{
- // Request favicon from from service URL via WebApi
+ // Request favicon from service URL via WebApi
try
{
var apiReturn =
await httpClient.GetFromJsonAsync<FaviconExtractModel>($"api/v1/Favicon/Extract?url={url}");
- if (apiReturn != null && apiReturn.Image != null)
+ if (apiReturn?.Image is not null)
{
credentialObject.Service.Logo = apiReturn.Image;
}
diff --git a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs b/src/AliasVault.Client/Services/Database/DbMergeUtility.cs
index 42266ce17..990c93e0e 100644
--- a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs
+++ b/src/AliasVault.Client/Services/Database/DbMergeUtility.cs
@@ -24,9 +24,9 @@ public static class DbMergeUtility
public static async Task<List<string>> GetTableNames(SqliteConnection connection)
{
var tables = new List<string>();
- using var command = connection.CreateCommand();
+ await using var command = connection.CreateCommand();
command.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';";
- using var reader = await command.ExecuteReaderAsync();
+ await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
tables.Add(reader.GetString(0));
@@ -44,14 +44,14 @@ public static class DbMergeUtility
/// <returns>Task.</returns>
public static async Task MergeTable(SqliteConnection baseConnection, SqliteConnection sourceConnection, string tableName)
{
- using var baseCommand = baseConnection.CreateCommand();
- using var sourceCommand = sourceConnection.CreateCommand();
+ await using var baseCommand = baseConnection.CreateCommand();
+ await using var sourceCommand = sourceConnection.CreateCommand();
baseCommand.CommandText = $"PRAGMA table_info({tableName})";
var columns = new List<string>();
// Get column names from the base table.
- using (var reader = await baseCommand.ExecuteReaderAsync())
+ await using (var reader = await baseCommand.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
@@ -69,7 +69,7 @@ public static class DbMergeUtility
// Get all records from the source table.
sourceCommand.CommandText = $"SELECT * FROM {tableName}";
- using var sourceReader = await sourceCommand.ExecuteReaderAsync();
+ await using var sourceReader = await sourceCommand.ExecuteReaderAsync();
Console.WriteLine($"Got records for {tableName}.");
@@ -115,21 +115,19 @@ public static class DbMergeUtility
}
/// <summary>
- /// Updates a record in the specified table with data from the source reader.
+ /// Inserts a new record into the specified table with data from the source reader.
/// </summary>
/// <param name="connection">The SQLite connection to use.</param>
- /// <param name="tableName">The name of the table to update.</param>
+ /// <param name="tableName">The name of the table to insert into.</param>
/// <param name="sourceReader">The data reader containing the source record.</param>
/// <param name="columns">The list of column names in the table.</param>
/// <returns>Task.</returns>
- public static async Task UpdateRecord(SqliteConnection connection, string tableName, SqliteDataReader sourceReader, List<string> columns)
+ private static async Task InsertRecord(SqliteConnection connection, string tableName, SqliteDataReader sourceReader, List<string> columns)
{
- using var command = connection.CreateCommand();
- var updateColumns = string.Join(", ", columns.Select(c => $"{c} = @{c}"));
- command.CommandText = $"UPDATE {tableName} SET {updateColumns} WHERE Id = @Id";
-
- Console.WriteLine($"Updating record in {tableName}.");
- Console.WriteLine($"Command: {command.CommandText}");
+ await using var command = connection.CreateCommand();
+ var columnNames = string.Join(", ", columns);
+ var parameterNames = string.Join(", ", columns.Select(c => $"@{c}"));
+ command.CommandText = $"INSERT INTO {tableName} ({columnNames}) VALUES ({parameterNames})";
for (int i = 0; i < columns.Count; i++)
{
@@ -140,19 +138,21 @@ public static class DbMergeUtility
}
/// <summary>
- /// Inserts a new record into the specified table with data from the source reader.
+ /// Updates a record in the specified table with data from the source reader.
/// </summary>
/// <param name="connection">The SQLite connection to use.</param>
- /// <param name="tableName">The name of the table to insert into.</param>
+ /// <param name="tableName">The name of the table to update.</param>
/// <param name="sourceReader">The data reader containing the source record.</param>
/// <param name="columns">The list of column names in the table.</param>
/// <returns>Task.</returns>
- public static async Task InsertRecord(SqliteConnection connection, string tableName, SqliteDataReader sourceReader, List<string> columns)
+ private static async Task UpdateRecord(SqliteConnection connection, string tableName, SqliteDataReader sourceReader, List<string> columns)
{
- using var command = connection.CreateCommand();
- var columnNames = string.Join(", ", columns);
- var parameterNames = string.Join(", ", columns.Select(c => $"@{c}"));
- command.CommandText = $"INSERT INTO {tableName} ({columnNames}) VALUES ({parameterNames})";
+ await using var command = connection.CreateCommand();
+ var updateColumns = string.Join(", ", columns.Select(c => $"{c} = @{c}"));
+ command.CommandText = $"UPDATE {tableName} SET {updateColumns} WHERE Id = @Id";
+
+ Console.WriteLine($"Updating record in {tableName}.");
+ Console.WriteLine($"Command: {command.CommandText}");
for (int i = 0; i < columns.Count; i++)
{
diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.cs
index edb99e730..930545d0e 100644
--- a/src/AliasVault.Client/Services/Database/DbService.cs
+++ b/src/AliasVault.Client/Services/Database/DbService.cs
@@ -30,7 +30,7 @@ public sealed class DbService : IDisposable
private readonly Config _config;
private readonly SettingsService _settingsService = new();
private readonly GlobalNotificationService _globalNotificationService;
- private SqliteConnection _sqlConnection;
+ private SqliteConnection? _sqlConnection;
private AliasClientDbContext _dbContext;
private long _vaultRevisionNumber;
private bool _isSuccessfullyInitialized;
@@ -127,20 +127,18 @@ public sealed class DbService : IDisposable
}
// Get all table names from the current base database.
- var tables = await DbMergeUtility.GetTableNames(_sqlConnection);
+ var tables = await DbMergeUtility.GetTableNames(_sqlConnection!);
// Disable foreign key checks on the base connection.
- await using (var command = _sqlConnection.CreateCommand())
+ await using (var command = _sqlConnection!.CreateCommand())
{
command.CommandText = "PRAGMA foreign_keys = OFF;";
await command.ExecuteNonQueryAsync();
}
// Merge each database into the base.
- var i = 0;
foreach (var connection in sqlConnections)
{
- i++;
foreach (var table in tables)
{
Console.WriteLine($"Merging table {table}.");
@@ -156,7 +154,7 @@ public sealed class DbService : IDisposable
// Verify foreign key integrity.
command.CommandText = "PRAGMA foreign_key_check;";
- using var reader = await command.ExecuteReaderAsync();
+ await using var reader = await command.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
// Foreign key violation detected.
@@ -165,7 +163,7 @@ public sealed class DbService : IDisposable
}
}
- // Update the dbcontext with the new merged database.
+ // Update the db context with the new merged database.
_dbContext = new AliasClientDbContext(_sqlConnection, log => Console.WriteLine(log));
// Clean up other connections.
@@ -200,7 +198,7 @@ public sealed class DbService : IDisposable
"The automatic merge was unsuccessful, possibly due to a password change or vault upgrade. " +
"Please log out and log back in to retrieve the latest version of your vault.");
Console.WriteLine($"Error merging databases: {ex.Message}");
- _state.UpdateState(DbServiceState.DatabaseStatus.MergeFailed, $"Error merging databases: {ex.Message}");
+ _state.UpdateState(DbServiceState.DatabaseStatus.Ready);
return false;
}
}
@@ -277,7 +275,7 @@ public sealed class DbService : IDisposable
// Export SQLite memory database to a temp file.
using var memoryStream = new MemoryStream();
- using var command = _sqlConnection.CreateCommand();
+ await using var command = _sqlConnection!.CreateCommand();
command.CommandText = "VACUUM main INTO @fileName";
command.Parameters.Add(new SqliteParameter("@fileName", tempFileName));
await command.ExecuteNonQueryAsync();
@@ -295,7 +293,7 @@ public sealed class DbService : IDisposable
/// <summary>
/// Migrate the database structure to the latest version.
/// </summary>
- /// <returns>Bool which indicates if migration was succesful.</returns>
+ /// <returns>Bool which indicates if migration was successful.</returns>
public async Task<bool> MigrateDatabaseAsync()
{
try
@@ -396,9 +394,10 @@ public sealed class DbService : IDisposable
/// <returns>SqliteConnection and AliasClientDbContext.</returns>
public (SqliteConnection SqliteConnection, AliasClientDbContext AliasClientDbContext) InitializeEmptyDatabase()
{
- if (_sqlConnection is not null && _sqlConnection.State == ConnectionState.Open)
+ if (_sqlConnection?.State == ConnectionState.Open)
{
_sqlConnection.Close();
+ _sqlConnection.Dispose();
}
_sqlConnection = new SqliteConnection("Data Source=:memory:");
@@ -413,41 +412,13 @@ public sealed class DbService : IDisposable
return (_sqlConnection, _dbContext);
}
- /// <summary>
- /// Implements the IDisposable interface.
- /// </summary>
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// Disposes the service.
- /// </summary>
- /// <param name="disposing">True if disposing.</param>
- public void Dispose(bool disposing)
- {
- if (_disposed)
- {
- return;
- }
-
- if (disposing)
- {
- _sqlConnection.Dispose();
- }
-
- _disposed = true;
- }
-
/// <summary>
/// Get a list of private email addresses that are used in aliases by this vault.
/// </summary>
/// <returns>List of email addresses.</returns>
public async Task<List<string>> GetEmailClaimListAsync()
{
- // Send list of email addresses that are used in aliases by this vault so they can be
+ // Send list of email addresses that are used in aliases by this vault, so they can be
// claimed on the server.
var emailAddresses = await _dbContext.Aliases
.Where(a => a.Email != null)
@@ -465,6 +436,15 @@ public sealed class DbService : IDisposable
return emailAddresses;
}
+ /// <summary>
+ /// Implements the IDisposable interface.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
/// <summary>
/// Loads a SQLite database from a base64 string which represents a .sqlite file.
/// </summary>
@@ -476,7 +456,7 @@ public sealed class DbService : IDisposable
var tempFileName = Path.GetRandomFileName();
await File.WriteAllBytesAsync(tempFileName, bytes);
- using (var command = connection.CreateCommand())
+ await using (var command = connection.CreateCommand())
{
// Disable foreign key constraints
command.CommandText = "PRAGMA foreign_keys = OFF;";
@@ -488,7 +468,7 @@ public sealed class DbService : IDisposable
FROM sqlite_master
WHERE type = 'table' AND name NOT LIKE 'sqlite_%';";
var dropTableCommands = new List<string>();
- using (var reader = await command.ExecuteReaderAsync())
+ await using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
@@ -513,7 +493,7 @@ public sealed class DbService : IDisposable
FROM importDb.sqlite_master
WHERE type = 'table' AND name NOT LIKE 'sqlite_%';";
var createTableCommands = new List<string>();
- using (var reader = await command.ExecuteReaderAsync())
+ await using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
@@ -534,7 +514,7 @@ public sealed class DbService : IDisposable
FROM importDb.sqlite_master
WHERE type = 'table' AND name NOT LIKE 'sqlite_%';";
var tableInsertCommands = new List<string>();
- using (var reader = await command.ExecuteReaderAsync())
+ await using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
@@ -594,7 +574,7 @@ public sealed class DbService : IDisposable
// Attempt to decrypt the database blob.
string decryptedBase64String = await _jsInteropService.SymmetricDecrypt(vault.Blob, _authService.GetEncryptionKeyAsBase64Async());
- await ImportDbContextFromBase64Async(decryptedBase64String, _sqlConnection);
+ await ImportDbContextFromBase64Async(decryptedBase64String, _sqlConnection!);
// Check if database is up-to-date with migrations.
var pendingMigrations = await _dbContext.Database.GetPendingMigrationsAsync();
@@ -735,4 +715,23 @@ public sealed class DbService : IDisposable
await SaveDatabaseAsync();
}
}
+
+ /// <summary>
+ /// Disposes the service.
+ /// </summary>
+ /// <param name="disposing">True if disposing.</param>
+ private void Dispose(bool disposing)
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ if (disposing)
+ {
+ _sqlConnection?.Dispose();
+ }
+
+ _disposed = true;
+ }
}
diff --git a/src/AliasVault.Client/Services/Database/DbServiceState.cs b/src/AliasVault.Client/Services/Database/DbServiceState.cs
index 53ff29834..d1dbcfa12 100644
--- a/src/AliasVault.Client/Services/Database/DbServiceState.cs
+++ b/src/AliasVault.Client/Services/Database/DbServiceState.cs
@@ -8,7 +8,7 @@
namespace AliasVault.Client.Services.Database;
/// <summary>
-/// Class to manage the state of the AliasClientDbService that others can subscribe to events for.
+/// Class to manage the state of the DbService that others can subscribe to events for.
/// </summary>
public sealed class DbServiceState
{
@@ -45,11 +45,6 @@ public sealed class DbServiceState
/// </summary>
MergeRequired,
- /// <summary>
- /// Database is being merged.
- /// </summary>
- Merging,
-
/// <summary>
/// Database merge failed.
/// </summary>
@@ -74,11 +69,6 @@ public sealed class DbServiceState
/// Database is saving to server.
/// </summary>
SavingToServer,
-
- /// <summary>
- /// An error occurred during a database operation.
- /// </summary>
- OperationError,
}
/// <summary>
@@ -156,20 +146,12 @@ public sealed class DbServiceState
public DateTime LastUpdated { get; set; } = DateTime.Now;
/// <summary>
- /// Returns true if the database state represents a initialized state.
+ /// Returns true if the database state represents an initialized state.
/// </summary>
/// <returns>Bool.</returns>
public bool IsInitialized()
{
- if (Status == DatabaseStatus.Uninitialized ||
- Status == DatabaseStatus.PendingMigrations ||
- Status == DatabaseStatus.Loading ||
- Status == DatabaseStatus.DecryptionFailed)
- {
- return false;
- }
-
- return true;
+ return Status is DatabaseStatus.Ready or DatabaseStatus.SavingToServer;
}
}
}
diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.cs
index aa6ba4d9c..535a6f97e 100644
--- a/src/AliasVault.Client/Services/JsInteropService.cs
+++ b/src/AliasVault.Client/Services/JsInteropService.cs
@@ -75,7 +75,7 @@ public sealed class JsInteropService(IJSRuntime jsRuntime)
await jsRuntime.InvokeVoidAsync("blurElement", elementId);
/// <summary>
- /// Copy a string to the browsers clipboard.
+ /// Copy a string to the browser's clipboard.
/// </summary>
/// <param name="value">Value to copy to clipboard.</param>
/// <returns>Task.</returns>
diff --git a/src/AliasVault.Client/Services/KeyboardShortcutService.cs b/src/AliasVault.Client/Services/KeyboardShortcutService.cs
index 0bcac55fc..26fa4c64a 100644
--- a/src/AliasVault.Client/Services/KeyboardShortcutService.cs
+++ b/src/AliasVault.Client/Services/KeyboardShortcutService.cs
@@ -13,7 +13,7 @@ using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
/// <summary>
-/// Service class for alias operations.
+/// Service to manage and act on keyboard shortcuts across the application.
/// </summary>
public sealed class KeyboardShortcutService : IAsyncDisposable
{
@@ -21,7 +21,7 @@ public sealed class KeyboardShortcutService : IAsyncDisposable
private readonly NavigationManager _navigationManager;
private readonly DbService _dbService;
private readonly AuthService _authService;
- private readonly Lazy<Task<IJSObjectReference>> moduleTask;
+ private readonly Lazy<Task<IJSObjectReference>> _moduleTask;
/// <summary>
/// Initializes a new instance of the <see cref="KeyboardShortcutService"/> class.
@@ -37,7 +37,7 @@ public sealed class KeyboardShortcutService : IAsyncDisposable
_dbService = dbService;
_authService = authService;
- moduleTask = new Lazy<Task<IJSObjectReference>>(() => jsRuntime.InvokeAsync<IJSObjectReference>(
+ _moduleTask = new Lazy<Task<IJSObjectReference>>(() => jsRuntime.InvokeAsync<IJSObjectReference>(
"import", "./js/modules/keyboardShortcuts.js").AsTask());
_ = RegisterStaticShortcuts();
@@ -52,7 +52,7 @@ public sealed class KeyboardShortcutService : IAsyncDisposable
public async Task RegisterShortcutAsync(string keys, Func<Task> callback)
{
_dotNetHelper.Value.RegisterCallback(keys, callback);
- var module = await moduleTask.Value;
+ var module = await _moduleTask.Value;
await module.InvokeVoidAsync("registerShortcut", keys, _dotNetHelper);
}
@@ -64,8 +64,8 @@ public sealed class KeyboardShortcutService : IAsyncDisposable
public async Task UnregisterShortcutAsync(string keys)
{
_dotNetHelper.Value.UnregisterCallback(keys);
- var module = await moduleTask.Value;
- await module!.InvokeVoidAsync("unregisterShortcut", keys);
+ var module = await _moduleTask.Value;
+ await module.InvokeVoidAsync("unregisterShortcut", keys);
}
/// <summary>
@@ -74,12 +74,11 @@ public sealed class KeyboardShortcutService : IAsyncDisposable
/// <returns>ValueTask.</returns>
public async ValueTask DisposeAsync()
{
- var module = await moduleTask.Value;
+ var module = await _moduleTask.Value;
await module.InvokeVoidAsync("unregisterAllShortcuts");
await module.DisposeAsync();
_dotNetHelper.Dispose();
- GC.SuppressFinalize(this);
}
/// <summary>
diff --git a/src/AliasVault.Client/Services/SettingsService.cs b/src/AliasVault.Client/Services/SettingsService.cs
index a54b076be..a02946267 100644
--- a/src/AliasVault.Client/Services/SettingsService.cs
+++ b/src/AliasVault.Client/Services/SettingsService.cs
@@ -36,7 +36,7 @@ public sealed class SettingsService
/// Gets a value indicating whether email refresh should be done automatically on the credentials page.
/// </summary>
/// <returns>AutoEmailRefresh setting as string.</returns>
- public bool AutoEmailRefresh => GetSetting<bool>("AutoEmailRefresh", true);
+ public bool AutoEmailRefresh => GetSetting("AutoEmailRefresh", true);
/// <summary>
/// Gets the DefaultIdentityLanguage setting.
@@ -56,7 +56,7 @@ public sealed class SettingsService
/// </summary>
/// <param name="value">The new value.</param>
/// <returns>Task.</returns>
- public Task SetAutoEmailRefresh(bool value) => SetSettingAsync<bool>("AutoEmailRefresh", value);
+ public Task SetAutoEmailRefresh(bool value) => SetSettingAsync("AutoEmailRefresh", value);
/// <summary>
/// Sets the DefaultIdentityLanguage setting.
@@ -95,7 +95,7 @@ public sealed class SettingsService
/// </summary>
/// <param name="value">Value (string) to cast.</param>
/// <typeparam name="T">Type to cast it to.</typeparam>
- /// <returns>The value casted to the requested type.</returns>
+ /// <returns>The value cast to the requested type.</returns>
private static T? CastSetting<T>(string value)
{
if (string.IsNullOrEmpty(value))
diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index e120c5159..11bda9e82 100644
--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -138,35 +138,33 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
catch
{
- // If this fails, then simply use a blank value
+ // If this fails, then simply use a blank value.
fromLocal = string.Empty;
fromDomain = string.Empty;
}
- // Create email object
- var email = new Email();
- email.From = from;
- email.FromLocal = fromLocal.ToLower();
- email.FromDomain = fromDomain.ToLower();
-
- // Local part to lowercase, as mailboxes are always lowercase
- email.To = toAddress.Address.ToLower();
- email.ToLocal = toAddress.User.ToLower();
- email.ToDomain = toAddress.Host.ToLower();
-
- email.Subject = message.Subject ?? string.Empty;
- email.MessageHtml = message.HtmlBody;
- email.MessagePlain = message.TextBody;
- email.MessageSource = message.ToString();
+ // Create email object.
+ var email = new Email
+ {
+ From = from,
+ FromLocal = fromLocal.ToLower(),
+ FromDomain = fromDomain.ToLower(),
+ To = toAddress.Address.ToLower(),
+ ToLocal = toAddress.User.ToLower(),
+ ToDomain = toAddress.Host.ToLower(),
+ Subject = message.Subject ?? string.Empty,
+ MessageHtml = message.HtmlBody,
+ MessagePlain = message.TextBody,
+ MessageSource = message.ToString(),
+ Date = message.Date.DateTime,
+ DateSystem = DateTime.UtcNow,
+ Visible = true,
+ };
- // Extract message preview text based on body contents.
+ // Extract a preview of the email message body to be used in the email listing preview in the UI.
email.MessagePreview = ExtractMessagePreview(email);
- email.Date = message.Date.DateTime;
- email.DateSystem = DateTime.UtcNow;
- email.Visible = true;
-
- // Parse attachments from email, and create separate attachment records in database for each attachment
+ // Parse attachments from email, and create separate attachment records in database for each attachment.
foreach (var attachment in message.Attachments)
{
var emailAttachment = CreateEmailAttachment(attachment);
@@ -235,7 +233,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
catch
{
- // Extracting useful words from email failed.. Skip the step, do nothing..
+ // Extracting useful words from email failed. Skip the step, do nothing.
}
return messagePreview;
@@ -267,19 +265,18 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
/// <returns>Attachment byte array.</returns>
private static byte[] GetAttachmentBytes(MimeEntity attachment)
{
- using (var memory = new MemoryStream())
- {
- if (attachment is MimePart mimePartAttachment)
- {
- mimePartAttachment.Content.DecodeTo(memory);
- }
- else
- {
- ((MessagePart)attachment).Message.WriteTo(memory);
- }
+ using var memory = new MemoryStream();
- return memory.ToArray();
+ if (attachment is MimePart mimePartAttachment)
+ {
+ mimePartAttachment.Content.DecodeTo(memory);
}
+ else
+ {
+ ((MessagePart)attachment).Message.WriteTo(memory);
+ }
+
+ return memory.ToArray();
}
/// <summary>
@@ -313,7 +310,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
if (userEmailClaim is null)
{
- // Email address has no user claim with corresponding encryption key so we cannot process it.
+ // Email address has no user claim with corresponding encryption key, so we cannot process it.
logger.LogWarning(
"Rejected email: email for {ToAddress} is not allowed. No user claim on this ToAddress.",
toAddress.User + "@" + toAddress.Host);
@@ -328,7 +325,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
if (userPublicKey is null)
{
- // Email address has no user claim with corresponding encryption key so we cannot process it.
+ // Email address has no user claim with corresponding encryption key, so we cannot process it.
logger.LogCritical(
"Rejected email: email for {ToAddress} cannot be processed. No primary encryption key found for this user.",
toAddress.User + "@" + toAddress.Host);
diff --git a/src/Services/AliasVault.SmtpService/Program.cs b/src/Services/AliasVault.SmtpService/Program.cs
index 47ff04a5b..0659c9519 100644
--- a/src/Services/AliasVault.SmtpService/Program.cs
+++ b/src/Services/AliasVault.SmtpService/Program.cs
@@ -5,7 +5,6 @@
// </copyright>
//-----------------------------------------------------------------------
-using System.Data.Common;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using AliasServerDb;
@@ -15,7 +14,6 @@ using AliasVault.SmtpService;
using AliasVault.SmtpService.Handlers;
using AliasVault.SmtpService.Workers;
using AliasVault.WorkerStatus.ServiceExtensions;
-using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using SmtpServer;
using SmtpServer.Storage;
diff --git a/src/Utilities/AliasVault.Auth/AuthLoggingService.cs b/src/Utilities/AliasVault.Auth/AuthLoggingService.cs
index c186ef490..adffeb5c6 100644
--- a/src/Utilities/AliasVault.Auth/AuthLoggingService.cs
+++ b/src/Utilities/AliasVault.Auth/AuthLoggingService.cs
@@ -13,7 +13,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
/// <summary>
-/// User service for managing users.
+/// Auth logging service for logging authentication events such as user login attempts.
/// </summary>
/// <param name="serviceProvider">IServiceProvider instance.</param>
/// <param name="httpContextAccessor">IHttpContextAccessor instance.</param>