Skip to content

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

Add email delete option to email modal (#184)

Leendert de Borst466c181ad176
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index 9fe97dba0..b8fe5f61d 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -240,7 +240,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
var newRefreshToken = GenerateRefreshToken();
// Add new refresh token.
- await context.AliasVaultUserRefreshTokens.AddAsync(new AliasVaultUserRefreshToken
+ context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken
{
UserId = user.Id,
DeviceIdentifier = deviceIdentifier,
@@ -526,7 +526,7 @@ public class AuthController(IDbContextFactory<AliasServerDbContext> dbContextFac
context.AliasVaultUserRefreshTokens.RemoveRange(existingTokens);
// Add new refresh token.
- await context.AliasVaultUserRefreshTokens.AddAsync(new AliasVaultUserRefreshToken
+ context.AliasVaultUserRefreshTokens.Add(new AliasVaultUserRefreshToken
{
UserId = user.Id,
DeviceIdentifier = deviceIdentifier,
diff --git a/src/AliasVault.Api/Controllers/Email/EmailController.cs b/src/AliasVault.Api/Controllers/Email/EmailController.cs
index a4cdee79e..dc9ef851e 100644
--- a/src/AliasVault.Api/Controllers/Email/EmailController.cs
+++ b/src/AliasVault.Api/Controllers/Email/EmailController.cs
@@ -19,10 +19,11 @@ using Microsoft.EntityFrameworkCore;
/// <summary>
/// Email controller for retrieving emails from the database.
/// </summary>
+/// <param name="logger">ILogger instance.</param>
/// <param name="dbContextFactory">DbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
[ApiVersion("1")]
-public class EmailController(IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
+public class EmailController(ILogger<VaultController> logger, IDbContextFactory<AliasServerDbContext> dbContextFactory, UserManager<AliasVaultUser> userManager) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Get the newest version of the vault for the current user.
@@ -34,31 +35,15 @@ public class EmailController(IDbContextFactory<AliasServerDbContext> dbContextFa
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var user = await GetCurrentUserAsync();
- if (user is null)
- {
- return Unauthorized("Not authenticated.");
- }
-
- // Retrieve email from database.
- var email = await context.Emails.Include(x => x.EncryptionKey).AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
- if (email is null)
- {
- return NotFound("Email not found.");
- }
-
- // See if this user has a valid claim to the email address.
- var emailClaim = await context.UserEmailClaims
- .FirstOrDefaultAsync(x => x.UserId == user.Id && x.Address == email.To);
-
- if (emailClaim is null)
+ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ if (errorResult != null)
{
- return Unauthorized("User does not have a claim to this email address.");
+ return errorResult;
}
var returnEmail = new EmailApiModel
{
- Id = email.Id,
+ Id = email!.Id,
Subject = email.Subject,
FromDisplay = ConversionHelper.ConvertFromToFromDisplay(email.From),
FromDomain = email.FromDomain,
@@ -94,4 +79,75 @@ public class EmailController(IDbContextFactory<AliasServerDbContext> dbContextFa
return Ok(returnEmail);
}
+
+ /// <summary>
+ /// Deletes an email for the current user.
+ /// </summary>
+ /// <param name="id">The email ID to delete.</param>
+ /// <returns>A response indicating the success or failure of the deletion.</returns>
+ [HttpDelete(template: "{id}", Name = "DeleteEmail")]
+ public async Task<IActionResult> DeleteEmail(int id)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ if (errorResult != null)
+ {
+ return errorResult;
+ }
+
+ // Delete associated attachments
+ context.EmailAttachments.RemoveRange(email!.Attachments);
+
+ // Delete the email
+ context.Emails.Remove(email);
+
+ try
+ {
+ await context.SaveChangesAsync();
+ return Ok();
+ }
+ catch (Exception ex)
+ {
+ // Log the exception
+ logger.LogError(ex, "An error occurred while deleting email with ID {id}.", id);
+ return StatusCode(500, $"An error occurred while deleting the email: {ex.Message}");
+ }
+ }
+
+ /// <summary>
+ /// Authenticates the user and retrieves the requested email.
+ /// </summary>
+ /// <param name="id">The email ID to retrieve.</param>
+ /// <param name="context">The database context.</param>
+ /// <returns>A tuple containing the authenticated user, the email, and an IActionResult if there's an error.</returns>
+ private async Task<(Email? Email, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
+ {
+ var user = await GetCurrentUserAsync();
+ if (user is null)
+ {
+ return (null, Unauthorized("Not authenticated."));
+ }
+
+ // Retrieve email from database.
+ var email = await context.Emails
+ .Include(x => x.Attachments)
+ .FirstOrDefaultAsync(x => x.Id == id);
+
+ if (email is null)
+ {
+ return (null, NotFound("Email not found."));
+ }
+
+ // See if this user has a valid claim to the email address.
+ var emailClaim = await context.UserEmailClaims
+ .FirstOrDefaultAsync(x => x.UserId == user.Id && x.Address == email.To);
+
+ if (emailClaim is null)
+ {
+ return (null, Unauthorized("User does not have a claim to this email address."));
+ }
+
+ return (email, null);
+ }
}
diff --git a/src/AliasVault.Api/Controllers/VaultController.cs b/src/AliasVault.Api/Controllers/VaultController.cs
index bd769a88a..1ec730f60 100644
--- a/src/AliasVault.Api/Controllers/VaultController.cs
+++ b/src/AliasVault.Api/Controllers/VaultController.cs
@@ -116,7 +116,7 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
context.Vaults.RemoveRange(vaultsToDelete);
// Add the new vault and commit to database.
- await context.Vaults.AddAsync(newVault);
+ context.Vaults.Add(newVault);
await context.SaveChangesAsync();
// Update user email claims if email addresses have been supplied.
@@ -176,7 +176,7 @@ public class VaultController(ILogger<VaultController> logger, IDbContextFactory<
{
try
{
- await context.UserEmailClaims.AddAsync(new UserEmailClaim
+ context.UserEmailClaims.Add(new UserEmailClaim
{
UserId = userId,
Address = sanitizedEmail,
diff --git a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor b/src/AliasVault.Client/Main/Components/Email/EmailModal.razor
index a543201b8..6347a3037 100644
--- a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor
+++ b/src/AliasVault.Client/Main/Components/Email/EmailModal.razor
@@ -1,5 +1,8 @@
@using AliasVault.Shared.Models.Spamok
@inject JsInteropService JsInteropService
+@inject GlobalNotificationService GlobalNotificationService
+@inject IHttpClientFactory HttpClientFactory
+@inject HttpClient HttpClient
<ClickOutsideHandler OnClose="OnClose" ContentId="emailModal">
<div class="fixed inset-0 z-50 overflow-auto bg-gray-500 bg-opacity-75 flex items-center justify-center">
@@ -32,7 +35,8 @@
</iframe>
</div>
</div>
- <div class="mt-6 flex justify-end">
+ <div class="mt-6 flex justify-end space-x-4">
+ <button @onclick="DeleteEmail" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">Delete</button>
<button @onclick="Close" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Close</button>
</div>
</div>
@@ -58,6 +62,12 @@
[Parameter]
public EventCallback<bool> OnClose { get; set; }
+ /// <summary>
+ /// Callback when an email is deleted.
+ /// </summary>
+ [Parameter]
+ public EventCallback<int> OnEmailDeleted { get; set; }
+
/// <summary>
/// The message body to display
/// </summary>
@@ -72,6 +82,91 @@
return OnClose.InvokeAsync(false);
}
+ /// <summary>
+ /// Delete the current email.
+ /// </summary>
+ private async Task DeleteEmail()
+ {
+ if (Email == null)
+ {
+ return;
+ }
+
+ if (IsSpamOk)
+ {
+ //await JsInteropService.Confirm("Are you sure you want to delete this email?", DeleteEmailAliasVault);
+ await DeleteEmailSpamOk();
+ }
+ else
+ {
+ //await JsInteropService.Confirm("Are you sure you want to delete this email?", DeleteEmailAliasVault);
+ await DeleteEmailAliasVault();
+ }
+ }
+
+ /// <summary>
+ /// Delete the current email in SpamOk.
+ /// </summary>
+ private async Task DeleteEmailSpamOk()
+ {
+ if (Email == null)
+ {
+ return;
+ }
+
+ try
+ {
+ var client = HttpClientFactory.CreateClient("EmailClient");
+ var response = await client.DeleteAsync($"https://api.spamok.com/v2/Email/{Email.ToLocal}/{Email.Id}");
+ if (response.IsSuccessStatusCode)
+ {
+ GlobalNotificationService.AddSuccessMessage("Email deleted successfully", true);
+ await OnEmailDeleted.InvokeAsync(Email.Id);
+ await Close();
+ }
+ else
+ {
+ var errorMessage = await response.Content.ReadAsStringAsync();
+ GlobalNotificationService.AddErrorMessage($"Failed to delete email: {errorMessage}", true);
+ }
+ }
+ catch (Exception ex)
+ {
+ GlobalNotificationService.AddErrorMessage($"An error occurred: {ex.Message}", true);
+ }
+ }
+
+ /// <summary>
+ /// Delete the current email in AliasVault.
+ /// </summary>
+ private async Task DeleteEmailAliasVault()
+ {
+ if (Email == null)
+ {
+ return;
+ }
+
+ try
+ {
+ var response = await HttpClient.DeleteAsync($"api/v1/Email/{Email.Id}");
+ if (response.IsSuccessStatusCode)
+ {
+ GlobalNotificationService.AddSuccessMessage("Email deleted successfully", true);
+ await OnEmailDeleted.InvokeAsync(Email.Id);
+ await Close();
+ }
+ else
+ {
+ var errorMessage = await response.Content.ReadAsStringAsync();
+ GlobalNotificationService.AddErrorMessage($"Failed to delete email: {errorMessage}", true);
+ }
+ }
+ catch (Exception ex)
+ {
+ GlobalNotificationService.AddErrorMessage($"An error occurred: {ex.Message}", true);
+ }
+ }
+
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
index 7e227c231..da56d8ee1 100644
--- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
+++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor
@@ -14,7 +14,7 @@
@if (EmailModalVisible)
{
- <EmailModal Email="@Email" IsSpamOk="@IsSpamOk" OnClose="CloseEmailModal" />
+ <EmailModal Email="@Email" IsSpamOk="@IsSpamOk" OnClose="CloseEmailModal" OnEmailDeleted="ManualRefresh" />
}
@if (ShowComponent)
diff --git a/src/AliasVault.Client/Main/Pages/Emails/Home.razor b/src/AliasVault.Client/Main/Pages/Emails/Home.razor
index 7e8163b7c..13108fc3f 100644
--- a/src/AliasVault.Client/Main/Pages/Emails/Home.razor
+++ b/src/AliasVault.Client/Main/Pages/Emails/Home.razor
@@ -13,7 +13,7 @@
@if (EmailModalVisible)
{
- <EmailModal Email="EmailModalEmail" IsSpamOk="false" OnClose="CloseEmailModal" />
+ <EmailModal Email="EmailModalEmail" IsSpamOk="false" OnClose="CloseEmailModal" OnEmailDeleted="RefreshData" />
}
<div class="grid grid-cols-1 px-4 pt-6 xl:grid-cols-3 xl:gap-4 dark:bg-gray-900">
@@ -44,7 +44,7 @@ else
<div class="overflow-x-auto px-4">
<Paginator CurrentPage="CurrentPage" PageSize="PageSize" TotalRecords="TotalRecords" OnPageChanged="HandlePageChanged"/>
- <div class="bg-white shadow rounded-lg overflow-hidden mt-6">
+ <div class="bg-white border rounded-lg overflow-hidden mt-6">
<div class="px-4 py-2 bg-gray-100 border-b">
<h2 class="font-semibold text-gray-800">Inbox</h2>
</div>
diff --git a/src/AliasVault.Client/Services/CredentialService.cs b/src/AliasVault.Client/Services/CredentialService.cs
index 15326c704..0b2880be7 100644
--- a/src/AliasVault.Client/Services/CredentialService.cs
+++ b/src/AliasVault.Client/Services/CredentialService.cs
@@ -160,7 +160,7 @@ public sealed class CredentialService(HttpClient httpClient, DbService dbService
login.Attachments.Add(attachment);
}
- await context.Credentials.AddAsync(login);
+ context.Credentials.Add(login);
// Add password.
login.Passwords.Add(loginObject.Passwords.First());
diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.cs
index 5bdfa4f75..072b2b3d6 100644
--- a/src/AliasVault.Client/Services/Database/DbService.cs
+++ b/src/AliasVault.Client/Services/Database/DbService.cs
@@ -526,7 +526,7 @@ public sealed class DbService : IDisposable
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
};
- await _dbContext.EncryptionKeys.AddAsync(encryptionKey);
+ _dbContext.EncryptionKeys.Add(encryptionKey);
return encryptionKey;
}
}
diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 3777b2955..b7e780300 100644
--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -357,7 +357,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
newEmail = EmailEncryption.EncryptEmail(newEmail, userEncryptionKey);
// Insert the email into the database.
- await dbContext.Emails.AddAsync(newEmail);
+ dbContext.Emails.Add(newEmail);
await dbContext.SaveChangesAsync();
return newEmail.Id;
diff --git a/src/Utilities/AliasVault.AuthLogging/AuthLoggingService.cs b/src/Utilities/AliasVault.AuthLogging/AuthLoggingService.cs
index c1fe881a1..bf0ba9c61 100644
--- a/src/Utilities/AliasVault.AuthLogging/AuthLoggingService.cs
+++ b/src/Utilities/AliasVault.AuthLogging/AuthLoggingService.cs
@@ -48,7 +48,7 @@ public class AuthLoggingService(IServiceProvider serviceProvider, IHttpContextAc
IsSuspiciousActivity = false,
};
- await dbContext.AuthLogs.AddAsync(authAttempt);
+ dbContext.AuthLogs.Add(authAttempt);
await dbContext.SaveChangesAsync();
}
@@ -82,7 +82,7 @@ public class AuthLoggingService(IServiceProvider serviceProvider, IHttpContextAc
IsSuspiciousActivity = false,
};
- await dbContext.AuthLogs.AddAsync(authAttempt);
+ dbContext.AuthLogs.Add(authAttempt);
await dbContext.SaveChangesAsync();
}
diff --git a/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs b/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
index 2535ebd2e..08255a37d 100644
--- a/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
+++ b/src/Utilities/AliasVault.WorkerStatus/StatusWorker.cs
@@ -84,7 +84,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbCont
/// <returns>New current status.</returns>
private async Task<WorkerServiceStatus> GetServiceStatus()
{
- var entry = await GetOrCreateInitialStatusRecord();
+ var entry = GetOrCreateInitialStatusRecord();
if (!string.IsNullOrEmpty(entry.DesiredStatus) && entry.CurrentStatus != entry.DesiredStatus)
{
@@ -155,7 +155,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbCont
/// <summary>
/// Retrieves status record or creates an initial status record if it does not exist.
/// </summary>
- private async Task<WorkerServiceStatus> GetOrCreateInitialStatusRecord()
+ private WorkerServiceStatus GetOrCreateInitialStatusRecord()
{
var entry = _dbContext.WorkerServiceStatuses.FirstOrDefault(x => x.ServiceName == globalServiceStatus.ServiceName);
if (entry != null)
@@ -169,7 +169,7 @@ public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbCont
CurrentStatus = Status.Started.ToString(),
DesiredStatus = string.Empty,
};
- await _dbContext.WorkerServiceStatuses.AddAsync(entry);
+ _dbContext.WorkerServiceStatuses.Add(entry);
return entry;
}