Refactor authentication system to use username instead of email; implement change password functionality and logging; add NLog for logging support
Some checks failed
Publish Container / publish (push) Failing after 1m9s

This commit is contained in:
MaddoScientisto 2026-03-17 20:08:02 +01:00
commit 6e3371514e
12 changed files with 287 additions and 45 deletions

View file

@ -1,10 +1,13 @@
using System.Globalization;
using System.Security.Claims;
using NLog.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Couchbase.Lite;
using WorkTracker.Components;
using WorkTracker.Configuration;
using WorkTracker.Services.Auth;
@ -14,6 +17,9 @@ using WorkTracker.Services.Storage;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Host.UseNLog();
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
@ -78,46 +84,173 @@ app.UseAuthorization();
app.UseAntiforgery();
app.MapPost("/login", async (HttpContext context, IAuthService authService) =>
app.MapPost("/api/login", async (HttpContext context) =>
{
var authService = context.RequestServices.GetRequiredService<IAuthService>();
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("Auth.Login");
var form = await context.Request.ReadFormAsync();
var email = form["email"].ToString();
var username = form["username"].ToString();
var password = form["password"].ToString();
var returnUrl = form["returnUrl"].ToString();
if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
return TypedResults.LocalRedirect($"/login?error=Missing%20credentials&returnUrl={Uri.EscapeDataString(returnUrl)}");
context.Response.Redirect($"/login?error=Missing%20credentials&returnUrl={Uri.EscapeDataString(returnUrl)}");
return;
}
var user = await authService.ValidateCredentialsAsync(email, password, context.RequestAborted);
var user = await authService.ValidateCredentialsAsync(username, password, context.RequestAborted);
if (user is null)
{
return TypedResults.LocalRedirect($"/login?error=Invalid%20credentials&returnUrl={Uri.EscapeDataString(returnUrl)}");
logger.LogWarning("Login failed for username {Username}", username);
context.Response.Redirect($"/login?error=Invalid%20credentials&returnUrl={Uri.EscapeDataString(returnUrl)}");
return;
}
var claims = new List<Claim>
{
new(ClaimTypes.NameIdentifier, user.Id),
new(ClaimTypes.Name, user.Email)
new(ClaimTypes.Name, user.Username)
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
// If the seeded or existing user must change password, redirect to change-password flow
if (user.MustChangePassword)
{
context.Response.Redirect("/change-password");
return;
}
var safeReturnUrl = string.IsNullOrWhiteSpace(returnUrl) || !Uri.IsWellFormedUriString(returnUrl, UriKind.Relative)
? "/"
: returnUrl;
return TypedResults.LocalRedirect(safeReturnUrl);
context.Response.Redirect(safeReturnUrl);
return;
}).DisableAntiforgery();
app.MapPost("/logout", async (HttpContext context) =>
app.MapPost("/api/logout", async (HttpContext context) =>
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return TypedResults.LocalRedirect("/login");
context.Response.Redirect("/login");
return;
}).DisableAntiforgery();
app.MapPost("/api/change-password", async (HttpContext context) =>
{
var authService = context.RequestServices.GetRequiredService<IAuthService>();
if (!context.User?.Identity?.IsAuthenticated ?? true)
{
await context.ChallengeAsync();
return;
}
var form = await context.Request.ReadFormAsync();
var newPassword = form["newPassword"].ToString();
var confirm = form["confirmPassword"].ToString();
if (string.IsNullOrWhiteSpace(newPassword) || string.IsNullOrWhiteSpace(confirm) || newPassword != confirm)
{
context.Response.Redirect("/change-password?error=Passwords%20do%20not%20match");
return;
}
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrWhiteSpace(userId))
{
await context.ChallengeAsync();
return;
}
var changed = await authService.ChangePasswordAsync(userId, newPassword, context.RequestAborted);
if (!changed)
{
context.Response.Redirect("/change-password?error=Unable%20to%20change%20password");
return;
}
context.Response.Redirect("/");
return;
}).DisableAntiforgery();
// Development-only endpoint to reset the seeded Admin password (protected by secret in URL)
if (app.Environment.IsDevelopment())
{
app.MapGet("/debug/reset-admin/{secret}", (HttpContext context, string secret) =>
{
const string expected = "81f58012-fe0b-4dcf-a638-77f9b99f92e3";
if (!string.Equals(secret, expected, StringComparison.Ordinal))
{
return Results.StatusCode(403);
}
var provider = context.RequestServices.GetRequiredService<CouchbaseLiteDatabaseProvider>();
var opts = context.RequestServices.GetRequiredService<IOptions<SingleUserOptions>>();
var username = opts.Value.Username.Trim();
var id = username.Trim().ToUpperInvariant();
// Hash the configured seed password
var passwordHasher = new Microsoft.AspNetCore.Identity.PasswordHasher<WorkTracker.Services.Auth.AuthUser>();
var tempUser = new WorkTracker.Services.Auth.AuthUser { Id = id, Username = username, UsernameNormalized = id };
var newHash = passwordHasher.HashPassword(tempUser, opts.Value.Password);
var doc = provider.Users.GetDocument(id);
if (doc is null)
{
var mutable = new MutableDocument(id);
mutable.SetString("username", username);
mutable.SetString("usernameNormalized", id);
mutable.SetString("passwordHash", newHash);
mutable.SetBoolean("mustChangePassword", true);
provider.Users.Save(mutable);
}
else
{
var mutable = doc.ToMutable();
mutable.SetString("passwordHash", newHash);
mutable.SetBoolean("mustChangePassword", true);
provider.Users.Save(mutable);
}
return Results.Json(new { ok = true, id, username });
});
app.MapGet("/debug/users/{secret}", (HttpContext context, string secret) =>
{
const string expected = "81f58012-fe0b-4dcf-a638-77f9b99f92e3";
if (!string.Equals(secret, expected, StringComparison.Ordinal))
{
return Results.StatusCode(403);
}
var provider = context.RequestServices.GetRequiredService<CouchbaseLiteDatabaseProvider>();
var opts = context.RequestServices.GetRequiredService<IOptions<SingleUserOptions>>();
var username = opts.Value.Username.Trim();
var id = username.Trim().ToUpperInvariant();
var doc = provider.Users.GetDocument(id);
if (doc is null)
{
return Results.NotFound();
}
var result = new
{
id = doc.Id,
username = doc.GetString("username") ?? doc.GetString("email"),
usernameNormalized = doc.GetString("usernameNormalized") ?? doc.GetString("emailNormalized"),
passwordHash = doc.GetString("passwordHash"),
mustChangePassword = doc.GetBoolean("mustChangePassword")
};
return Results.Json(result);
});
}
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();