Feature/breadboard #4

Merged
jheaps merged 25 commits from feature/breadboard into master 2026-08-26 17:36:05 -06:00
10 changed files with 571 additions and 6 deletions
Showing only changes of commit c173677f57 - Show all commits
@@ -0,0 +1,12 @@
CREATE TABLE app.password_reset_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
token_hash VARCHAR(64) NOT NULL,
created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ NULL,
FOREIGN KEY (user_id) REFERENCES app.users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_prt_token_hash ON app.password_reset_tokens(token_hash);
CREATE INDEX IF NOT EXISTS idx_prt_user_id ON app.password_reset_tokens(user_id);
+1
View File
@@ -21,6 +21,7 @@
</a> </a>
<h1>Welcome back, @Model.Dashboard?.Username!</h1> <h1>Welcome back, @Model.Dashboard?.Username!</h1>
</div> </div>
<div class="quick-actions"> <div class="quick-actions">
@if (Model.Dashboard?.EmailVerified == false) @if (Model.Dashboard?.EmailVerified == false)
{ {
+3
View File
@@ -60,11 +60,14 @@
<div class="invalid-feedback"></div> <div class="invalid-feedback"></div>
</div> </div>
<div class="form-options">
<div class="checkbox-wrapper"> <div class="checkbox-wrapper">
<input type="checkbox" id="rememberMe" name="rememberMe" <input type="checkbox" id="rememberMe" name="rememberMe"
@(Model.RememberMe ? "checked" : "") /> @(Model.RememberMe ? "checked" : "") />
<label for="rememberMe">Remember me</label> <label for="rememberMe">Remember me</label>
</div> </div>
<a href="/LoginHelp" class="forgot-password-link">Forgot password?</a>
</div>
<button type="submit" class="btn-primary">Sign In</button> <button type="submit" class="btn-primary">Sign In</button>
</form> </form>
+7 -1
View File
@@ -20,7 +20,7 @@ public class LoginModel(AuthService authService) : PageModel
public string? SuccessMessage { get; set; } public string? SuccessMessage { get; set; }
public string? WarningMessage { get; set; } public string? WarningMessage { get; set; }
public void OnGet([FromQuery] string? registered, [FromQuery] string? verified) public void OnGet([FromQuery] string? registered, [FromQuery] string? verified, [FromQuery] string? reset)
{ {
// Check if user is already logged in // Check if user is already logged in
var userId = HttpContext.Session.GetString("UserId"); var userId = HttpContext.Session.GetString("UserId");
@@ -41,6 +41,12 @@ public class LoginModel(AuthService authService) : PageModel
{ {
SuccessMessage = "Email verified! You can now sign in."; SuccessMessage = "Email verified! You can now sign in.";
} }
// Show success message if password was just reset
if (reset == "true")
{
SuccessMessage = "Your password has been reset. You can now sign in with your new password.";
}
} }
public async Task<IActionResult> OnPostAsync() public async Task<IActionResult> OnPostAsync()
+102
View File
@@ -0,0 +1,102 @@
@page
@model Media.JoshHeaps.Net.Pages.LoginHelpModel
@{
ViewData["Title"] = "Login Help";
Layout = "_Layout";
}
@section Styles {
<link rel="stylesheet" href="~/css/auth.css" asp-append-version="true" />
}
@section Scripts {
<script src="~/js/auth.js" asp-append-version="true"></script>
}
<div class="auth-container">
<div class="auth-card">
@if (Model.ShowResetForm)
{
<div class="auth-header">
<h1>Reset Password</h1>
<p>Enter your new password below</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
<form id="resetPasswordForm" method="post" asp-page-handler="ResetPassword">
@Html.AntiForgeryToken()
<input type="hidden" name="Token" value="@Model.Token" />
<div class="form-group">
<label for="newPassword" class="form-label">New Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="newPassword" name="NewPassword"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
<div class="password-strength">
<div class="password-strength-bar"></div>
</div>
<div class="password-strength-text"></div>
</div>
<div class="form-group">
<label for="confirmPassword" class="form-label">Confirm Password</label>
<div class="password-wrapper">
<input type="password" class="form-control" id="confirmPassword" name="ConfirmPassword"
autocomplete="new-password" required minlength="8" />
<button type="button" class="password-toggle">Show</button>
</div>
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Reset Password</button>
</form>
}
else
{
<div class="auth-header">
<h1>Forgot Password</h1>
<p>Enter your email to receive a reset link</p>
</div>
@if (!string.IsNullOrEmpty(Model.ErrorMessage))
{
<div class="alert alert-danger">
@Model.ErrorMessage
</div>
}
@if (!string.IsNullOrEmpty(Model.SuccessMessage))
{
<div class="alert alert-success">
@Model.SuccessMessage
</div>
}
<form id="requestResetForm" method="post" asp-page-handler="RequestReset">
@Html.AntiForgeryToken()
<div class="form-group">
<label for="email" class="form-label">Email Address</label>
<input type="email" class="form-control" id="email" name="Email"
value="@Model.Email" autocomplete="email" required />
<div class="invalid-feedback"></div>
</div>
<button type="submit" class="btn-primary">Send Reset Link</button>
</form>
}
<div class="auth-footer">
<p>Remember your password? <a href="/Login">Sign in</a></p>
</div>
</div>
</div>
@@ -0,0 +1,111 @@
using Media.JoshHeaps.Net.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Media.JoshHeaps.Net.Pages;
public class LoginHelpModel(AuthService authService, EmailService emailService, ILogger<LoginHelpModel> logger) : PageModel
{
[BindProperty]
public string Email { get; set; } = string.Empty;
[BindProperty]
public string Token { get; set; } = string.Empty;
[BindProperty]
public string NewPassword { get; set; } = string.Empty;
[BindProperty]
public string ConfirmPassword { get; set; } = string.Empty;
public string? ErrorMessage { get; set; }
public string? SuccessMessage { get; set; }
public bool ShowResetForm { get; set; }
public async Task<IActionResult> OnGetAsync([FromQuery] string? token)
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (!string.IsNullOrEmpty(token))
{
var (valid, error) = await authService.ValidatePasswordResetTokenAsync(token);
if (valid)
{
ShowResetForm = true;
Token = token;
}
else
{
ErrorMessage = error;
}
}
return Page();
}
public async Task<IActionResult> OnPostRequestResetAsync()
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (string.IsNullOrWhiteSpace(Email))
{
ErrorMessage = "Please enter your email address.";
return Page();
}
var (success, error, token, username) = await authService.RequestPasswordResetAsync(Email.Trim());
if (!success)
{
logger.LogError("Password reset request failed for {Email}: {Error}", Email, error);
}
// Send email if we got a token back (user exists and is eligible)
if (token != null)
{
await emailService.SendPasswordResetEmailAsync(Email.Trim(), username ?? Email.Split('@')[0], token);
}
// Always show the same message regardless of whether the email exists
SuccessMessage = "If an account exists with that email, you will receive a password reset link shortly.";
return Page();
}
public async Task<IActionResult> OnPostResetPasswordAsync()
{
// Redirect if already logged in
var userId = HttpContext.Session.GetString("UserId");
if (!string.IsNullOrEmpty(userId))
return Redirect("/Landing");
if (string.IsNullOrWhiteSpace(NewPassword) || NewPassword.Length < 8)
{
ErrorMessage = "Password must be at least 8 characters.";
ShowResetForm = true;
return Page();
}
if (NewPassword != ConfirmPassword)
{
ErrorMessage = "Passwords do not match.";
ShowResetForm = true;
return Page();
}
var (success, error) = await authService.ResetPasswordAsync(Token, NewPassword);
if (!success)
{
ErrorMessage = error;
return Page();
}
return Redirect("/Login?reset=true");
}
}
+171
View File
@@ -1,3 +1,5 @@
using System.Security.Cryptography;
using System.Text;
using Media.JoshHeaps.Net; using Media.JoshHeaps.Net;
using Media.JoshHeaps.Net.Models; using Media.JoshHeaps.Net.Models;
@@ -302,4 +304,173 @@ public class AuthService(DbExecutor db)
new { userId, lastLogin = DateTime.UtcNow } new { userId, lastLogin = DateTime.UtcNow }
); );
} }
public static string GenerateSecureToken()
{
var bytes = RandomNumberGenerator.GetBytes(32);
return Convert.ToBase64String(bytes)
.Replace("+", "-")
.Replace("/", "_")
.TrimEnd('=');
}
public static string HashToken(string token)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(token));
return Convert.ToHexString(bytes).ToLowerInvariant();
}
public async Task<(bool Success, string? Error, string? Token, string? Username)> RequestPasswordResetAsync(string email)
{
try
{
var userRow = await db.ExecuteReaderAsync(
"SELECT id, username, is_active, locked_until FROM app.users WHERE email = @email",
reader => new
{
UserId = reader.GetInt64(0),
Username = reader.GetString(1),
IsActive = reader.GetBoolean(2),
LockedUntil = reader.IsDBNull(3) ? (DateTime?)null : reader.GetDateTime(3)
},
new { email }
);
if (userRow == null)
{
// Artificial delay to prevent timing-based email enumeration
await Task.Delay(Random.Shared.Next(100, 300));
return (true, null, null, null);
}
// Silently succeed for inactive/locked accounts (don't reveal state)
if (!userRow.IsActive ||
(userRow.LockedUntil.HasValue && userRow.LockedUntil.Value > DateTime.UtcNow))
{
return (true, null, null, null);
}
// Rate limit: max 3 requests per hour
var recentCount = await db.ExecuteAsync<long>(
@"SELECT COUNT(*) FROM app.password_reset_tokens
WHERE user_id = @userId AND created_at > @cutoff",
new { userId = userRow.UserId, cutoff = DateTimeOffset.UtcNow.AddHours(-1) }
);
if (recentCount >= 3)
{
return (true, null, null, null);
}
// Invalidate all existing unused tokens for this user
await db.ExecuteNonQueryAsync(
@"UPDATE app.password_reset_tokens
SET used_at = @now
WHERE user_id = @userId AND used_at IS NULL",
new { userId = userRow.UserId, now = DateTimeOffset.UtcNow }
);
// Generate and store new token
var token = GenerateSecureToken();
var tokenHash = HashToken(token);
var expiresAt = DateTimeOffset.UtcNow.AddHours(1);
await db.ExecuteNonQueryAsync(
@"INSERT INTO app.password_reset_tokens (user_id, token_hash, expires_at)
VALUES (@userId, @tokenHash, @expiresAt)",
new { userId = userRow.UserId, tokenHash, expiresAt }
);
return (true, null, token, userRow.Username);
}
catch (Exception ex)
{
return (false, $"Password reset request failed: {ex.Message}", null, null);
}
}
public async Task<(bool Valid, string? Error)> ValidatePasswordResetTokenAsync(string token)
{
try
{
var tokenHash = HashToken(token);
var tokenRow = await db.ExecuteReaderAsync(
@"SELECT expires_at, used_at FROM app.password_reset_tokens
WHERE token_hash = @tokenHash",
reader => new
{
ExpiresAt = reader.GetFieldValue<DateTimeOffset>(0),
UsedAt = reader.IsDBNull(1) ? (DateTimeOffset?)null : reader.GetFieldValue<DateTimeOffset>(1)
},
new { tokenHash }
);
if (tokenRow == null)
return (false, "Invalid or expired reset link. Please request a new one.");
if (tokenRow.UsedAt.HasValue)
return (false, "This reset link has already been used. Please request a new one.");
if (tokenRow.ExpiresAt < DateTimeOffset.UtcNow)
return (false, "This reset link has expired. Please request a new one.");
return (true, null);
}
catch (Exception ex)
{
return (false, $"Token validation failed: {ex.Message}");
}
}
public async Task<(bool Success, string? Error)> ResetPasswordAsync(string token, string newPassword)
{
try
{
var tokenHash = HashToken(token);
var tokenRow = await db.ExecuteReaderAsync(
@"SELECT id, user_id, expires_at, used_at FROM app.password_reset_tokens
WHERE token_hash = @tokenHash",
reader => new
{
Id = reader.GetInt64(0),
UserId = reader.GetInt64(1),
ExpiresAt = reader.GetFieldValue<DateTimeOffset>(2),
UsedAt = reader.IsDBNull(3) ? (DateTimeOffset?)null : reader.GetFieldValue<DateTimeOffset>(3)
},
new { tokenHash }
);
if (tokenRow == null)
return (false, "Invalid or expired reset link. Please request a new one.");
if (tokenRow.UsedAt.HasValue)
return (false, "This reset link has already been used. Please request a new one.");
if (tokenRow.ExpiresAt < DateTimeOffset.UtcNow)
return (false, "This reset link has expired. Please request a new one.");
// Hash new password and update user
var passwordHash = HashPassword(newPassword);
await db.ExecuteNonQueryAsync(
@"UPDATE app.users
SET password_hash = @passwordHash, failed_login_attempts = 0, locked_until = NULL
WHERE id = @userId",
new { userId = tokenRow.UserId, passwordHash }
);
// Mark token as used
await db.ExecuteNonQueryAsync(
"UPDATE app.password_reset_tokens SET used_at = @now WHERE id = @tokenId",
new { tokenId = tokenRow.Id, now = DateTimeOffset.UtcNow }
);
return (true, null);
}
catch (Exception ex)
{
return (false, $"Password reset failed: {ex.Message}");
}
}
} }
+1 -1
View File
@@ -107,7 +107,7 @@ If you didn't create an account, you can safely ignore this email.
try try
{ {
var appUrl = config["AppUrl"] ?? "http://localhost:5000"; var appUrl = config["AppUrl"] ?? "http://localhost:5000";
var resetUrl = $"{appUrl}/ResetPassword?token={resetToken}"; var resetUrl = $"{appUrl}/LoginHelp?token={resetToken}";
var message = new MimeMessage(); var message = new MimeMessage();
message.From.Add(new MailboxAddress( message.From.Add(new MailboxAddress(
+23
View File
@@ -152,6 +152,29 @@
display: block; display: block;
} }
.form-options {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
.form-options .checkbox-wrapper {
margin-bottom: 0;
}
.forgot-password-link {
color: var(--text-secondary);
font-size: 13px;
text-decoration: none;
transition: color 0.2s ease;
}
.forgot-password-link:hover {
color: var(--accent-primary);
text-decoration: underline;
}
.checkbox-wrapper { .checkbox-wrapper {
display: flex; display: flex;
align-items: center; align-items: center;
+136
View File
@@ -336,9 +336,145 @@ function initRegisterForm() {
}); });
} }
// Password reset form validation
function initPasswordResetForm() {
const form = document.getElementById('resetPasswordForm');
if (!form) return;
const passwordInput = document.getElementById('newPassword');
const confirmPasswordInput = document.getElementById('confirmPassword');
if (passwordInput) {
passwordInput.addEventListener('input', function() {
checkPasswordStrength(this.value);
if (this.value && validatePassword(this.value)) {
clearError(this);
}
if (confirmPasswordInput && confirmPasswordInput.value) {
if (confirmPasswordInput.value === this.value) {
clearError(confirmPasswordInput);
} else {
showError(confirmPasswordInput, 'Passwords do not match');
}
}
});
passwordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Password is required');
} else if (!validatePassword(this.value)) {
showError(this, 'Password must be at least 8 characters');
} else {
clearError(this);
}
});
}
if (confirmPasswordInput) {
confirmPasswordInput.addEventListener('input', function() {
if (passwordInput && this.value === passwordInput.value) {
clearError(this);
}
});
confirmPasswordInput.addEventListener('blur', function() {
if (!this.value) {
showError(this, 'Please confirm your password');
} else if (passwordInput && this.value !== passwordInput.value) {
showError(this, 'Passwords do not match');
} else {
clearError(this);
}
});
}
form.addEventListener('submit', function(e) {
e.preventDefault();
let isValid = true;
if (!passwordInput.value) {
showError(passwordInput, 'Password is required');
isValid = false;
} else if (!validatePassword(passwordInput.value)) {
showError(passwordInput, 'Password must be at least 8 characters');
isValid = false;
} else {
clearError(passwordInput);
}
if (!confirmPasswordInput.value) {
showError(confirmPasswordInput, 'Please confirm your password');
isValid = false;
} else if (confirmPasswordInput.value !== passwordInput.value) {
showError(confirmPasswordInput, 'Passwords do not match');
isValid = false;
} else {
clearError(confirmPasswordInput);
}
if (isValid) {
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Resetting...';
form.submit();
}
});
}
// Request reset form validation
function initRequestResetForm() {
const form = document.getElementById('requestResetForm');
if (!form) return;
const emailInput = document.getElementById('email');
if (emailInput) {
emailInput.addEventListener('blur', function() {
if (!this.value.trim()) {
showError(this, 'Email is required');
} else if (!validateEmail(this.value)) {
showError(this, 'Please enter a valid email address');
} else {
clearError(this);
}
});
emailInput.addEventListener('input', function() {
if (this.value.trim() && validateEmail(this.value)) {
clearError(this);
}
});
}
form.addEventListener('submit', function(e) {
e.preventDefault();
if (!emailInput.value.trim()) {
showError(emailInput, 'Email is required');
return;
}
if (!validateEmail(emailInput.value)) {
showError(emailInput, 'Please enter a valid email address');
return;
}
clearError(emailInput);
const submitBtn = form.querySelector('button[type="submit"]');
submitBtn.disabled = true;
submitBtn.innerHTML = '<span class="spinner"></span> Sending...';
form.submit();
});
}
// Initialize on page load // Initialize on page load
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
initPasswordToggles(); initPasswordToggles();
initLoginForm(); initLoginForm();
initRegisterForm(); initRegisterForm();
initPasswordResetForm();
initRequestResetForm();
}); });