Add email-based password reset flow

Users who forget their password can now request a reset link via email.
Tokens are SHA-256 hashed before storage, expire after 1 hour, and
previous unused tokens are invalidated on new requests. The forgot-password
endpoint always returns success to prevent email enumeration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-13 21:42:45 -05:00
parent d874e0e2ae
commit d354da5b51
11 changed files with 661 additions and 1 deletions
@@ -0,0 +1,25 @@
"""Add password_reset_tokens table."""
from alembic import op
revision = "0011"
down_revision = "0010"
def upgrade() -> None:
op.execute("""
CREATE TABLE password_reset_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
used BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
op.execute("CREATE INDEX ix_password_reset_tokens_token_hash ON password_reset_tokens (token_hash)")
op.execute("CREATE INDEX ix_password_reset_tokens_user_id ON password_reset_tokens (user_id)")
def downgrade() -> None:
op.execute("DROP TABLE IF EXISTS password_reset_tokens")
+12
View File
@@ -22,6 +22,18 @@ const router = createRouter({
component: () => import("@/views/RegisterView.vue"),
meta: { public: true },
},
{
path: "/forgot-password",
name: "forgot-password",
component: () => import("@/views/ForgotPasswordView.vue"),
meta: { public: true },
},
{
path: "/reset-password",
name: "reset-password",
component: () => import("@/views/ResetPasswordView.vue"),
meta: { public: true },
},
{
path: "/notes",
name: "notes",
+167
View File
@@ -0,0 +1,167 @@
<script setup lang="ts">
import { ref } from "vue";
import { apiPost } from "@/api/client";
import AppLogo from "@/components/AppLogo.vue";
const email = ref("");
const error = ref("");
const submitted = ref(false);
const submitting = ref(false);
async function handleSubmit() {
error.value = "";
submitting.value = true;
try {
await apiPost("/api/auth/forgot-password", { email: email.value });
submitted.value = true;
} catch (e: unknown) {
if (e && typeof e === "object" && "body" in e) {
const body = (e as { body?: { error?: string } }).body;
error.value = body?.error || "Something went wrong";
} else {
error.value = "Something went wrong";
}
} finally {
submitting.value = false;
}
}
</script>
<template>
<main class="auth-page">
<div class="auth-card">
<div class="auth-brand"><AppLogo :size="32" /><h1>Reset Password</h1></div>
<template v-if="!submitted">
<p class="auth-hint">
Enter the email address associated with your account and we'll send you a link to reset your password.
</p>
<form @submit.prevent="handleSubmit">
<div class="field">
<label for="email">Email</label>
<input
id="email"
v-model="email"
type="email"
autocomplete="email"
required
class="input"
/>
</div>
<p v-if="error" class="error-msg">{{ error }}</p>
<button type="submit" class="btn-submit" :disabled="submitting">
{{ submitting ? "Sending..." : "Send Reset Link" }}
</button>
</form>
</template>
<div v-else class="success-msg">
<p>If an account exists with that email address, you will receive a password reset link shortly.</p>
<p>Check your email and follow the instructions to reset your password.</p>
</div>
<p class="auth-footer">
<router-link to="/login">Back to Sign In</router-link>
</p>
</div>
</main>
</template>
<style scoped>
.auth-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 1rem;
}
.auth-card {
width: 100%;
max-width: 400px;
background: var(--color-bg-card);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
padding: 2rem;
}
.auth-brand {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.auth-card h1 {
margin: 0;
text-align: center;
}
.auth-hint {
text-align: center;
font-size: 0.9rem;
color: var(--color-text-secondary);
margin-bottom: 1rem;
}
.field {
margin-bottom: 1rem;
}
.field label {
display: block;
font-size: 0.9rem;
font-weight: 600;
margin-bottom: 0.35rem;
}
.input {
width: 100%;
padding: 0.5rem 0.75rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
font-size: 0.95rem;
background: var(--color-bg);
color: var(--color-text);
box-sizing: border-box;
}
.input:focus {
outline: none;
border-color: var(--color-primary);
}
.error-msg {
color: var(--color-danger);
font-size: 0.9rem;
margin: 0 0 0.75rem;
}
.success-msg {
text-align: center;
color: var(--color-text-secondary);
font-size: 0.95rem;
padding: 0.5rem 0;
}
.success-msg p {
margin: 0.5rem 0;
}
.btn-submit {
width: 100%;
padding: 0.6rem;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.95rem;
font-weight: 600;
}
.btn-submit:disabled {
opacity: 0.6;
cursor: default;
}
.btn-submit:hover:not(:disabled) {
opacity: 0.9;
}
.auth-footer {
text-align: center;
font-size: 0.9rem;
color: var(--color-text-secondary);
margin: 1rem 0 0;
}
.auth-footer a {
color: var(--color-primary);
}
</style>
+14
View File
@@ -69,6 +69,9 @@ async function handleSubmit() {
class="input"
/>
</div>
<p class="forgot-link">
<router-link to="/forgot-password">Forgot your password?</router-link>
</p>
<p v-if="error" class="error-msg">{{ error }}</p>
<button type="submit" class="btn-submit" :disabled="submitting">
{{ submitting ? "Signing in..." : "Sign In" }}
@@ -173,4 +176,15 @@ async function handleSubmit() {
.auth-footer a {
color: var(--color-primary);
}
.forgot-link {
text-align: right;
margin: -0.5rem 0 0.75rem;
font-size: 0.85rem;
}
.forgot-link a {
color: var(--color-text-secondary);
}
.forgot-link a:hover {
color: var(--color-primary);
}
</style>
+225
View File
@@ -0,0 +1,225 @@
<script setup lang="ts">
import { ref, computed } from "vue";
import { useRoute } from "vue-router";
import { apiPost } from "@/api/client";
import AppLogo from "@/components/AppLogo.vue";
const route = useRoute();
const token = computed(() => (route.query.token as string) || "");
const password = ref("");
const confirmPassword = ref("");
const error = ref("");
const submitting = ref(false);
const success = ref(false);
const passwordMismatch = computed(
() => confirmPassword.value.length > 0 && password.value !== confirmPassword.value
);
const canSubmit = computed(
() => !submitting.value && !passwordMismatch.value && password.value.length >= 8 && !!token.value
);
async function handleSubmit() {
if (passwordMismatch.value) {
error.value = "Passwords do not match";
return;
}
error.value = "";
submitting.value = true;
try {
await apiPost("/api/auth/reset-password", {
token: token.value,
new_password: password.value,
});
success.value = true;
} catch (e: unknown) {
if (e && typeof e === "object" && "body" in e) {
const body = (e as { body?: { error?: string } }).body;
error.value = body?.error || "Failed to reset password";
} else {
error.value = "Failed to reset password";
}
} finally {
submitting.value = false;
}
}
</script>
<template>
<main class="auth-page">
<div class="auth-card">
<div class="auth-brand"><AppLogo :size="32" /><h1>Set New Password</h1></div>
<div v-if="!token" class="error-block">
<p>Invalid reset link. Please request a new password reset.</p>
<p class="auth-footer">
<router-link to="/forgot-password">Request new link</router-link>
</p>
</div>
<template v-else-if="!success">
<form @submit.prevent="handleSubmit">
<div class="field">
<label for="password">New Password</label>
<input
id="password"
v-model="password"
type="password"
autocomplete="new-password"
required
minlength="8"
class="input"
/>
<p class="field-hint">Must be at least 8 characters</p>
</div>
<div class="field">
<label for="confirm-password">Confirm Password</label>
<input
id="confirm-password"
v-model="confirmPassword"
type="password"
autocomplete="new-password"
required
class="input"
:class="{ 'input-error': passwordMismatch }"
/>
<p v-if="passwordMismatch" class="error-hint">Passwords do not match</p>
</div>
<p v-if="error" class="error-msg">{{ error }}</p>
<button type="submit" class="btn-submit" :disabled="!canSubmit">
{{ submitting ? "Resetting..." : "Reset Password" }}
</button>
</form>
</template>
<div v-else class="success-msg">
<p>Your password has been reset successfully.</p>
<p>You can now sign in with your new password.</p>
</div>
<p class="auth-footer">
<router-link to="/login">Back to Sign In</router-link>
</p>
</div>
</main>
</template>
<style scoped>
.auth-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 1rem;
}
.auth-card {
width: 100%;
max-width: 400px;
background: var(--color-bg-card);
border: 1px solid var(--color-border);
border-radius: var(--radius-md);
padding: 2rem;
}
.auth-brand {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin-bottom: 1.5rem;
}
.auth-card h1 {
margin: 0;
text-align: center;
}
.error-block {
text-align: center;
color: var(--color-text-secondary);
font-size: 0.95rem;
padding: 0.5rem 0;
}
.error-block p {
margin: 0.5rem 0;
}
.success-msg {
text-align: center;
color: var(--color-text-secondary);
font-size: 0.95rem;
padding: 0.5rem 0;
}
.success-msg p {
margin: 0.5rem 0;
}
.field {
margin-bottom: 1rem;
}
.field label {
display: block;
font-size: 0.9rem;
font-weight: 600;
margin-bottom: 0.35rem;
}
.input {
width: 100%;
padding: 0.5rem 0.75rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
font-size: 0.95rem;
background: var(--color-bg);
color: var(--color-text);
box-sizing: border-box;
}
.input:focus {
outline: none;
border-color: var(--color-primary);
}
.input-error {
border-color: var(--color-danger);
}
.input-error:focus {
border-color: var(--color-danger);
}
.field-hint {
margin: 0.35rem 0 0;
font-size: 0.8rem;
color: var(--color-text-muted);
}
.error-hint {
margin: 0.35rem 0 0;
font-size: 0.8rem;
color: var(--color-danger);
}
.error-msg {
color: var(--color-danger);
font-size: 0.9rem;
margin: 0 0 0.75rem;
}
.btn-submit {
width: 100%;
padding: 0.6rem;
background: var(--color-primary);
color: #fff;
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.95rem;
font-weight: 600;
}
.btn-submit:disabled {
opacity: 0.6;
cursor: default;
}
.btn-submit:hover:not(:disabled) {
opacity: 0.9;
}
.auth-footer {
text-align: center;
font-size: 0.9rem;
color: var(--color-text-secondary);
margin: 1rem 0 0;
}
.auth-footer a {
color: var(--color-primary);
}
</style>
+1
View File
@@ -37,3 +37,4 @@ class Config:
SMTP_FROM_ADDRESS: str = os.environ.get("SMTP_FROM_ADDRESS", "")
SMTP_FROM_NAME: str = os.environ.get("SMTP_FROM_NAME", "Fabled Assistant")
SMTP_USE_TLS: bool = os.environ.get("SMTP_USE_TLS", "true").lower() in ("1", "true", "yes")
BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/")
+1
View File
@@ -16,3 +16,4 @@ from fabledassistant.models.conversation import Conversation, Message # noqa: E
from fabledassistant.models.setting import Setting # noqa: E402, F401
from fabledassistant.models.user import User # noqa: E402, F401
from fabledassistant.models.app_log import AppLog # noqa: E402, F401
from fabledassistant.models.password_reset import PasswordResetToken # noqa: E402, F401
@@ -0,0 +1,24 @@
from datetime import datetime, timezone
from sqlalchemy import Boolean, DateTime, ForeignKey, Index, Text
from sqlalchemy.orm import Mapped, mapped_column
from fabledassistant.models import Base
class PasswordResetToken(Base):
__tablename__ = "password_reset_tokens"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
token_hash: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
used: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
)
__table_args__ = (
Index("ix_password_reset_tokens_token_hash", "token_hash"),
Index("ix_password_reset_tokens_user_id", "user_id"),
)
+76 -1
View File
@@ -3,17 +3,26 @@ import asyncio
from quart import Blueprint, g, jsonify, request, session
from fabledassistant.auth import login_required, get_current_user_id
from fabledassistant.config import Config
from fabledassistant.services.auth import (
authenticate,
change_password,
create_password_reset_token,
create_user,
get_user_by_email,
get_user_by_id,
get_user_by_username,
get_user_count,
is_registration_open,
reset_password_with_token,
)
from fabledassistant.services.logging import log_audit
from fabledassistant.services.notifications import notify_security_event
from fabledassistant.services.notifications import (
notify_security_event,
send_password_reset_email,
send_password_reset_success_email,
)
from fabledassistant.services.email import is_smtp_configured
auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
@@ -121,6 +130,72 @@ async def update_password():
return jsonify({"status": "ok"})
@auth_bp.route("/forgot-password", methods=["POST"])
async def forgot_password():
data = await request.get_json()
email = (data.get("email") or "").strip().lower()
if not email:
return jsonify({"error": "Email is required"}), 400
# Always return success to prevent email enumeration
user = await get_user_by_email(email)
if user and await is_smtp_configured():
raw_token = await create_password_reset_token(user.id)
reset_url = f"{Config.BASE_URL}/reset-password?token={raw_token}"
asyncio.create_task(send_password_reset_email(user.email, reset_url))
await log_audit(
"password_reset_requested",
user_id=user.id,
username=user.username,
ip_address=request.remote_addr,
)
return jsonify({"status": "ok"})
@auth_bp.route("/reset-password", methods=["POST"])
async def reset_password():
data = await request.get_json()
token = (data.get("token") or "").strip()
new_password = data.get("new_password") or ""
if not token:
return jsonify({"error": "Reset token is required"}), 400
if len(new_password) < 8:
return jsonify({"error": "Password must be at least 8 characters"}), 400
success = await reset_password_with_token(token, new_password)
if not success:
return jsonify({"error": "Invalid or expired reset link"}), 400
# Look up user by token to send notifications (token is now used, so look up by hash)
import hashlib
from fabledassistant.models import async_session
from fabledassistant.models.password_reset import PasswordResetToken
from sqlalchemy import select
token_hash = hashlib.sha256(token.encode()).hexdigest()
async with async_session() as session:
result = await session.execute(
select(PasswordResetToken).where(PasswordResetToken.token_hash == token_hash)
)
reset_token = result.scalars().first()
if reset_token:
user = await get_user_by_id(reset_token.user_id)
if user:
await log_audit(
"password_reset_completed",
user_id=user.id,
username=user.username,
ip_address=request.remote_addr,
)
if user.email:
asyncio.create_task(send_password_reset_success_email(user.email))
return jsonify({"status": "ok"})
@auth_bp.route("/status", methods=["GET"])
async def status():
count = await get_user_count()
+70
View File
@@ -1,4 +1,7 @@
import hashlib
import logging
import secrets
from datetime import datetime, timedelta, timezone
import bcrypt
from sqlalchemy import func, select, update
@@ -6,6 +9,7 @@ from sqlalchemy import func, select, update
from fabledassistant.models import async_session
from fabledassistant.models.conversation import Conversation
from fabledassistant.models.note import Note
from fabledassistant.models.password_reset import PasswordResetToken
from fabledassistant.models.setting import Setting
from fabledassistant.models.user import User
@@ -150,3 +154,69 @@ async def delete_user(user_id: int) -> bool:
async def set_registration_open(admin_user_id: int, open: bool) -> None:
from fabledassistant.services.settings import set_setting
await set_setting(admin_user_id, "registration_open", "true" if open else "false")
async def get_user_by_email(email: str) -> User | None:
async with async_session() as session:
result = await session.execute(
select(User).where(func.lower(User.email) == email.lower())
)
return result.scalars().first()
async def create_password_reset_token(user_id: int) -> str:
"""Generate a password reset token. Returns the raw token (for the email link)."""
raw_token = secrets.token_urlsafe(32)
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
expires_at = datetime.now(timezone.utc) + timedelta(hours=1)
async with async_session() as session:
# Invalidate any existing unused tokens for this user
result = await session.execute(
select(PasswordResetToken).where(
PasswordResetToken.user_id == user_id,
PasswordResetToken.used.is_(False),
)
)
for old_token in result.scalars().all():
old_token.used = True
token = PasswordResetToken(
user_id=user_id,
token_hash=token_hash,
expires_at=expires_at,
)
session.add(token)
await session.commit()
logger.info("Password reset token created for user %d", user_id)
return raw_token
async def reset_password_with_token(raw_token: str, new_password: str) -> bool:
"""Validate a reset token and update the user's password. Returns True on success."""
token_hash = hashlib.sha256(raw_token.encode()).hexdigest()
async with async_session() as session:
result = await session.execute(
select(PasswordResetToken).where(PasswordResetToken.token_hash == token_hash)
)
reset_token = result.scalars().first()
if not reset_token:
return False
if reset_token.used:
return False
if reset_token.expires_at < datetime.now(timezone.utc):
return False
user = await session.get(User, reset_token.user_id)
if not user:
return False
user.password_hash = hash_password(new_password)
reset_token.used = True
await session.commit()
logger.info("Password reset via token for user %d (%s)", user.id, user.username)
return True
@@ -92,6 +92,52 @@ async def notify_security_event(
logger.exception("Failed to send security notification for user %d", user_id)
async def send_password_reset_email(email: str, reset_url: str) -> None:
"""Send a password reset email with a link to reset the user's password."""
html = f"""
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px;">
<div style="background: #6366f1; color: #fff; padding: 16px 24px; border-radius: 8px 8px 0 0; text-align: center;">
<h1 style="margin: 0; font-size: 20px;">Password Reset</h1>
</div>
<div style="background: #f9fafb; padding: 24px; border: 1px solid #e5e7eb; border-top: none; border-radius: 0 0 8px 8px;">
<p style="margin: 0 0 16px; color: #374151; font-size: 15px;">
We received a request to reset your password. Click the button below to choose a new password:
</p>
<div style="text-align: center; margin: 24px 0;">
<a href="{reset_url}" style="display: inline-block; background: #6366f1; color: #fff; padding: 12px 32px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 15px;">
Reset Password
</a>
</div>
<p style="margin: 0 0 8px; color: #6b7280; font-size: 13px;">This link expires in 1 hour.</p>
<p style="margin: 0; color: #6b7280; font-size: 13px;">If you didn't request this, you can safely ignore this email.</p>
<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 16px 0;" />
<p style="margin: 0; color: #9ca3af; font-size: 12px;">If the button doesn't work, copy and paste this link into your browser:</p>
<p style="margin: 4px 0 0; color: #9ca3af; font-size: 12px; word-break: break-all;">{reset_url}</p>
</div>
</div>
"""
await send_email(email, "Fabled Assistant - Password Reset", html)
async def send_password_reset_success_email(email: str) -> None:
"""Send a notification that the password was successfully reset."""
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
html = f"""
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 24px;">
<div style="background: #6366f1; color: #fff; padding: 16px 24px; border-radius: 8px 8px 0 0; text-align: center;">
<h1 style="margin: 0; font-size: 20px;">Password Changed</h1>
</div>
<div style="background: #f9fafb; padding: 24px; border: 1px solid #e5e7eb; border-top: none; border-radius: 0 0 8px 8px;">
<p style="margin: 0 0 16px; color: #374151; font-size: 15px;">
Your password was successfully reset at {timestamp}.
</p>
<p style="margin: 0; color: #6b7280; font-size: 13px;">If you didn't make this change, please contact your administrator immediately.</p>
</div>
</div>
"""
await send_email(email, "Fabled Assistant - Password Changed", html)
async def check_due_tasks() -> None:
"""Check for tasks due today and send reminder emails."""
if not await is_smtp_configured():