Skip to content

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

Implement working E2E tests

Leendert de Borst45e04bcf8b43
diff --git a/src/AliasDb/AliasDbContext.cs b/src/AliasDb/AliasDbContext.cs
index 67918cc08..086a3e2bc 100644
--- a/src/AliasDb/AliasDbContext.cs
+++ b/src/AliasDb/AliasDbContext.cs
@@ -51,19 +51,25 @@ public class AliasDbContext : IdentityDbContext
public DbSet<AspNetUserRefreshTokens> AspNetUserRefreshTokens { get; set; }
/// <summary>
- /// Gets or sets the Identities DbSet.
+ /// Sets up the connection string if it is not already configured.
/// </summary>
/// <param name="optionsBuilder">DbContextOptionsBuilder instance.</param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
- var configuration = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .Build();
-
- optionsBuilder
- .UseSqlite(configuration.GetConnectionString("AliasDbContext"))
- .UseLazyLoadingProxies();
+ // If the options are not already configured, use the appsettings.json file.
+ // Tip: the E2E tests will provide a different connection string directly
+ // which will override this default config.
+ /*if (!optionsBuilder.IsConfigured)
+ {
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile("appsettings.json")
+ .Build();
+
+ optionsBuilder
+ .UseSqlite(configuration.GetConnectionString("AliasDbContext"))
+ .UseLazyLoadingProxies();
+ } */
}
/// <summary>
diff --git a/src/AliasVault.Api/Controllers/AliasController.cs b/src/AliasVault.Api/Controllers/AliasController.cs
index 174f8d855..6a15a2d5a 100644
--- a/src/AliasVault.Api/Controllers/AliasController.cs
+++ b/src/AliasVault.Api/Controllers/AliasController.cs
@@ -10,8 +10,11 @@ using Service = AliasVault.Shared.Models.WebApi.Service;
public class AliasController : AuthenticatedRequestController
{
- public AliasController(UserManager<IdentityUser> userManager) : base(userManager)
+ private readonly AliasDbContext _context;
+
+ public AliasController(AliasDbContext context, UserManager<IdentityUser> userManager) : base(userManager)
{
+ _context = context;
}
[HttpGet("items")]
@@ -24,24 +27,21 @@ public class AliasController : AuthenticatedRequestController
}
// Logic to retrieve items for the user.
- using (var dbContext = new AliasDbContext())
- {
- var aliases = await dbContext.Logins
- .Include(x => x.Identity)
- .Include(x => x.Service)
- .Where(x => x.UserId == user.Id)
- .Select(x => new AliasListEntry
- {
- Id = x.Id,
- Logo = x.Service.Logo,
- Service = x.Service.Name,
- CreateDate = x.CreatedAt
- })
+ var aliases = await _context.Logins
+ .Include(x => x.Identity)
+ .Include(x => x.Service)
+ .Where(x => x.UserId == user.Id)
+ .Select(x => new AliasListEntry
+ {
+ Id = x.Id,
+ Logo = x.Service.Logo,
+ Service = x.Service.Name,
+ CreateDate = x.CreatedAt
+ })
- .ToListAsync();
+ .ToListAsync();
- return Ok(aliases);
- }
+ return Ok(aliases);
}
[HttpGet("{aliasId}")]
@@ -53,58 +53,55 @@ public class AliasController : AuthenticatedRequestController
return Unauthorized();
}
- using (var dbContext = new AliasDbContext())
- {
- var aliasObject = await dbContext.Logins
- .Include(x => x.Passwords)
- .Include(x => x.Identity)
- .Include(x => x.Service)
- .Where(x => x.Id == aliasId)
- .Where(x => x.UserId == user.Id)
- .Select(x => new Alias()
+ var aliasObject = await _context.Logins
+ .Include(x => x.Passwords)
+ .Include(x => x.Identity)
+ .Include(x => x.Service)
+ .Where(x => x.Id == aliasId)
+ .Where(x => x.UserId == user.Id)
+ .Select(x => new Alias()
+ {
+ Service = new Service()
{
- Service = new Service()
- {
- Name = x.Service.Name,
- Url = x.Service.Url,
- LogoUrl = "",
- CreatedAt = x.Service.CreatedAt,
- UpdatedAt = x.Service.UpdatedAt
- },
- Identity = new Identity()
- {
- NickName = x.Identity.NickName,
- FirstName = x.Identity.FirstName,
- LastName = x.Identity.LastName,
- BirthDate = x.Identity.BirthDate.ToString("yyyy-MM-dd"),
- Gender = x.Identity.Gender,
- AddressStreet = x.Identity.AddressStreet,
- AddressCity = x.Identity.AddressCity,
- AddressState = x.Identity.AddressState,
- AddressZipCode = x.Identity.AddressZipCode,
- AddressCountry = x.Identity.AddressCountry,
- Hobbies = x.Identity.Hobbies,
- EmailPrefix = x.Identity.EmailPrefix,
- PhoneMobile = x.Identity.PhoneMobile,
- BankAccountIBAN = x.Identity.BankAccountIBAN,
- CreatedAt = x.Identity.CreatedAt,
- UpdatedAt = x.Identity.UpdatedAt
- },
- Password = new AliasVault.Shared.Models.WebApi.Password()
- {
- Value = x.Passwords.First().Value ?? "",
- Description = "",
- CreatedAt = x.Passwords.First().CreatedAt,
- UpdatedAt = x.Passwords.First().UpdatedAt
- },
- CreateDate = x.CreatedAt,
- LastUpdate = x.UpdatedAt
-
- })
- .FirstAsync();
-
- return Ok(aliasObject);
- }
+ Name = x.Service.Name,
+ Url = x.Service.Url,
+ LogoUrl = "",
+ CreatedAt = x.Service.CreatedAt,
+ UpdatedAt = x.Service.UpdatedAt
+ },
+ Identity = new Identity()
+ {
+ NickName = x.Identity.NickName,
+ FirstName = x.Identity.FirstName,
+ LastName = x.Identity.LastName,
+ BirthDate = x.Identity.BirthDate.ToString("yyyy-MM-dd"),
+ Gender = x.Identity.Gender,
+ AddressStreet = x.Identity.AddressStreet,
+ AddressCity = x.Identity.AddressCity,
+ AddressState = x.Identity.AddressState,
+ AddressZipCode = x.Identity.AddressZipCode,
+ AddressCountry = x.Identity.AddressCountry,
+ Hobbies = x.Identity.Hobbies,
+ EmailPrefix = x.Identity.EmailPrefix,
+ PhoneMobile = x.Identity.PhoneMobile,
+ BankAccountIBAN = x.Identity.BankAccountIBAN,
+ CreatedAt = x.Identity.CreatedAt,
+ UpdatedAt = x.Identity.UpdatedAt
+ },
+ Password = new AliasVault.Shared.Models.WebApi.Password()
+ {
+ Value = x.Passwords.First().Value ?? "",
+ Description = "",
+ CreatedAt = x.Passwords.First().CreatedAt,
+ UpdatedAt = x.Passwords.First().UpdatedAt
+ },
+ CreateDate = x.CreatedAt,
+ LastUpdate = x.UpdatedAt
+
+ })
+ .FirstAsync();
+
+ return Ok(aliasObject);
}
/// <summary>
@@ -121,52 +118,49 @@ public class AliasController : AuthenticatedRequestController
return Unauthorized();
}
- using (var dbContext = new AliasDbContext())
+ var login = new Login();
+ login.UserId = user.Id;
+ login.CreatedAt = DateTime.UtcNow;
+ login.UpdatedAt = DateTime.UtcNow;
+ login.Identity = new AliasDb.Identity()
{
- var login = new Login();
- login.UserId = user.Id;
- login.CreatedAt = DateTime.UtcNow;
- login.UpdatedAt = DateTime.UtcNow;
- login.Identity = new AliasDb.Identity()
- {
- NickName = model.Identity.NickName,
- FirstName = model.Identity.FirstName,
- LastName = model.Identity.LastName,
- BirthDate = DateTime.Parse(model.Identity.BirthDate),
- Gender = model.Identity.Gender,
- AddressStreet = model.Identity.AddressStreet,
- AddressCity = model.Identity.AddressCity,
- AddressState = model.Identity.AddressState,
- AddressZipCode = model.Identity.AddressZipCode,
- AddressCountry = model.Identity.AddressCountry,
- Hobbies = model.Identity.Hobbies,
- EmailPrefix = model.Identity.EmailPrefix,
- PhoneMobile = model.Identity.PhoneMobile,
- BankAccountIBAN = model.Identity.BankAccountIBAN,
- CreatedAt = DateTime.UtcNow,
- UpdatedAt = DateTime.UtcNow
- };
-
- login.Passwords.Add(new AliasDb.Password()
- {
- Value = model.Password.Value,
- CreatedAt = DateTime.UtcNow,
- UpdatedAt = DateTime.UtcNow
- });
+ NickName = model.Identity.NickName,
+ FirstName = model.Identity.FirstName,
+ LastName = model.Identity.LastName,
+ BirthDate = DateTime.Parse(model.Identity.BirthDate),
+ Gender = model.Identity.Gender,
+ AddressStreet = model.Identity.AddressStreet,
+ AddressCity = model.Identity.AddressCity,
+ AddressState = model.Identity.AddressState,
+ AddressZipCode = model.Identity.AddressZipCode,
+ AddressCountry = model.Identity.AddressCountry,
+ Hobbies = model.Identity.Hobbies,
+ EmailPrefix = model.Identity.EmailPrefix,
+ PhoneMobile = model.Identity.PhoneMobile,
+ BankAccountIBAN = model.Identity.BankAccountIBAN,
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow
+ };
+
+ login.Passwords.Add(new AliasDb.Password()
+ {
+ Value = model.Password.Value,
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow
+ });
- login.Service = new AliasDb.Service()
- {
- Name = model.Service.Name,
- Url = model.Service.Url,
- CreatedAt = DateTime.UtcNow,
- UpdatedAt = DateTime.UtcNow
- };
+ login.Service = new AliasDb.Service()
+ {
+ Name = model.Service.Name,
+ Url = model.Service.Url,
+ CreatedAt = DateTime.UtcNow,
+ UpdatedAt = DateTime.UtcNow
+ };
- dbContext.Logins.Add(login);
- await dbContext.SaveChangesAsync();
+ _context.Logins.Add(login);
+ await _context.SaveChangesAsync();
- return Ok(login.Id);
- }
+ return Ok(login.Id);
}
/// <summary>
@@ -184,44 +178,41 @@ public class AliasController : AuthenticatedRequestController
return Unauthorized();
}
- using (var dbContext = new AliasDbContext())
- {
- // Get the existing entry.
- var login = await dbContext.Logins
- .Include(x => x.Identity)
- .Include(x => x.Service)
- .Include(x => x.Passwords)
- .Where(x => x.Id == aliasId)
- .Where(x => x.UserId == user.Id)
- .FirstAsync();
-
- login.UpdatedAt = DateTime.UtcNow;
- login.Identity.NickName = model.Identity.NickName;
- login.Identity.FirstName = model.Identity.FirstName;
- login.Identity.LastName = model.Identity.LastName;
- login.Identity.BirthDate = DateTime.Parse(model.Identity.BirthDate);
- login.Identity.Gender = model.Identity.Gender;
- login.Identity.AddressStreet = model.Identity.AddressStreet;
- login.Identity.AddressCity = model.Identity.AddressCity;
- login.Identity.AddressState = model.Identity.AddressState;
- login.Identity.AddressZipCode = model.Identity.AddressZipCode;
- login.Identity.AddressCountry = model.Identity.AddressCountry;
- login.Identity.Hobbies = model.Identity.Hobbies;
- login.Identity.EmailPrefix = model.Identity.EmailPrefix;
- login.Identity.PhoneMobile = model.Identity.PhoneMobile;
- login.Identity.BankAccountIBAN = model.Identity.BankAccountIBAN;
-
- login.Passwords.First().Value = model.Password.Value;
- login.Passwords.First().UpdatedAt = DateTime.UtcNow;
-
- login.Service.Name = model.Service.Name;
- login.Service.Url = model.Service.Url;
- login.Service.UpdatedAt = DateTime.UtcNow;
-
- await dbContext.SaveChangesAsync();
-
- return Ok(login.Id);
- }
+ // Get the existing entry.
+ var login = await _context.Logins
+ .Include(x => x.Identity)
+ .Include(x => x.Service)
+ .Include(x => x.Passwords)
+ .Where(x => x.Id == aliasId)
+ .Where(x => x.UserId == user.Id)
+ .FirstAsync();
+
+ login.UpdatedAt = DateTime.UtcNow;
+ login.Identity.NickName = model.Identity.NickName;
+ login.Identity.FirstName = model.Identity.FirstName;
+ login.Identity.LastName = model.Identity.LastName;
+ login.Identity.BirthDate = DateTime.Parse(model.Identity.BirthDate);
+ login.Identity.Gender = model.Identity.Gender;
+ login.Identity.AddressStreet = model.Identity.AddressStreet;
+ login.Identity.AddressCity = model.Identity.AddressCity;
+ login.Identity.AddressState = model.Identity.AddressState;
+ login.Identity.AddressZipCode = model.Identity.AddressZipCode;
+ login.Identity.AddressCountry = model.Identity.AddressCountry;
+ login.Identity.Hobbies = model.Identity.Hobbies;
+ login.Identity.EmailPrefix = model.Identity.EmailPrefix;
+ login.Identity.PhoneMobile = model.Identity.PhoneMobile;
+ login.Identity.BankAccountIBAN = model.Identity.BankAccountIBAN;
+
+ login.Passwords.First().Value = model.Password.Value;
+ login.Passwords.First().UpdatedAt = DateTime.UtcNow;
+
+ login.Service.Name = model.Service.Name;
+ login.Service.Url = model.Service.Url;
+ login.Service.UpdatedAt = DateTime.UtcNow;
+
+ await _context.SaveChangesAsync();
+
+ return Ok(login.Id);
}
/// <summary>
@@ -237,17 +228,14 @@ public class AliasController : AuthenticatedRequestController
return Unauthorized();
}
- using (var dbContext = new AliasDbContext())
- {
- var login = await dbContext.Logins
- .Where(x => x.Id == aliasId)
- .Where(x => x.UserId == user.Id)
- .FirstAsync();
+ var login = await _context.Logins
+ .Where(x => x.Id == aliasId)
+ .Where(x => x.UserId == user.Id)
+ .FirstAsync();
- dbContext.Logins.Remove(login);
- await dbContext.SaveChangesAsync();
+ _context.Logins.Remove(login);
+ await _context.SaveChangesAsync();
- return Ok();
- }
+ return Ok();
}
}
diff --git a/src/AliasVault.Api/Controllers/AuthController.cs b/src/AliasVault.Api/Controllers/AuthController.cs
index 88db9a82c..612e0d1ee 100644
--- a/src/AliasVault.Api/Controllers/AuthController.cs
+++ b/src/AliasVault.Api/Controllers/AuthController.cs
@@ -15,14 +15,16 @@ using System.Text;
[ApiController]
public class AuthController : ControllerBase
{
+ private readonly AliasDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IConfiguration _configuration;
private const string LoginProvider = "AliasVault";
private const string RefreshToken = "RefreshToken";
- public AuthController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, IConfiguration configuration)
+ public AuthController(AliasDbContext context, UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, IConfiguration configuration)
{
+ _context = context;
_userManager = userManager;
_signInManager = signInManager;
_configuration = configuration;
@@ -34,34 +36,8 @@ public class AuthController : ControllerBase
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
- var token = GenerateJwtToken(user);
- var refreshToken = GenerateRefreshToken();
-
- // Generate device identifier
- var deviceIdentifier = GenerateDeviceIdentifier(Request);
-
- // Save refresh token to database.
- using (var dbContext = new AliasDbContext())
- {
- // Remove any existing refresh tokens for this user and device.
- var existingTokens = dbContext.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier);
- dbContext.AspNetUserRefreshTokens.RemoveRange(existingTokens);
-
- // Add new refresh token.
- dbContext.AspNetUserRefreshTokens.Add(new AspNetUserRefreshTokens
- {
- UserId = user.Id,
- DeviceIdentifier = deviceIdentifier,
- Value = refreshToken,
- ExpireDate = DateTime.Now.AddDays(30),
- CreatedAt = DateTime.Now
- });
- await dbContext.SaveChangesAsync();
- }
-
- await _userManager.SetAuthenticationTokenAsync(user, LoginProvider, RefreshToken, refreshToken);
-
- return Ok(new TokenModel() { Token = token, RefreshToken = refreshToken });
+ var tokenModel = await GenerateNewTokenForUser(user);
+ return Ok(tokenModel);
}
return Unauthorized();
}
@@ -82,36 +58,34 @@ public class AuthController : ControllerBase
}
// Check if the refresh token is valid.
- using (var dbContext = new AliasDbContext())
+ // Remove any existing refresh tokens for this user and device.
+ var deviceIdentifier = GenerateDeviceIdentifier(Request);
+ var existingToken = _context.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier).FirstOrDefault();
+ if (existingToken == null || existingToken.Value != tokenModel.RefreshToken || existingToken.ExpireDate < DateTime.Now)
{
- // Remove any existing refresh tokens for this user and device.
- var deviceIdentifier = GenerateDeviceIdentifier(Request);
- var existingToken = dbContext.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier).FirstOrDefault();
- if (existingToken == null || existingToken.Value != tokenModel.RefreshToken || existingToken.ExpireDate < DateTime.Now)
- {
- return Unauthorized("Refresh token expired");
- }
-
- // Remove the existing refresh token.
- dbContext.AspNetUserRefreshTokens.Remove(existingToken);
-
- // Generate a new refresh token to replace the old one.
- var newRefreshToken = GenerateRefreshToken();
-
- // Add new refresh token.
- dbContext.AspNetUserRefreshTokens.Add(new AspNetUserRefreshTokens
- {
- UserId = user.Id,
- DeviceIdentifier = deviceIdentifier,
- Value = newRefreshToken,
- ExpireDate = DateTime.Now.AddDays(30),
- CreatedAt = DateTime.Now
- });
- await dbContext.SaveChangesAsync();
-
- var token = GenerateJwtToken(user);
- return Ok(new TokenModel() { Token = token, RefreshToken = newRefreshToken });
+ return Unauthorized("Refresh token expired");
}
+
+ // Remove the existing refresh token.
+ _context.AspNetUserRefreshTokens.Remove(existingToken);
+
+ // Generate a new refresh token to replace the old one.
+ var newRefreshToken = GenerateRefreshToken();
+
+ // Add new refresh token.
+ _context.AspNetUserRefreshTokens.Add(new AspNetUserRefreshTokens
+ {
+ UserId = user.Id,
+ DeviceIdentifier = deviceIdentifier,
+ Value = newRefreshToken,
+ ExpireDate = DateTime.Now.AddDays(30),
+ CreatedAt = DateTime.Now
+ });
+ await _context.SaveChangesAsync();
+
+ var token = GenerateJwtToken(user);
+ return Ok(new TokenModel() { Token = token, RefreshToken = newRefreshToken });
+
}
[HttpPost("revoke")]
@@ -130,20 +104,17 @@ public class AuthController : ControllerBase
}
// Check if the refresh token is valid.
- using (var dbContext = new AliasDbContext())
+ var deviceIdentifier = GenerateDeviceIdentifier(Request);
+ var existingToken = _context.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier).FirstOrDefault();
+ if (existingToken == null || existingToken.Value != model.RefreshToken)
{
- var deviceIdentifier = GenerateDeviceIdentifier(Request);
- var existingToken = dbContext.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier).FirstOrDefault();
- if (existingToken == null || existingToken.Value != model.RefreshToken)
- {
- return Unauthorized("Invalid refresh token");
- }
-
- // Remove the existing refresh token.
- dbContext.AspNetUserRefreshTokens.Remove(existingToken);
- await dbContext.SaveChangesAsync();
+ return Unauthorized("Invalid refresh token");
}
+ // Remove the existing refresh token.
+ _context.AspNetUserRefreshTokens.Remove(existingToken);
+ await _context.SaveChangesAsync();
+
return Ok("Refresh token revoked successfully");
}
@@ -157,9 +128,10 @@ public class AuthController : ControllerBase
{
// When a user is registered, they are automatically signed in.
await _signInManager.SignInAsync(user, isPersistent: false);
+
// Return the token.
- var token = GenerateJwtToken(user);
- return Ok(new { token });
+ var tokenModel = await GenerateNewTokenForUser(user);
+ return Ok(tokenModel);
}
else
{
@@ -232,4 +204,31 @@ public class AuthController : ControllerBase
var rawIdentifier = $"{userAgent}|{acceptLanguage}";
return rawIdentifier;
}
+
+ private async Task<TokenModel> GenerateNewTokenForUser(IdentityUser user)
+ {
+ var token = GenerateJwtToken(user);
+ var refreshToken = GenerateRefreshToken();
+
+ // Generate device identifier
+ var deviceIdentifier = GenerateDeviceIdentifier(Request);
+
+ // Save refresh token to database.
+ // Remove any existing refresh tokens for this user and device.
+ var existingTokens = _context.AspNetUserRefreshTokens.Where(t => t.UserId == user.Id && t.DeviceIdentifier == deviceIdentifier);
+ _context.AspNetUserRefreshTokens.RemoveRange(existingTokens);
+
+ // Add new refresh token.
+ _context.AspNetUserRefreshTokens.Add(new AspNetUserRefreshTokens
+ {
+ UserId = user.Id,
+ DeviceIdentifier = deviceIdentifier,
+ Value = refreshToken,
+ ExpireDate = DateTime.Now.AddDays(30),
+ CreatedAt = DateTime.Now
+ });
+ await _context.SaveChangesAsync();
+
+ return new TokenModel() { Token = token, RefreshToken = refreshToken };
+ }
}
diff --git a/src/AliasVault.Api/Program.cs b/src/AliasVault.Api/Program.cs
index ac8d858b9..fdf7dfa7e 100644
--- a/src/AliasVault.Api/Program.cs
+++ b/src/AliasVault.Api/Program.cs
@@ -1,7 +1,10 @@
+using System.Data.Common;
using System.Text;
using AliasDb;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
+using Microsoft.Data.Sqlite;
+using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
@@ -18,7 +21,25 @@ builder.Services.AddLogging(logging =>
});
// Add services to the container.
-builder.Services.AddDbContextFactory<AliasDbContext>();
+builder.Services.AddSingleton<DbConnection>(container =>
+{
+ var configFile = new ConfigurationBuilder()
+ .SetBasePath(Directory.GetCurrentDirectory())
+ .AddJsonFile("appsettings.json")
+ .Build();
+
+ var connection = new SqliteConnection(configFile.GetConnectionString("AliasDbContext"));
+ connection.Open();
+
+ return connection;
+});
+
+builder.Services.AddDbContext<AliasDbContext>((container, options) =>
+{
+ var connection = container.GetRequiredService<DbConnection>();
+ options.UseSqlite(connection).UseLazyLoadingProxies();
+});
+
builder.Services.AddDataProtection();
builder.Services.Configure<DataProtectionTokenProviderOptions>(options =>
{
@@ -119,6 +140,27 @@ app.UseAuthorization();
app.MapControllers();
+using (var scope = app.Services.CreateScope())
+{
+ var container = scope.ServiceProvider;
+ var db = container.GetRequiredService<AliasDbContext>();
+
+ db.Database.EnsureCreated();
+
+ /*if (!db..Any())
+ {
+ try
+ {
+ db.Initialize();
+ }
+ catch (Exception ex)
+ {
+ var logger = container.GetRequiredService<ILogger<Program>>();
+ logger.LogError(ex, "An error occurred seeding the database. Error: {Message}", ex.Message);
+ }
+ }*/
+}
+
app.Run();
/// <summary>
diff --git a/src/AliasVault.WebApp/Auth/Pages/Register.razor b/src/AliasVault.WebApp/Auth/Pages/Register.razor
index 0ff63a1a9..eba047427 100644
--- a/src/AliasVault.WebApp/Auth/Pages/Register.razor
+++ b/src/AliasVault.WebApp/Auth/Pages/Register.razor
@@ -1,12 +1,15 @@
@page "/user/register"
@attribute [AllowAnonymous]
@layout Auth.Layout.MainLayout
+@using System.Text.Json
@using AliasVault.Shared.Models
@using AliasVault.WebApp.Auth.Components
+@using AliasVault.WebApp.Auth.Services
@inject HttpClient Http
@inject AuthenticationStateProvider AuthStateProvider
@inject ILocalStorageService LocalStorage
@inject NavigationManager NavigationManager
+@inject AuthService AuthService
<h2 class="text-2xl font-bold text-gray-900 dark:text-white">
@@ -24,15 +27,15 @@
</div>
<div>
<label asp-for="Input.Password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Confirm password</label>
- <InputTextField id="password" @bind-Value="user.PasswordConfirm" type="password" placeholder="••••••••" />
+ <InputTextField id="password2" @bind-Value="user.PasswordConfirm" type="password" placeholder="••••••••" />
</div>
<div class="flex items-start">
<div class="flex items-center h-5">
- <input id="remember" aria-describedby="remember" name="remember" type="checkbox" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" required>
+ <input id="terms" aria-describedby="terms" name="terms" type="checkbox" class="w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" required>
</div>
<div class="ml-3 text-sm">
- <label for="remember" class="font-medium text-gray-900 dark:text-white">I accept the <a href="#" class="text-primary-700 hover:underline dark:text-primary-500">Terms and Conditions</a></label>
+ <label for="terms" class="font-medium text-gray-900 dark:text-white">I accept the <a href="#" class="text-primary-700 hover:underline dark:text-primary-500">Terms and Conditions</a></label>
</div>
</div>
@@ -72,9 +75,22 @@
if (result.IsSuccessStatusCode)
{
- var token = await result.Content.ReadAsStringAsync();
- await LocalStorage.SetItemAsync("token", token);
- await AuthStateProvider.GetAuthenticationStateAsync();
+ var responseContent = await result.Content.ReadAsStringAsync();
+ var tokenObject = JsonSerializer.Deserialize<TokenModel>(responseContent);
+
+ if (tokenObject != null)
+ {
+ // Store the token as a plain string in local storage
+ await AuthService.StoreAccessTokenAsync(tokenObject.Token);
+ await AuthService.StoreRefreshTokenAsync(tokenObject.RefreshToken);
+ await AuthStateProvider.GetAuthenticationStateAsync();
+ }
+ else
+ {
+ // Handle the case where the token is not present in the response
+ Console.WriteLine("Token not found in the response.");
+ }
+
NavigationManager.NavigateTo("/");
}
else
diff --git a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
index a1c6cd141..f6d89937b 100644
--- a/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
+++ b/src/AliasVault.WebApp/Pages/Aliases/AddEdit.razor
@@ -259,6 +259,20 @@ else
obj.Service.Logo = await FaviconExtractor.FaviconService.GetFaviconAsync(obj.Service.Url);
} */
+ // Sanity check for unittest. Delete later if not needed.
+ // Try to parse birthdate as datetime. if it fails, set it to empty.
+ if (obj.Identity.BirthDate != null)
+ {
+ try
+ {
+ DateTime.Parse(obj.Identity.BirthDate);
+ }
+ catch (Exception)
+ {
+ obj.Identity.BirthDate = "1900-01-01";
+ }
+ }
+
if (EditMode)
{
await AliasService.UpdateAliasAsync(obj, Id.Value);
diff --git a/src/Tests/AliasVault.E2ETests/AliasTests.cs b/src/Tests/AliasVault.E2ETests/AliasTests.cs
new file mode 100644
index 000000000..71ae48593
--- /dev/null
+++ b/src/Tests/AliasVault.E2ETests/AliasTests.cs
@@ -0,0 +1,119 @@
+using Microsoft.Playwright;
+
+namespace AliasVault.E2ETests;
+
+[Parallelizable(ParallelScope.Self)]
+[TestFixture]
+public class AliasTests : PlaywrightTest
+{
+ /// <summary>
+ /// Test if registering a new account works.
+ /// </summary>
+ [Test]
+ public async Task AliasListingCorrect()
+ {
+ var navigationTask = Page.WaitForNavigationAsync();
+ await Page.GotoAsync(_appBaseUrl + "aliases");
+ await navigationTask;
+
+ // Wait for the content to load.
+ await Page.WaitForSelectorAsync("text=AliasVault");
+
+ // Check if the expected content is present.
+ var pageContent = await Page.TextContentAsync("body");
+ Assert.That(pageContent, Does.Contain("Find all of your aliases below"), "No index content after logging in.");
+ }
+
+ /// <summary>
+ /// Test if registering a new account works.
+ /// </summary>
+ [Test]
+ public async Task CreateAlias()
+ {
+ var navigationTask = Page.WaitForNavigationAsync();
+ await Page.GotoAsync(_appBaseUrl + "add-alias");
+ await navigationTask;
+
+ // Wait for the content to load.
+ await Page.WaitForSelectorAsync("text=AliasVault");
+
+ // Check if a button with text "Generate Random Identity" appears
+ var generateButton = Page.Locator("text=Generate Random Identity");
+ Assert.That(generateButton, Is.Not.Null, "Generate button not found.");
+
+ // Fill all input fields with random data
+ await FillAllInputFields(Page);
+
+ // Press submit button with text "Create Alias"
+ var submitButton = Page.Locator("text=Save Alias").First;
+ navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 200000 });
+ await submitButton.ClickAsync();
+ await navigationTask;
+
+ // Check if the redirection occurred
+ var currentUrl = Page.Url;
+ Assert.That(currentUrl, Does.Contain(_appBaseUrl + "alias/"));
+
+ // Wait for the content to load.
+ await Page.WaitForSelectorAsync("text=Login credentials");
+
+ // Check if the alias was created
+ var pageContent = await Page.TextContentAsync("body");
+ Assert.That(pageContent, Does.Contain("Login credentials"), "Alias not created.");
+
+ // TODO: Implement proper data input and verification if what was created is correct.
+ }
+
+ private static readonly Random Random = new Random();
+
+ public static async Task FillAllInputFields(IPage page)
+ {
+ // Locate all input fields
+ var inputFields = page.Locator("input");
+
+ // Get the count of input fields
+ var count = await inputFields.CountAsync();
+
+ // Iterate through each input field and fill with random data
+ for (int i = 0; i < count; i++)
+ {
+ var input = inputFields.Nth(i);
+ var inputType = await input.GetAttributeAsync("type");
+
+ // Generate appropriate random data based on input type
+ string randomData = inputType switch
+ {
+ "email" => GenerateRandomEmail(),
+ "number" => GenerateRandomNumber(),
+ "password" => GenerateRandomPassword(),
+ _ => GenerateRandomString() // Default for text, search, etc.
+ };
+
+ await input.FillAsync(randomData);
+ }
+ }
+
+ private static string GenerateRandomString(int length = 10)
+ {
+ const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
+ return new string(Enumerable.Repeat(chars, length)
+ .Select(s => s[Random.Next(s.Length)]).ToArray());
+ }
+
+ private static string GenerateRandomEmail()
+ {
+ return $"{GenerateRandomString(5)}@example.com";
+ }
+
+ private static string GenerateRandomNumber()
+ {
+ return Random.Next(0, 10000).ToString();
+ }
+
+ private static string GenerateRandomPassword(int length = 12)
+ {
+ const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
+ return new string(Enumerable.Repeat(chars, length)
+ .Select(s => s[Random.Next(s.Length)]).ToArray());
+ }
+}
diff --git a/src/Tests/AliasVault.E2ETests/AuthTests.cs b/src/Tests/AliasVault.E2ETests/AuthTests.cs
index fe6ab2796..cfaaa2a30 100644
--- a/src/Tests/AliasVault.E2ETests/AuthTests.cs
+++ b/src/Tests/AliasVault.E2ETests/AuthTests.cs
@@ -4,28 +4,47 @@ namespace AliasVault.E2ETests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
-public class Tests : PlaywrightTest
+public class AuthTests : PlaywrightTest
{
/// <summary>
- /// Test if the login screen is shown when the app is first started.
+ /// Test if registering a new account works.
/// </summary>
[Test]
+ public async Task LogoutAndLogin()
+ {
+ // Logout
+ var navigationTask = Page.WaitForNavigationAsync();
+ await Page.GotoAsync(_appBaseUrl + "user/logout");
+ await navigationTask;
+
+ // Wait for the content to load.
+ await Page.WaitForSelectorAsync("text=AliasVault");
+
+ // Check that we got redirected to /user/login
+ var currentUrl = Page.Url;
+ Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));
+
+ await Login();
+ }
+
+ /// <summary>
+ /// Test if logging in works.
+ /// </summary>
public async Task Login()
{
- // Replace with the URL where your Blazor app is running
- await Page.GotoAsync("http://localhost:5000");
+ await Page.GotoAsync(_appBaseUrl);
var navigationTask = Page.WaitForNavigationAsync();
await navigationTask;
// Check that we got redirected to /user/login
var currentUrl = Page.Url;
- Assert.That(currentUrl, Is.EqualTo("http://localhost:5000/user/login"));
+ Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));
// Try to login with test credentials.
var emailField = Page.Locator("input[id='email']");
var passwordField = Page.Locator("input[id='password']");
- await emailField.FillAsync("[email protected]");
- await passwordField.FillAsync("password");
+ await emailField.FillAsync(_randomEmail);
+ await passwordField.FillAsync(_randomPassword);
// Check if we get redirected when clicking on the login button.
var loginButton = Page.Locator("button[type='submit']");
@@ -35,7 +54,7 @@ public class Tests : PlaywrightTest
// Check if the redirection occurred
currentUrl = Page.Url;
- Assert.That(currentUrl, Is.EqualTo("http://localhost:5000/"));
+ Assert.That(currentUrl, Is.EqualTo(_appBaseUrl));
// Check if the login was successful by verifying content.
var pageContent = await Page.TextContentAsync("body");
diff --git a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
index 738fb72ba..af827010f 100644
--- a/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
+++ b/src/Tests/AliasVault.E2ETests/PlaywrightTest.cs
@@ -13,21 +13,34 @@ public class PlaywrightTest
private WebAppManager _webAppManager;
+ protected string _randomEmail = "";
+ protected string _randomPassword = "";
+ protected int apiPort = 5001;
+ protected int appPort = 5000;
+ protected string _appBaseUrl = "http://localhost:5000/";
+
/// <summary>
/// For starting the WebAPI project in-memory.
/// </summary>
private WebApplicationFactoryFixture<AliasVaultApiProgram> _factory = new();
- [SetUp]
- public async Task SetUp()
+ [OneTimeSetUp]
+ public async Task OneTimeSetUp()
{
_webAppManager = new WebAppManager();
- _factory.HostUrl = "http://localhost:5001";
+ // Determine random port for the WebAPI between 5000-5500
+ apiPort = new Random().Next(5000, 5500);
+ // Determine random port for the BlazorWasm which is apiPort + 1
+ appPort = apiPort + 1;
+ // Update base URL
+ _appBaseUrl = "http://localhost:" + appPort + "/";
+
+ _factory.HostUrl = "http://localhost:" + apiPort;
_factory.CreateDefaultClient();
//await _webAppManager.StartWebApiAsync(5001);
- await _webAppManager.StartBlazorWasmAsync( 5000);
+ await _webAppManager.StartBlazorWasmAsync(appPort);
var playwright = await Playwright.CreateAsync();
Browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });
@@ -38,7 +51,7 @@ public class PlaywrightTest
{
var response = new
{
- ApiUrl = "http://localhost:5001"
+ ApiUrl = "http://localhost:" + apiPort
};
await route.FulfillAsync(new RouteFulfillOptions
{
@@ -48,10 +61,13 @@ public class PlaywrightTest
});
Page = await Context.NewPageAsync();
+
+ // Register a new account via the UI
+ await Register();
}
- [TearDown]
- public async Task TearDown()
+ [OneTimeTearDown]
+ public async Task OneTimeTearDown()
{
await Page.CloseAsync();
await Context.CloseAsync();
@@ -61,4 +77,50 @@ public class PlaywrightTest
//_webAppManager.StopWebApi();
_webAppManager.StopBlazorWasm();
}
+
+ /// <summary>
+ /// Register a new random account.
+ /// </summary>
+ public async Task Register()
+ {
+ // Generate random email and password
+ _randomEmail = $"{Guid.NewGuid().ToString()}@test.com";
+ _randomPassword = Guid.NewGuid().ToString();
+
+ await Page.GotoAsync(_appBaseUrl);
+ var navigationTask = Page.WaitForNavigationAsync();
+ await navigationTask;
+
+ // Check that we got redirected to /user/login
+ var currentUrl = Page.Url;
+ Assert.That(currentUrl, Is.EqualTo(_appBaseUrl + "user/login"));
+
+ // Try to register a new account.
+ var registerButton = Page.Locator("a[href='/user/register']");
+ navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 2000 });
+ await registerButton.ClickAsync();
+ await navigationTask;
+
+ // Try to login with test credentials.
+ var emailField = Page.Locator("input[id='email']");
+ var passwordField = Page.Locator("input[id='password']");
+ var password2Field = Page.Locator("input[id='password2']");
+ await emailField.FillAsync(_randomEmail);
+ await passwordField.FillAsync(_randomPassword);
+ await password2Field.FillAsync(_randomPassword);
+
+ // Check the terms of service checkbox
+ var termsCheckbox = Page.Locator("input[id='terms']");
+ await termsCheckbox.CheckAsync();
+
+ // Check if we get redirected when clicking on the register button.
+ var submitButton = Page.Locator("button[type='submit']");
+ navigationTask = Page.WaitForNavigationAsync(new PageWaitForNavigationOptions() { Timeout = 200000});
+ await submitButton.ClickAsync();
+ await navigationTask;
+
+ // Check if the redirection occurred
+ currentUrl = Page.Url;
+ Assert.That(currentUrl, Is.EqualTo(_appBaseUrl));
+ }
}
diff --git a/src/Tests/AliasVault.E2ETests/WebAppManager.cs b/src/Tests/AliasVault.E2ETests/WebAppManager.cs
index 7cf252a0a..b6f0fd113 100644
--- a/src/Tests/AliasVault.E2ETests/WebAppManager.cs
+++ b/src/Tests/AliasVault.E2ETests/WebAppManager.cs
@@ -153,7 +153,7 @@ public class WebAppManager
#else
KillProcessAndChildrenUnix(_blazorWasmProcess.Id);
#endif
- _webApiProcess.Dispose();
+ _blazorWasmProcess.Dispose();
}
}
diff --git a/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs b/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs
index 6eaccaf6a..36cc5d086 100644
--- a/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs
+++ b/src/Tests/AliasVault.E2ETests/WebApplicationFactoryFixture.cs
@@ -1,8 +1,9 @@
+using System.Data.Common;
using AliasDb;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
+using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -19,21 +20,32 @@ public class WebApplicationFactoryFixture<TEntryPoint> : WebApplicationFactory<T
builder.ConfigureServices((context, services) =>
{
- var databaseFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.db");
- var connectionString = $"Data Source={Guid.NewGuid()}.db";
+ var dbContextDescriptor = services.SingleOrDefault(
+ d => d.ServiceType ==
+ typeof(DbContextOptions<AliasDbContext>));
- services.AddDbContextFactory<AliasDbContext>(options =>
+ services.Remove(dbContextDescriptor);
+
+ var dbConnectionDescriptor = services.SingleOrDefault(
+ d => d.ServiceType ==
+ typeof(DbConnection));
+
+ services.Remove(dbConnectionDescriptor);
+
+ // Create open SqliteConnection so EF won't automatically close it.
+ services.AddSingleton<DbConnection>(container =>
{
- options.UseSqlite(connectionString).UseLazyLoadingProxies();
+ var connection = new SqliteConnection("DataSource=:memory:");
+ connection.Open();
+
+ return connection;
});
- // Ensure the database is created
- var sp = services.BuildServiceProvider();
- using (var scope = sp.CreateScope())
+ services.AddDbContext<AliasDbContext>((container, options) =>
{
- var dbContext = scope.ServiceProvider.GetRequiredService<AliasDbContext>();
- dbContext.Database.EnsureCreated();
- }
+ var connection = container.GetRequiredService<DbConnection>();
+ options.UseSqlite(connection);
+ });
});
}