feat: add password reset email

This commit is contained in:
gosangam
2026-06-02 18:37:38 +05:30
parent dc01d09f09
commit cb70a84dd5
12 changed files with 662 additions and 88 deletions
+201
View File
@@ -0,0 +1,201 @@
"use client";
/**
* ChangePasswordModal — three-field "change my password" form rendered in
* a centred portal dialog. Mirrors the AuthModal pattern (backdrop +
* fixed-position card + Esc-to-close + body scroll-lock) so the look and
* feel matches.
*
* Opens from /settings → Authentication → Change password.
*
* On success: closes itself, refreshes the user state via auth-provider's
* setUser so the rest of the app sees the fresh JWT-backed user. The BFF
* has already re-issued the session cookie, so the caller stays signed in
* on this device.
*/
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { useAuth } from "@/components/auth/auth-provider";
import { auth, AuthError } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export function ChangePasswordModal({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
const { user, setUser } = useAuth();
// OAuth-only accounts have no existing password to verify against — the
// modal renders two fields (new + confirm) instead of three. Backend
// accepts current_password as optional in this case.
const requireCurrent = user?.has_password ?? true;
const [current, setCurrent] = useState("");
const [next, setNext] = useState("");
const [confirm, setConfirm] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
// Reset form whenever the modal closes — re-opening should start blank,
// not show the previous attempt.
useEffect(() => {
if (open) return;
setCurrent("");
setNext("");
setConfirm("");
setError(null);
setSubmitting(false);
}, [open]);
// Esc-to-close.
useEffect(() => {
if (!open) return;
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [open, onClose]);
// Body scroll-lock while the modal is open.
useEffect(() => {
if (!open) return;
const prev = document.body.style.overflow;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = prev;
};
}, [open]);
if (!open || typeof document === "undefined") return null;
async function onSubmit(e: React.SyntheticEvent) {
e.preventDefault();
setError(null);
if (next.length < 8) {
setError("New password must be at least 8 characters.");
return;
}
if (next !== confirm) {
setError("New passwords don't match.");
return;
}
setSubmitting(true);
try {
const updated = await auth.changePassword(current, next);
setUser(updated);
onClose();
} catch (err) {
setError(
err instanceof AuthError ? err.message : "Could not change password.",
);
} finally {
setSubmitting(false);
}
}
return createPortal(
<>
<div
className="fixed inset-0 z-100 bg-foreground/40 backdrop-blur-sm animate-in fade-in-0"
onClick={onClose}
aria-hidden
/>
<div
role="dialog"
aria-modal="true"
aria-labelledby="change-password-title"
className="fixed left-1/2 top-1/2 z-101 w-full max-w-md -translate-x-1/2 -translate-y-1/2 px-4"
>
<div className="rounded-2xl border border-border bg-card shadow-xl overflow-hidden">
<header className="flex items-center justify-between px-5 py-4 border-b border-border">
<h2
id="change-password-title"
className="font-[family-name:var(--font-title)] font-semibold text-xl text-foreground"
>
Change password
</h2>
<button
type="button"
onClick={onClose}
className="size-8 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center justify-center"
aria-label="Close"
>
<X className="size-4" />
</button>
</header>
<form onSubmit={onSubmit} className="px-5 py-5 space-y-4">
{requireCurrent ? (
<div className="space-y-1.5">
<Label htmlFor="cp-current">Current password</Label>
<Input
id="cp-current"
type="password"
autoComplete="current-password"
required
value={current}
onChange={(e) => setCurrent(e.target.value)}
/>
</div>
) : null}
<div className="space-y-1.5">
<Label htmlFor="cp-new">New password</Label>
<Input
id="cp-new"
type="password"
autoComplete="new-password"
minLength={8}
required
value={next}
onChange={(e) => setNext(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
At least 8 characters.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="cp-confirm">Confirm new password</Label>
<Input
id="cp-confirm"
type="password"
autoComplete="new-password"
required
value={confirm}
onChange={(e) => setConfirm(e.target.value)}
/>
</div>
{error ? (
<p className="text-sm text-destructive">{error}</p>
) : null}
<div className="flex items-center justify-end gap-2 pt-1">
<Button
type="button"
variant="ghost"
onClick={onClose}
className="h-10 px-4 text-sm"
>
Cancel
</Button>
<Button
type="submit"
disabled={submitting}
className="h-10 px-4 text-sm"
>
{submitting ? "Saving…" : "Save changes"}
</Button>
</div>
</form>
</div>
</div>
</>,
document.body,
);
}
+1 -1
View File
@@ -138,7 +138,7 @@ export function UserMenu() {
{user.name}
</p>
<p className="text-xs text-muted-foreground truncate">
{user.email}
{user.email ?? `@${user.handle}`}
</p>
</div>
<div className="h-px bg-border my-1" />
+73 -16
View File
@@ -5,27 +5,34 @@ import { auth, AuthError } from "@/lib/auth";
import { useAuth } from "./auth-provider";
/**
* Persistent top ribbon shown when a logged-in user has not yet verified
* their email. Lets them re-trigger the verification mail without leaving
* the page.
* Top ribbon for accounts whose email is either missing (OAuth sign-up
* without an address) or present-but-unverified.
*
* Two modes:
* • Missing email — an inline "Add your email" input that POSTs to
* /auth/email. On success the user state refreshes and the banner
* automatically flips into the "verify your email" mode.
* • Unverified email — existing "Resend verification" call to action.
*
* Renders nothing when:
* - auth state is still loading
* - user is logged out
* - user.email_verified_at is set
* - user dismissed it for this session (banner is meant to be persistent
* across navigations but skippable per-tab; we keep the dismissed flag
* in component state so a refresh brings it back)
* - user.email_verified_at is set (the address has been confirmed)
* - user dismissed it for this session (persistent across navigations
* but reset on full page refresh)
*/
export function VerifyEmailBanner() {
const { user, loading } = useAuth();
const { user, loading, setUser } = useAuth();
const [sent, setSent] = useState(false);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [dismissed, setDismissed] = useState(false);
const [newEmail, setNewEmail] = useState("");
if (loading || !user || user.email_verified_at || dismissed) return null;
const needsEmail = !user.email;
async function onResend() {
setError(null);
setBusy(true);
@@ -41,18 +48,68 @@ export function VerifyEmailBanner() {
}
}
async function onSetEmail(e: React.FormEvent) {
e.preventDefault();
setError(null);
setBusy(true);
try {
const updated = await auth.setEmail(newEmail);
setUser(updated);
setSent(true);
} catch (err) {
setError(err instanceof AuthError ? err.message : "Could not save email.");
} finally {
setBusy(false);
}
}
return (
<div className="w-full bg-amber-50 dark:bg-amber-950/40 text-amber-900 dark:text-amber-100 border-b border-amber-200/60 dark:border-amber-800/60">
<div className="max-w-5xl mx-auto px-4 py-2 flex flex-wrap items-center justify-between gap-3 text-sm">
<p>
{sent
? "✓ Verification email sent — check your inbox."
: error
? error
: `Verify your email (${user.email}) to secure your account.`}
</p>
{sent ? (
<p>
{needsEmail
? "✓ Email saved — check your inbox for a verification link."
: "✓ Verification email sent — check your inbox."}
</p>
) : needsEmail ? (
<form
onSubmit={onSetEmail}
className="flex flex-1 flex-wrap items-center gap-2"
>
<label htmlFor="banner-email" className="shrink-0">
Add an email to your account:
</label>
<input
id="banner-email"
type="email"
required
value={newEmail}
onChange={(e) => setNewEmail(e.target.value)}
placeholder="you@example.com"
className="flex-1 min-w-[12rem] rounded-md border border-amber-300/70 dark:border-amber-800/70 bg-white/70 dark:bg-amber-950/30 px-2 py-1 text-amber-900 dark:text-amber-50 placeholder:text-amber-700/50 dark:placeholder:text-amber-200/40"
/>
<button
type="submit"
disabled={busy || newEmail.trim() === ""}
className="font-medium underline-offset-2 hover:underline disabled:opacity-60"
>
{busy ? "Saving…" : "Save"}
</button>
{error ? (
<span className="text-amber-900/80 dark:text-amber-100/80">
{error}
</span>
) : null}
</form>
) : (
<p>
{error ?? `Verify your email (${user.email}) to secure your account.`}
</p>
)}
<div className="flex items-center gap-2">
{!sent ? (
{!sent && !needsEmail ? (
<button
type="button"
onClick={onResend}