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}
+70 -4
View File
@@ -171,10 +171,16 @@ export function ProfileEditForm({
<div className="space-y-1.5">
<Label htmlFor="profile-email">Email</Label>
<Input id="profile-email" value={user.email} disabled />
<p className="text-xs text-muted-foreground">
Email changes aren&apos;t supported yet.
</p>
{user.email ? (
<>
<Input id="profile-email" value={user.email} disabled />
<p className="text-xs text-muted-foreground">
Email changes aren&apos;t supported yet.
</p>
</>
) : (
<AddEmailInline />
)}
</div>
</div>
@@ -202,6 +208,66 @@ export function ProfileEditForm({
);
}
function AddEmailInline() {
const { setUser } = useAuth();
const [email, setEmail] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState(false);
async function onSave(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSaving(true);
try {
const updated = await auth.setEmail(email);
setUser(updated);
setSent(true);
} catch (err) {
setError(err instanceof AuthError ? err.message : "Could not save email.");
} finally {
setSaving(false);
}
}
if (sent) {
return (
<p className="text-xs text-muted-foreground">
✓ Email saved — check your inbox for a verification link.
</p>
);
}
return (
<form onSubmit={onSave} className="space-y-1.5">
<div className="flex gap-2">
<Input
id="profile-email"
type="email"
required
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
/>
<Button
type="submit"
disabled={saving || email.trim() === ""}
className="h-10 px-3 text-sm"
>
{saving ? "Saving…" : "Save"}
</Button>
</div>
{error ? (
<p className="text-xs text-destructive">{error}</p>
) : (
<p className="text-xs text-muted-foreground">
Add an email to enable password recovery and notifications.
</p>
)}
</form>
);
}
function AvatarPreview({ src, name }: { src: string | null; name: string }) {
if (src) {
return (
+5 -5
View File
@@ -12,8 +12,8 @@
* "is this my profile?" signal (the /u/me layout passes it; the
* /u/[handle] layout does not), so the two buttons stay in lockstep
* and visitors on someone else's profile see a clean row with no
* personal-settings affordances. The gear links to /u/me/settings
* (the inline reading-prefs page) rather than opening a popover —
* personal-settings affordances. The gear links to /settings (the
* dedicated settings page) rather than opening a popover —
* centred-row popovers tend to spill off the left edge on narrow
* viewports.
*
@@ -84,9 +84,9 @@ export function ProfileHeader({
) : null}
{showReadingSettings ? (
<Link
href="/u/me/settings"
aria-label="Reading settings"
title="Reading settings"
href="/settings"
aria-label="Settings"
title="Settings"
className={cn(
"size-9 inline-flex items-center justify-center rounded-lg",
"border border-border text-foreground hover:bg-muted",
+19 -7
View File
@@ -242,8 +242,12 @@ type Placement = "below-right" | "above-left";
* can push the panel off-screen, which is why auth users get the
* dedicated settings page instead.
* - "inline" — render the controls flat as part of normal page flow,
* full-width up to a sensible cap. Used by /u/me/settings. */
type Variant = "popover" | "inline";
* full-width up to a sensible cap, wrapped in a subtle card.
* - "bare" — like "inline" but with no card chrome at all. The controls
* blend into the surrounding page as a normal section. Used by the
* top-level /settings screen where reading prefs are just one of
* several stacked sections. */
type Variant = "popover" | "inline" | "bare";
export function ReadingSettings({
variant = "popover",
@@ -468,9 +472,9 @@ export function ReadingSettings({
visiblePalettes.find((p) => p.id === activePaletteId)?.name ?? "";
if (!mounted) {
// Inline variant: render nothing until mounted so we don't flash a
// misaligned skeleton on the dedicated settings page.
if (variant === "inline") return null;
// Inline / bare variants: render nothing until mounted so we don't
// flash a misaligned skeleton on the dedicated settings page.
if (variant === "inline" || variant === "bare") return null;
return (
<Button variant="ghost" size="icon-sm" aria-label="Reading settings">
<Settings className="size-4" />
@@ -611,8 +615,7 @@ export function ReadingSettings({
// ── Inline variant ──────────────────────────────────────────────────
// Renders the same controls as a flush, full-width card. No popover
// positioning, so it can't drift off-viewport on a narrow screen. Used
// by /u/me/settings.
// positioning, so it can't drift off-viewport on a narrow screen.
if (variant === "inline") {
return (
<div className="w-full max-w-xl rounded-lg border border-border bg-card p-4 sm:p-5">
@@ -621,6 +624,15 @@ export function ReadingSettings({
);
}
// ── Bare variant ────────────────────────────────────────────────────
// No card, no border — controls render flush with the surrounding page
// so the section reads as part of the main flow rather than a callout.
// Used by /settings, where reading prefs sit alongside several other
// unstyled sections.
if (variant === "bare") {
return <div className="w-full">{panelInner}</div>;
}
// ── Popover variant (default) ───────────────────────────────────────
const toggle = () => setOpen((v) => !v);