Skip to content

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

Code style refactor (#11)

Leendert de Borst6d0371919eb7
diff --git a/src/AliasVault.Api/Controllers/AliasController.cs b/src/AliasVault.Api/Controllers/AliasController.cs
index 1cc4f5bfb..c07e7696a 100644
--- a/src/AliasVault.Api/Controllers/AliasController.cs
+++ b/src/AliasVault.Api/Controllers/AliasController.cs
@@ -23,8 +23,6 @@ using Service = AliasVault.Shared.Models.WebApi.Service;
/// <param name="userManager">UserManager instance.</param>
public class AliasController(AliasDbContext context, UserManager<IdentityUser> userManager) : AuthenticatedRequestController(userManager)
{
- private readonly AliasDbContext _context = context;
-
/// <summary>
/// Get all alias items for the current user.
/// </summary>
@@ -39,7 +37,7 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
}
// Logic to retrieve items for the user.
- var aliases = await _context.Logins
+ var aliases = await context.Logins
.Include(x => x.Identity)
.Include(x => x.Service)
.Where(x => x.UserId == user.Id)
@@ -70,7 +68,7 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
return Unauthorized();
}
- var aliasObject = await _context.Logins
+ var aliasObject = await context.Logins
.Include(x => x.Passwords)
.Include(x => x.Identity)
.Include(x => x.Service)
@@ -175,8 +173,8 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
UpdatedAt = DateTime.UtcNow,
};
- await _context.Logins.AddAsync(login);
- await _context.SaveChangesAsync();
+ await context.Logins.AddAsync(login);
+ await context.SaveChangesAsync();
return Ok(login.Id);
}
@@ -197,7 +195,7 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
}
// Get the existing entry.
- var login = await _context.Logins
+ var login = await context.Logins
.Include(x => x.Identity)
.Include(x => x.Service)
.Include(x => x.Passwords)
@@ -228,7 +226,7 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
login.Service.Url = model.Service.Url;
login.Service.UpdatedAt = DateTime.UtcNow;
- await _context.SaveChangesAsync();
+ await context.SaveChangesAsync();
return Ok(login.Id);
}
@@ -247,13 +245,13 @@ public class AliasController(AliasDbContext context, UserManager<IdentityUser> u
return Unauthorized();
}
- var login = await _context.Logins
+ var login = await context.Logins
.Where(x => x.Id == aliasId)
.Where(x => x.UserId == user.Id)
.FirstAsync();
- _context.Logins.Remove(login);
- await _context.SaveChangesAsync();
+ context.Logins.Remove(login);
+ await context.SaveChangesAsync();
return Ok();
}
diff --git a/src/AliasVault.Api/Program.cs b/src/AliasVault.Api/Program.cs
index 9a213e651..49b0a5c95 100644
--- a/src/AliasVault.Api/Program.cs
+++ b/src/AliasVault.Api/Program.cs
@@ -157,7 +157,13 @@ using (var scope = app.Services.CreateScope())
await app.RunAsync();
-/// <summary>
-/// For starting the WebAPI project in-memory from E2ETests project.
-/// </summary>
-public class AliasVaultApiProgram { }
+namespace AliasVault.Api
+{
+ /// <summary>
+ /// Explicit program class definition. This is required in order to start the WebAPI project
+ /// in-memory from E2ETests project via WebApplicationFactory.
+ /// </summary>
+ public partial class Program
+ {
+ }
+}
diff --git a/src/AliasVault.WebApp/AliasVault.WebApp.csproj b/src/AliasVault.WebApp/AliasVault.WebApp.csproj
index 89fac0879..5fb654ef5 100644
--- a/src/AliasVault.WebApp/AliasVault.WebApp.csproj
+++ b/src/AliasVault.WebApp/AliasVault.WebApp.csproj
@@ -17,6 +17,15 @@
<DocumentationFile>bin\Release\net8.0\AliasVault.WebApp.xml</DocumentationFile>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+ <TreatWarningsAsErrors>True</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
+ <TreatWarningsAsErrors>True</TreatWarningsAsErrors>
+ <Optimize>True</Optimize>
+ </PropertyGroup>
+
<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.5.0" />
<PackageReference Include="Microsoft.AspNetCore.Authorization" Version="8.0.6" />
diff --git a/src/AliasVault.WebApp/Auth/Components/InputTextField.razor b/src/AliasVault.WebApp/Auth/Components/InputTextField.razor
index 41a9b634f..4ca195285 100644
--- a/src/AliasVault.WebApp/Auth/Components/InputTextField.razor
+++ b/src/AliasVault.WebApp/Auth/Components/InputTextField.razor
@@ -9,10 +9,10 @@
class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" />
@code {
- [Parameter] public string Id { get; set; }
- [Parameter] public string Value { get; set; }
+ [Parameter] public string Id { get; set; } = null!;
+ [Parameter] public string Value { get; set; } = null!;
[Parameter] public EventCallback<string> ValueChanged { get; set; }
- [Parameter] public Expression<Func<string>> ValueExpression { get; set; }
- [Parameter] public string Placeholder { get; set; }
- [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object> AdditionalAttributes { get; set; }
+ [Parameter] public Expression<Func<string>> ValueExpression { get; set; } = null!;
+ [Parameter] public string Placeholder { get; set; } = null!;
+ [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object> AdditionalAttributes { get; set; } = new();
}
diff --git a/src/AliasVault.WebApp/Auth/Pages/Login.razor b/src/AliasVault.WebApp/Auth/Pages/Login.razor
index c84cc7299..58a36038e 100644
--- a/src/AliasVault.WebApp/Auth/Pages/Login.razor
+++ b/src/AliasVault.WebApp/Auth/Pages/Login.razor
@@ -45,7 +45,7 @@
@code {
LoginModel user = new LoginModel();
- FullScreenLoadingIndicator loadingIndicator;
+ FullScreenLoadingIndicator loadingIndicator = new();
protected override async Task OnInitializedAsync()
{
diff --git a/src/AliasVault.WebApp/Auth/Pages/Register.razor b/src/AliasVault.WebApp/Auth/Pages/Register.razor
index eba047427..024b32523 100644
--- a/src/AliasVault.WebApp/Auth/Pages/Register.razor
+++ b/src/AliasVault.WebApp/Auth/Pages/Register.razor
@@ -61,7 +61,7 @@
@code {
RegisterModel user = new RegisterModel();
- FullScreenLoadingIndicator loadingIndicator;
+ FullScreenLoadingIndicator loadingIndicator = new();
List<string> validationErrors = new List<string>();
async Task HandleRegister()
@@ -114,10 +114,10 @@
public class ValidationErrorResponse
{
- public string Type { get; set; }
- public string Title { get; set; }
+ public string Type { get; set; } = null!;
+ public string Title { get; set; } = null!;
public int Status { get; set; }
- public IDictionary<string, string[]> Errors { get; set; }
- public string TraceId { get; set; }
+ public Dictionary<string, string[]> Errors { get; set; } = new();
+ public string TraceId { get; set; } = null!;
}
}
diff --git a/src/AliasVault.WebApp/Auth/Services/AliasVaultApiHandlerService.cs b/src/AliasVault.WebApp/Auth/Services/AliasVaultApiHandlerService.cs
index bb186841b..bdc0f2848 100644
--- a/src/AliasVault.WebApp/Auth/Services/AliasVaultApiHandlerService.cs
+++ b/src/AliasVault.WebApp/Auth/Services/AliasVaultApiHandlerService.cs
@@ -1,19 +1,28 @@
-using Microsoft.AspNetCore.Components;
+//-----------------------------------------------------------------------
+// <copyright file="AliasVaultApiHandlerService.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.WebApp.Auth.Services;
using System.Net;
using System.Net.Http.Headers;
+using Microsoft.AspNetCore.Components;
-public class AliasVaultApiHandlerService : DelegatingHandler
+/// <summary>
+/// This services handles all API requests to the AliasVault API and will add the access token to the request headers.
+/// If a 401 unauthorized is returned by the API it will intercept this response and attempt to automatically refresh the access token.
+/// </summary>
+public class AliasVaultApiHandlerService(IServiceProvider serviceProvider) : DelegatingHandler
{
- private readonly IServiceProvider _serviceProvider;
-
- public AliasVaultApiHandlerService(IServiceProvider serviceProvider)
- {
- _serviceProvider = serviceProvider;
- }
-
+ /// <summary>
+ /// Override the SendAsync method to add the access token to the request headers.
+ /// </summary>
+ /// <param name="request">HttpRequestMessage instance.</param>
+ /// <param name="cancellationToken">CancellationToken instance.</param>
+ /// <returns>HttpResponseMessage.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Check if the request already contains the refreshed token to prevent infinite loop
@@ -25,7 +34,7 @@ public class AliasVaultApiHandlerService : DelegatingHandler
}
// Set the access token in the Authorization header
- var authService = _serviceProvider.GetRequiredService<AuthService>();
+ var authService = serviceProvider.GetRequiredService<AuthService>();
var token = await authService.GetAccessTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
@@ -39,21 +48,20 @@ public class AliasVaultApiHandlerService : DelegatingHandler
{
// Retry the original request with the new access token
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", newToken);
- // Add a custom header to indicate that this is a retry attempt
+
+ // Add a custom header to indicate that the next request is a retry attempt and any failure should be ignored.
request.Headers.Add("X-Ignore-Failure", "true");
response = await base.SendAsync(request, cancellationToken);
return response;
}
else
{
- // Refreshing token failed. This might be caused by the refresh token itself expired or has been revoked.
- // Remove token from localstorage and redirect to login.
+ // Refreshing token failed. This might be caused by the expiration or revocation of the refresh token itself.
+ // Remove the token from local storage and redirect to the login page.
await authService.RemoveTokensAsync();
- // Redirect to the login page.
- var navigationManager = _serviceProvider.GetRequiredService<NavigationManager>();
+ var navigationManager = serviceProvider.GetRequiredService<NavigationManager>();
navigationManager.NavigateTo("/user/login");
-
}
}
diff --git a/src/AliasVault.WebApp/Auth/Services/AuthService.cs b/src/AliasVault.WebApp/Auth/Services/AuthService.cs
index 7f248d5e2..ff7d00761 100644
--- a/src/AliasVault.WebApp/Auth/Services/AuthService.cs
+++ b/src/AliasVault.WebApp/Auth/Services/AuthService.cs
@@ -1,27 +1,43 @@
-
-using System.Net.Http.Headers;
-using Microsoft.AspNetCore.Components.Authorization;
+//-----------------------------------------------------------------------
+// <copyright file="AuthService.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.WebApp.Auth.Services;
-using AliasVault.Shared.Models;
-using Blazored.LocalStorage;
using System.Net.Http.Json;
using System.Text.Json;
+using AliasVault.Shared.Models;
+using Blazored.LocalStorage;
+/// <summary>
+/// This service is responsible for handling authentication-related operations such as refreshing tokens,
+/// storing tokens, and revoking tokens.
+/// </summary>
public class AuthService
{
- private readonly HttpClient _httpClient;
- private readonly ILocalStorageService _localStorage;
private const string AccessTokenKey = "token";
private const string RefreshTokenKey = "refreshToken";
+ private readonly HttpClient _httpClient;
+ private readonly ILocalStorageService _localStorage;
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthService"/> class.
+ /// </summary>
+ /// <param name="httpClient">The HTTP client.</param>
+ /// <param name="localStorage">The local storage service.</param>
public AuthService(HttpClient httpClient, ILocalStorageService localStorage)
{
_httpClient = httpClient;
_localStorage = localStorage;
}
+ /// <summary>
+ /// Refreshes the access token asynchronously.
+ /// </summary>
+ /// <returns>The new access token.</returns>
public async Task<string?> RefreshTokenAsync()
{
// Your logic to get the refresh token and request a new access token
@@ -30,8 +46,9 @@ public class AuthService
var tokenInput = new TokenModel { Token = accessToken, RefreshToken = refreshToken };
using var request = new HttpRequestMessage(HttpMethod.Post, "api/Auth/refresh")
{
- Content = JsonContent.Create(tokenInput)
+ Content = JsonContent.Create(tokenInput),
};
+
// Add the X-Ignore-Failure header to the request so any failure does not trigger another refresh token request.
request.Headers.Add("X-Ignore-Failure", "true");
var response = await _httpClient.SendAsync(request);
@@ -55,44 +72,47 @@ public class AuthService
}
/// <summary>
- /// Retrieve the stored refresh token (e.g., from local storage or a secure place).
+ /// Retrieves the stored access token asynchronously.
/// </summary>
- /// <returns></returns>
+ /// <returns>The stored access token.</returns>
public async Task<string> GetAccessTokenAsync()
{
- return await _localStorage.GetItemAsStringAsync(AccessTokenKey);
+ return await _localStorage.GetItemAsStringAsync(AccessTokenKey) ?? string.Empty;
}
/// <summary>
- /// Store the new access token (e.g., in local storage)
+ /// Stores the new access token asynchronously.
/// </summary>
- /// <param name="newToken"></param>
+ /// <param name="newToken">The new access token.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StoreAccessTokenAsync(string newToken)
{
await _localStorage.SetItemAsStringAsync(AccessTokenKey, newToken);
}
/// <summary>
- /// Retrieve the stored refresh token (e.g., from local storage or a secure place).
+ /// Retrieves the stored refresh token asynchronously.
/// </summary>
- /// <returns></returns>
+ /// <returns>The stored refresh token.</returns>
public async Task<string> GetRefreshTokenAsync()
{
- return await _localStorage.GetItemAsStringAsync(RefreshTokenKey);
+ return await _localStorage.GetItemAsStringAsync(RefreshTokenKey) ?? string.Empty;
}
/// <summary>
- /// Store the new access token (e.g., in local storage).
+ /// Stores the new refresh token asynchronously.
/// </summary>
- /// <param name="newToken"></param>
+ /// <param name="newToken">The new refresh token.</param>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task StoreRefreshTokenAsync(string newToken)
{
await _localStorage.SetItemAsStringAsync(RefreshTokenKey, newToken);
}
/// <summary>
- /// Remove the stored access and refresh tokens, called when logging out.
+ /// Removes the stored access and refresh tokens asynchronously, called when logging out.
/// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task RemoveTokensAsync()
{
await _localStorage.RemoveItemAsync(AccessTokenKey);
@@ -111,15 +131,21 @@ public class AuthService
}
/// <summary>
- /// Revoke the access and refresh tokens on the server.
+ /// Revokes the access and refresh tokens on the server asynchronously.
/// </summary>
+ /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task RevokeTokenAsync()
{
- var tokenInput = new TokenModel { Token = await GetAccessTokenAsync(), RefreshToken = await GetRefreshTokenAsync() };
+ var tokenInput = new TokenModel {
+ Token = await GetAccessTokenAsync(),
+ RefreshToken = await GetRefreshTokenAsync(),
+ };
+
using var request = new HttpRequestMessage(HttpMethod.Post, "api/Auth/revoke")
{
- Content = JsonContent.Create(tokenInput)
+ Content = JsonContent.Create(tokenInput),
};
+
// Add the X-Ignore-Failure header to the request so any failure does not trigger another refresh token request.
request.Headers.Add("X-Ignore-Failure", "true");
await _httpClient.SendAsync(request);
diff --git a/src/AliasVault.WebApp/Components/Alias/Alias.razor b/src/AliasVault.WebApp/Components/Alias/Alias.razor
index ba0d336fc..422287698 100644
--- a/src/AliasVault.WebApp/Components/Alias/Alias.razor
+++ b/src/AliasVault.WebApp/Components/Alias/Alias.razor
@@ -12,18 +12,10 @@
@code {
[Parameter]
public AliasVault.Shared.Models.WebApi.AliasListEntry Obj { get; set; } = new();
- private bool showModal = false;
private void ShowDetails()
{
// Redirect to view page instead for now.
NavigationManager.NavigateTo($"/alias/{Obj.Id}");
- //showModal = true;
}
-
- private void CloseDetails()
- {
- showModal = false;
- }
-
}
diff --git a/src/AliasVault.WebApp/Components/CopyPasteFormRow.razor b/src/AliasVault.WebApp/Components/CopyPasteFormRow.razor
index 529d5e5ea..205d4b89f 100644
--- a/src/AliasVault.WebApp/Components/CopyPasteFormRow.razor
+++ b/src/AliasVault.WebApp/Components/CopyPasteFormRow.razor
@@ -16,8 +16,8 @@
</div>
@code {
- [Parameter] public string Label { get; set; }
- [Parameter] public string Value { get; set; }
+ [Parameter] public string Label { get; set; } = "Value";
+ [Parameter] public string Value { get; set; } = string.Empty;
private bool _copied => ClipboardCopyService.GetCopiedId() == _inputId;
private string _inputId = Guid.NewGuid().ToString();
diff --git a/src/AliasVault.WebApp/Components/EditFormRow.razor b/src/AliasVault.WebApp/Components/EditFormRow.razor
index be9791857..f7ff61bf2 100644
--- a/src/AliasVault.WebApp/Components/EditFormRow.razor
+++ b/src/AliasVault.WebApp/Components/EditFormRow.razor
@@ -8,15 +8,15 @@
</div>
@code {
- [Parameter] public string Label { get; set; }
- [Parameter] public string Value { get; set; }
+ [Parameter] public string Label { get; set; } = "Value";
+ [Parameter] public string Value { get; set; } = string.Empty;
[Parameter] public EventCallback<string> ValueChanged { get; set; }
private string _inputId = Guid.NewGuid().ToString();
private async Task OnInputChanged(ChangeEventArgs e)
{
- Value = e.Value.ToString();
+ Value = e.Value?.ToString() ?? string.Empty;
await ValueChanged.InvokeAsync(Value);
}
}
diff --git a/src/AliasVault.WebApp/Components/Email/RecentEmails.razor b/src/AliasVault.WebApp/Components/Email/RecentEmails.razor
index ab5d8945b..ad270809e 100644
--- a/src/AliasVault.WebApp/Components/Email/RecentEmails.razor
+++ b/src/AliasVault.WebApp/Components/Email/RecentEmails.razor
@@ -56,23 +56,21 @@ else
@code {
[Parameter]
- public string EmailPrefix { get; set; }
+ public string EmailPrefix { get; set; } = string.Empty;
[Parameter]
public List<MailboxEmailApiModel> MailboxEmails { get; set; } = new List<MailboxEmailApiModel>();
public bool IsLoading { get; set; } = true;
- protected override Task OnAfterRenderAsync(bool firstRender)
+ protected override async Task OnAfterRenderAsync(bool firstRender)
{
- base.OnAfterRenderAsync(firstRender);
+ await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
- LoadRecentEmailsAsync();
+ await LoadRecentEmailsAsync();
}
-
- return Task.CompletedTask;
}
private async Task LoadRecentEmailsAsync()
diff --git a/src/AliasVault.WebApp/Components/Models/BreadcrumbItem.cs b/src/AliasVault.WebApp/Components/Models/BreadcrumbItem.cs
index 01813e22a..bf8cebdc5 100644
--- a/src/AliasVault.WebApp/Components/Models/BreadcrumbItem.cs
+++ b/src/AliasVault.WebApp/Components/Models/BreadcrumbItem.cs
@@ -1,7 +1,24 @@
+//-----------------------------------------------------------------------
+// <copyright file="BreadcrumbItem.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.WebApp.Components.Models;
+/// <summary>
+/// Represents a breadcrumb item for the breadcrumb component.
+/// </summary>
public class BreadcrumbItem
{
+ /// <summary>
+ /// Gets or sets the display name for the breadcrumb item.
+ /// </summary>
public string? DisplayName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the URL for the breadcrumb item.
+ /// </summary>
public string? Url { get; set; }
}
diff --git a/src/AliasVault.WebApp/Components/RedirectToLogin.razor b/src/AliasVault.WebApp/Components/RedirectToLogin.razor
index 145177ab4..885bbb063 100644
--- a/src/AliasVault.WebApp/Components/RedirectToLogin.razor
+++ b/src/AliasVault.WebApp/Components/RedirectToLogin.razor
@@ -1,6 +1,6 @@
-@code {
- [Inject] private NavigationManager Navigation { get; set; }
+@inject NavigationManager Navigation
+@code {
protected override void OnInitialized()
{
Navigation.NavigateTo("/user/login");
diff --git a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
index f6d89937b..02695c6a9 100644
--- a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
+++ b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
@@ -173,6 +173,8 @@ else
protected override async Task OnInitializedAsync()
{
+ await Task.Yield();
+
if (EditMode)
{
BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Edit alias" });
diff --git a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/AttachmentApiModel.cs b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/AttachmentApiModel.cs
index bc7cc5c17..6200df3cc 100644
--- a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/AttachmentApiModel.cs
+++ b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/AttachmentApiModel.cs
@@ -1,10 +1,39 @@
+//-----------------------------------------------------------------------
+// <copyright file="AttachmentApiModel.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 BlazorServer.Models.Spamok;
+/// <summary>
+/// Represents an attachment for an email.
+/// </summary>
public class AttachmentApiModel
{
+ /// <summary>
+ /// Gets or sets the ID of the attachment.
+ /// </summary>
public int Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the ID of the email the attachment belongs to.
+ /// </summary>
public int Email_Id { get; set; }
- public string Filename { get; set; }
- public string MimeType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the filename of the attachment.
+ /// </summary>
+ public string Filename { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the MIME type of the attachment.
+ /// </summary>
+ public string MimeType { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the size of the attachment in bytes.
+ /// </summary>
public int Filesize { get; set; }
-}
\ No newline at end of file
+}
diff --git a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/EmailApiModel.cs b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/EmailApiModel.cs
index 924294851..f19a899c5 100644
--- a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/EmailApiModel.cs
+++ b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/EmailApiModel.cs
@@ -1,18 +1,79 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailApiModel.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 BlazorServer.Models.Spamok;
+/// <summary>
+/// Represents an email API model.
+/// </summary>
public class EmailApiModel
{
+ /// <summary>
+ /// Gets or sets the ID of the email.
+ /// </summary>
public int Id { get; set; }
- public string Subject { get; set; }
- public string FromDisplay { get; set; }
- public string FromDomain { get; set; }
- public string FromLocal { get; set; }
- public string ToDomain { get; set; }
- public string ToLocal { get; set; }
+
+ /// <summary>
+ /// Gets or sets the subject of the email.
+ /// </summary>
+ public string Subject { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the display name of the sender.
+ /// </summary>
+ public string FromDisplay { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the domain of the sender's email address.
+ /// </summary>
+ public string FromDomain { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the local part of the sender's email address.
+ /// </summary>
+ public string FromLocal { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the domain of the recipient's email address.
+ /// </summary>
+ public string ToDomain { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the local part of the recipient's email address.
+ /// </summary>
+ public string ToLocal { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets the date of the email.
+ /// </summary>
public DateTime Date { get; set; }
+
+ /// <summary>
+ /// Gets or sets the system date of the email.
+ /// </summary>
public DateTime DateSystem { get; set; }
+
+ /// <summary>
+ /// Gets or sets the number of seconds ago the email was received.
+ /// </summary>
public double SecondsAgo { get; set; }
+
+ /// <summary>
+ /// Gets or sets the HTML content of the email message.
+ /// </summary>
public string? MessageHtml { get; set; }
+
+ /// <summary>
+ /// Gets or sets the plain text content of the email message.
+ /// </summary>
public string? MessagePlain { get; set; }
- public List<AttachmentApiModel> Attachments { get; set; }
-}
\ No newline at end of file
+
+ /// <summary>
+ /// Gets or sets the list of attachments in the email.
+ /// </summary>
+ public List<AttachmentApiModel> Attachments { get; set; } = new();
+}
diff --git a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs
index 057912510..82305d79f 100644
--- a/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs
+++ b/src/AliasVault.WebApp/Pages/Aliases/Mailbox/Models/Spamok/MailboxApiModel.cs
@@ -1,8 +1,29 @@
-namespace BlazorServer.Models.Spamok;
+//-----------------------------------------------------------------------
+// <copyright file="MailboxApiModel.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 BlazorServer.Models.Spamok;
+
+/// <summary>
+/// Represents a mailbox API model.
+/// </summary>
public class MailboxApiModel
{
- public string Address { get; set; }
+ /// <summary>
+ /// Gets or sets the address of the mailbox.
+ /// </summary>
+ public string Address { get; set; } = string.Empty;
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the mailbox is subscribed.
+ /// </summary>
public bool Subscribed { get; set; }
- public List<MailboxEmailApiModel> Mails { get; set; }
-}
\ No newline at end of file
+
+ /// <summary>
+ /// Gets or sets the list of mailbox email API models.
+ /// </summary>
+ public List<MailboxEmailApiModel> Mails { get; set; } = new();
+}
diff --git a/src/AliasVault.WebApp/Services/AliasService.cs b/src/AliasVault.WebApp/Services/AliasService.cs
index 9abb10ee8..b7643ce5a 100644
--- a/src/AliasVault.WebApp/Services/AliasService.cs
+++ b/src/AliasVault.WebApp/Services/AliasService.cs
@@ -1,48 +1,50 @@
+//-----------------------------------------------------------------------
+// <copyright file="AliasService.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.WebApp.Services;
+
using System.Net.Http.Json;
-using AliasDb;
using AliasVault.Shared.Models.WebApi;
using Identity = AliasGenerators.Identity.Models.Identity;
-namespace AliasVault.WebApp.Services;
-
-public class AliasService
+/// <summary>
+/// Service class for alias operations.
+/// </summary>
+public class AliasService(HttpClient httpClient)
{
- private HttpClient _httpClient;
-
- /// <summary>
- /// Public constructor which can be called from static async method or directly.
- /// </summary>
- /// <param name="aliasObj"></param>
- /// <param name="httpClient"></param>
- public AliasService(HttpClient httpClient)
- {
- _httpClient = httpClient;
- }
-
/// <summary>
/// Generate random identity by calling the IdentityGenerator API.
/// </summary>
- /// <returns></returns>
+ /// <returns>Identity object.</returns>
public async Task<Identity> GenerateRandomIdentityAsync()
{
- return await _httpClient.GetFromJsonAsync<Identity>("api/Identity/generate");
+ var identity = await httpClient.GetFromJsonAsync<Identity>("api/Identity/generate");
+ if (identity == null)
+ {
+ throw new InvalidOperationException("Failed to generate random identity.");
+ }
+
+ return identity;
}
/// <summary>
/// Insert new entry into database.
/// </summary>
- /// <param name="aliasObject"></param>
+ /// <param name="aliasObject">Alias object to insert.</param>
+ /// <returns>Guid of inserted entry.</returns>
public async Task<Guid> InsertAliasAsync(Alias aliasObject)
{
- // Put to webapi.
try
{
- var returnObject = await _httpClient.PutAsJsonAsync<Alias>("api/Alias", aliasObject);
+ var returnObject = await httpClient.PutAsJsonAsync<Alias>("api/Alias", aliasObject);
return await returnObject.Content.ReadFromJsonAsync<Guid>();
}
catch
{
- // Return null if failed. If authentication failed, the AliasVaultApiHandlerService will redirect to login page.
return Guid.Empty;
}
}
@@ -50,19 +52,18 @@ public class AliasService
/// <summary>
/// Update an existing entry to database.
/// </summary>
- /// <param name="aliasObject"></param>
- /// <param name="id"></param>
+ /// <param name="aliasObject">Alias object to update.</param>
+ /// <param name="id">Id of alias to update.</param>
+ /// <returns>Guid of updated entry.</returns>
public async Task<Guid> UpdateAliasAsync(Alias aliasObject, Guid id)
{
- // Post to webapi.
try
{
- var returnObject = await _httpClient.PostAsJsonAsync<Alias>("api/Alias/" + id, aliasObject);
+ var returnObject = await httpClient.PostAsJsonAsync<Alias>("api/Alias/" + id, aliasObject);
return await returnObject.Content.ReadFromJsonAsync<Guid>();
}
catch
{
- // Return null if failed. If authentication failed, the AliasVaultApiHandlerService will redirect to login page.
return Guid.Empty;
}
}
@@ -70,48 +71,47 @@ public class AliasService
/// <summary>
/// Load existing entry from database.
/// </summary>
- /// <param name="aliasId"></param>
+ /// <param name="aliasId">Id of alias to load.</param>
+ /// <returns>Alias object.</returns>
public async Task<Alias?> LoadAliasAsync(Guid aliasId)
{
- // Make webapi call to get list of all entries.
try
{
- return await _httpClient.GetFromJsonAsync<Alias>("api/Alias/" + aliasId);
+ return await httpClient.GetFromJsonAsync<Alias>("api/Alias/" + aliasId);
}
catch
{
- // Return null if failed. If authentication failed, the AliasVaultApiHandlerService will redirect to login page.
return null;
}
}
/// <summary>
- /// Get list with all entries from database.
+ /// Get list with all entries that belong to current user.
/// </summary>
+ /// <returns>List of AliasListEntry objects.</returns>
public async Task<List<AliasListEntry>?> GetListAsync()
{
- // Make webapi call to get list of all entries.
try
{
- return await _httpClient.GetFromJsonAsync<List<AliasListEntry>>("api/Alias/items");
+ return await httpClient.GetFromJsonAsync<List<AliasListEntry>>("api/Alias/items");
}
catch
{
- // Return null if failed. If authentication failed, the AliasVaultApiHandlerService will redirect to login page.
- return null;
+ return new List<AliasListEntry>();
}
}
/// <summary>
/// Removes existing entry from database.
/// </summary>
- /// <param name="alias"></param>
- public async Task DeleteAliasAsync(Guid Id)
+ /// <param name="id">Id of alias to delete.</param>
+ /// <returns>Task.</returns>
+ public async Task DeleteAliasAsync(Guid id)
{
// Delete from webapi.
try
{
- await _httpClient.DeleteAsync("api/Alias/" + Id);
+ await httpClient.DeleteAsync("api/Alias/" + id);
}
catch
{
diff --git a/src/AliasVault.WebApp/Services/ClipboardCopyService.cs b/src/AliasVault.WebApp/Services/ClipboardCopyService.cs
index fc0613d65..bd98d854a 100644
--- a/src/AliasVault.WebApp/Services/ClipboardCopyService.cs
+++ b/src/AliasVault.WebApp/Services/ClipboardCopyService.cs
@@ -1,3 +1,10 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClipboardCopyService.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.WebApp.Services;
/// <summary>
@@ -5,18 +12,26 @@ namespace AliasVault.WebApp.Services;
/// </summary>
public class ClipboardCopyService
{
- private string _currentCopiedId;
- public event Action<string> OnCopy;
+ private string _currentCopiedId = string.Empty;
+
+ /// <summary>
+ /// Event to notify the application that an item has been copied.
+ /// </summary>
+ public event Action<string> OnCopy = null!;
/// <summary>
/// Keep track of the last copied item.
/// </summary>
- /// <param name="id"></param>
+ /// <param name="id">Id of the last copied item.</param>
public void SetCopied(string id)
{
_currentCopiedId = id;
OnCopy?.Invoke(_currentCopiedId);
}
+ /// <summary>
+ /// Get the last copied item.
+ /// </summary>
+ /// <returns>Id of last copied item.</returns>
public string GetCopiedId() => _currentCopiedId;
}
diff --git a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
index 1c634b0c0..a5458da96 100644
--- a/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
+++ b/src/Tests/AliasVault.E2ETests/AliasVault.E2ETests.csproj
@@ -17,6 +17,14 @@
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+ <TreatWarningsAsErrors>False</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
+ <TreatWarningsAsErrors>False</TreatWarningsAsErrors>
+ </PropertyGroup>
+
<ItemGroup>
<AdditionalFiles Include="..\..\stylecop.json" Link="stylecop.json" />
</ItemGroup>
diff --git a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
index 4ce892cb4..05577e653 100644
--- a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
@@ -22,7 +22,7 @@ public class PlaywrightTest
/// <summary>
/// For starting the WebAPI project in-memory.
/// </summary>
- private WebApplicationFactoryFixture<AliasVaultApiProgram> _factory = new();
+ private WebApplicationFactoryFixture<AliasVault.Api.Program> _factory = new();
[OneTimeSetUp]
public async Task OneTimeSetUp()
diff --git a/src/Utilities/FaviconExtractor/FaviconExtractor.cs b/src/Utilities/FaviconExtractor/FaviconExtractor.cs
index a140aa5fe..b3e72a8df 100644
--- a/src/Utilities/FaviconExtractor/FaviconExtractor.cs
+++ b/src/Utilities/FaviconExtractor/FaviconExtractor.cs
@@ -1,70 +1,88 @@
-namespace FaviconExtractor;
+//-----------------------------------------------------------------------
+// <copyright file="FaviconExtractor.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 FaviconExtractor;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using HtmlAgilityPack;
-public class FaviconService
+/// <summary>
+/// Favicon service for extracting favicons from URLs.
+/// </summary>
+public static class FaviconExtractor
{
- public static async Task<byte[]> GetFaviconAsync(string url)
+ /// <summary>
+ /// Extracts the favicon from a URL.
+ /// </summary>
+ /// <param name="url">The URL to extract the favicon for.</param>
+ /// <returns>Byte array for favicon image.</returns>
+ public static async Task<byte[]?> GetFaviconAsync(string url)
{
- using (HttpClient client = new HttpClient())
+ using HttpClient client = new();
+ HttpResponseMessage response = await client.GetAsync(url);
+ if (!response.IsSuccessStatusCode)
{
- HttpResponseMessage response = await client.GetAsync(url);
- if (!response.IsSuccessStatusCode)
- {
- return null;
- }
-
- string htmlContent = await response.Content.ReadAsStringAsync();
- HtmlDocument htmlDoc = new HtmlDocument();
- htmlDoc.LoadHtml(htmlContent);
+ return null;
+ }
- // Find all favicon links in the HTML
- var faviconNodes = htmlDoc.DocumentNode.SelectNodes("//link[contains(@rel, 'icon')]");
- if (faviconNodes == null || !faviconNodes.Any())
- {
- return null;
- }
+ string htmlContent = await response.Content.ReadAsStringAsync();
+ HtmlDocument htmlDoc = new();
+ htmlDoc.LoadHtml(htmlContent);
- // Extract favicon URLs and their sizes
- var favicons = faviconNodes
- .Select(node => new
- {
- Url = node.GetAttributeValue("href", null),
- Size = GetFaviconSize(node.GetAttributeValue("sizes", "0x0"))
- })
- .Where(favicon => !string.IsNullOrEmpty(favicon.Url))
- .OrderByDescending(favicon => favicon.Size)
- .ToList();
+ // Find all favicon links in the HTML
+ var faviconNodes = htmlDoc.DocumentNode.SelectNodes("//link[contains(@rel, 'icon')]");
+ if (faviconNodes == null || faviconNodes.Count == 0)
+ {
+ return null;
+ }
- if (!favicons.Any())
+ // Extract favicon URLs and their sizes
+ var favicons = faviconNodes
+ .Select(node => new
{
- return null;
- }
+ Url = node.GetAttributeValue("href", null),
+ Size = GetFaviconSize(node.GetAttributeValue("sizes", "0x0")),
+ })
+ .Where(favicon => !string.IsNullOrEmpty(favicon.Url))
+ .OrderByDescending(favicon => favicon.Size)
+ .ToList();
- var bestFavicon = favicons.First();
- var faviconUrl = bestFavicon.Url;
+ if (favicons.Count == 0)
+ {
+ return null;
+ }
- // If the favicon URL is relative, convert it to an absolute URL
- if (!Uri.IsWellFormedUriString(faviconUrl, UriKind.Absolute))
- {
- var baseUri = new Uri(url);
- faviconUrl = new Uri(baseUri, faviconUrl).ToString();
- }
+ var bestFavicon = favicons[0];
+ var faviconUrl = bestFavicon.Url;
- HttpResponseMessage faviconResponse = await client.GetAsync(faviconUrl);
- if (!faviconResponse.IsSuccessStatusCode)
- {
- return null;
- }
+ // If the favicon URL is relative, convert it to an absolute URL
+ if (!Uri.IsWellFormedUriString(faviconUrl, UriKind.Absolute))
+ {
+ var baseUri = new Uri(url);
+ faviconUrl = new Uri(baseUri, faviconUrl).ToString();
+ }
- byte[] faviconBytes = await faviconResponse.Content.ReadAsByteArrayAsync();
- return faviconBytes;
+ HttpResponseMessage faviconResponse = await client.GetAsync(faviconUrl);
+ if (!faviconResponse.IsSuccessStatusCode)
+ {
+ return null;
}
+
+ byte[] faviconBytes = await faviconResponse.Content.ReadAsByteArrayAsync();
+ return faviconBytes;
}
+ /// <summary>
+ /// Gets the size of a favicon from a size string.
+ /// </summary>
+ /// <param name="size">Size string.</param>
+ /// <returns>Int which represent pixel count of image size.</returns>
private static int GetFaviconSize(string size)
{
if (string.IsNullOrEmpty(size) || size == "any")
diff --git a/src/Utilities/FaviconExtractor/FaviconExtractor.csproj b/src/Utilities/FaviconExtractor/FaviconExtractor.csproj
index 879717bff..34516a33b 100644
--- a/src/Utilities/FaviconExtractor/FaviconExtractor.csproj
+++ b/src/Utilities/FaviconExtractor/FaviconExtractor.csproj
@@ -17,7 +17,7 @@
</PropertyGroup>
<ItemGroup>
- <Content Include="..\..\stylecop.json" Link="stylecop.json" />
+ <AdditionalFiles Include="..\..\stylecop.json" Link="stylecop.json" />
</ItemGroup>
<ItemGroup>