feat: social auth account linking
This commit is contained in:
+257
-46
@@ -14,9 +14,19 @@
|
||||
* `<main>` below.
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { Suspense, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import {
|
||||
AlertCircle,
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { auth, AuthError } from "@/lib/auth";
|
||||
import { useAuth } from "@/components/auth/auth-provider";
|
||||
import { AddEmailModal } from "@/components/auth/add-email-modal";
|
||||
import { ChangePasswordModal } from "@/components/auth/change-password-modal";
|
||||
import { ReadingSettings } from "@/components/reading-settings";
|
||||
|
||||
@@ -29,9 +39,9 @@ export default function SettingsPage() {
|
||||
<header className="space-y-1">
|
||||
<Link
|
||||
href="/u/me"
|
||||
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
className="inline-flex items-center gap-1 text-base text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
<ChevronLeft className="size-5" />
|
||||
Back to profile
|
||||
</Link>
|
||||
<h1 className="font-[family-name:var(--font-title)] text-3xl font-semibold text-foreground pt-2">
|
||||
@@ -47,16 +57,56 @@ export default function SettingsPage() {
|
||||
</Section>
|
||||
|
||||
<Section title="Authentication">
|
||||
{/* Suspense boundary required because LinkResult reads
|
||||
useSearchParams — Next.js bails out of SSR otherwise. */}
|
||||
<Suspense fallback={null}>
|
||||
<LinkResult />
|
||||
</Suspense>
|
||||
<AuthenticationSection />
|
||||
</Section>
|
||||
|
||||
<Section title="Legal">
|
||||
<LegalSection />
|
||||
</Section>
|
||||
|
||||
<SignOutSection />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function SignOutSection() {
|
||||
const { logOut } = useAuth();
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function onSignOut() {
|
||||
setBusy(true);
|
||||
try {
|
||||
await logOut();
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} catch {
|
||||
// Logout errors are silent — the cookie is cleared on the server
|
||||
// either way and the next protected request will redirect anyway.
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSignOut}
|
||||
disabled={busy}
|
||||
className="inline-flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-4 py-2.5 text-base font-medium text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-60"
|
||||
>
|
||||
<LogOut className="size-5" />
|
||||
{busy ? "Signing out…" : "Sign out"}
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
description,
|
||||
@@ -69,11 +119,11 @@ function Section({
|
||||
return (
|
||||
<section className="space-y-4">
|
||||
<div className="border-b border-border pb-3">
|
||||
<h2 className="font-[family-name:var(--font-title)] text-xl font-semibold text-foreground">
|
||||
<h2 className="font-[family-name:var(--font-title)] text-2xl font-semibold text-foreground">
|
||||
{title}
|
||||
</h2>
|
||||
{description ? (
|
||||
<p className="text-sm text-muted-foreground mt-1">{description}</p>
|
||||
<p className="text-base text-muted-foreground mt-1">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div>{children}</div>
|
||||
@@ -84,64 +134,226 @@ function Section({
|
||||
// ─── Authentication ────────────────────────────────────────────────────
|
||||
|
||||
function AuthenticationSection() {
|
||||
const { user } = useAuth();
|
||||
const [pwModalOpen, setPwModalOpen] = useState(false);
|
||||
const [emailModalOpen, setEmailModalOpen] = useState(false);
|
||||
const [linkedProviders, setLinkedProviders] = useState<Set<string> | null>(
|
||||
null,
|
||||
);
|
||||
const next = "/settings";
|
||||
|
||||
// Fetch linked providers on mount. A null set means "not yet loaded" — we
|
||||
// render the rows as if nothing is connected until the answer comes back,
|
||||
// which is fine because the only thing that changes after load is the
|
||||
// "Connected" pill swapping in for "Connect".
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
auth
|
||||
.linkedProviders()
|
||||
.then(({ providers }) => {
|
||||
if (!cancelled) setLinkedProviders(new Set(providers));
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setLinkedProviders(new Set());
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
function startOAuth(provider: "facebook" | "google") {
|
||||
const u = new URL(`${BFF_BASE}/api/v1/auth/oauth/${provider}/start`);
|
||||
// /link/start — links the provider to the currently-authenticated
|
||||
// user (auth cookie travels on the top-level navigation). The login
|
||||
// page still uses /start for sign-in / sign-up.
|
||||
const u = new URL(
|
||||
`${BFF_BASE}/api/v1/auth/oauth/${provider}/link/start`,
|
||||
);
|
||||
u.searchParams.set("next", next);
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
function providerAction(provider: "google" | "facebook") {
|
||||
if (linkedProviders?.has(provider)) {
|
||||
return <ConnectedPill />;
|
||||
}
|
||||
return (
|
||||
<a
|
||||
href={startOAuth(provider)}
|
||||
className="text-base font-medium text-primary hover:underline"
|
||||
>
|
||||
Connect
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
// Three contextual states for the email-related rows:
|
||||
// • user has no email → "Add your email" row only
|
||||
// • user has email, NOT verified → "Verify your email" row +
|
||||
// "Change your password" row
|
||||
// • user has email, verified → "Change your password" row
|
||||
const needsEmail = !user?.email;
|
||||
const needsVerify = !!user?.email && !user.email_verified_at;
|
||||
|
||||
return (
|
||||
<>
|
||||
<ul className="divide-y divide-border">
|
||||
<Row
|
||||
icon={<GoogleGlyph />}
|
||||
label="Connect your Google account"
|
||||
action={
|
||||
<a
|
||||
href={startOAuth("google")}
|
||||
className="text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
Connect
|
||||
</a>
|
||||
}
|
||||
action={providerAction("google")}
|
||||
/>
|
||||
<Row
|
||||
icon={<FacebookGlyph />}
|
||||
label="Connect your Facebook account"
|
||||
action={
|
||||
<a
|
||||
href={startOAuth("facebook")}
|
||||
className="text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
Connect
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
<Row
|
||||
label="Change your password"
|
||||
description="Update the password you use to sign in."
|
||||
action={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPwModalOpen(true)}
|
||||
className="text-sm font-medium text-primary hover:underline"
|
||||
>
|
||||
Change
|
||||
</button>
|
||||
}
|
||||
action={providerAction("facebook")}
|
||||
/>
|
||||
{needsEmail ? (
|
||||
<Row
|
||||
label="Add your email"
|
||||
description="Required for password recovery. We'll send a verification link."
|
||||
action={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEmailModalOpen(true)}
|
||||
className="text-base font-medium text-primary hover:underline"
|
||||
>
|
||||
Add email
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{needsVerify ? <VerifyEmailRow email={user!.email!} /> : null}
|
||||
<Row
|
||||
label="Change your password"
|
||||
description="Update the password you use to sign in."
|
||||
action={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPwModalOpen(true)}
|
||||
className="text-base font-medium text-primary hover:underline"
|
||||
>
|
||||
Change
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</ul>
|
||||
<ChangePasswordModal
|
||||
open={pwModalOpen}
|
||||
onClose={() => setPwModalOpen(false)}
|
||||
/>
|
||||
<AddEmailModal
|
||||
open={emailModalOpen}
|
||||
onClose={() => setEmailModalOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function VerifyEmailRow({ email }: { email: string }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function onResend() {
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await auth.resendVerification();
|
||||
setSent(true);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof AuthError
|
||||
? err.message
|
||||
: "Could not send verification email.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Row
|
||||
label="Verify your email"
|
||||
description={
|
||||
sent
|
||||
? `✓ Verification email sent to ${email}.`
|
||||
: error ?? `We need to confirm ${email} before it can be used for recovery.`
|
||||
}
|
||||
action={
|
||||
sent ? (
|
||||
<span className="text-base text-muted-foreground">Sent</span>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={busy}
|
||||
className="text-base font-medium text-primary hover:underline disabled:opacity-60"
|
||||
>
|
||||
{busy ? "Sending…" : "Resend"}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function LinkResult() {
|
||||
const params = useSearchParams();
|
||||
const router = useRouter();
|
||||
const raw = params.get("link");
|
||||
|
||||
// Strip the param from the URL so a refresh doesn't re-show the banner.
|
||||
useEffect(() => {
|
||||
if (!raw) return;
|
||||
const next = new URLSearchParams(params.toString());
|
||||
next.delete("link");
|
||||
const q = next.toString();
|
||||
router.replace(q ? `/settings?${q}` : "/settings");
|
||||
}, [raw, params, router]);
|
||||
|
||||
if (!raw) return null;
|
||||
|
||||
// Format: "<provider>:<status>" — `google:ok`, `facebook:claimed`, etc.
|
||||
const [provider, status] = raw.split(":", 2);
|
||||
const name = provider.charAt(0).toUpperCase() + provider.slice(1);
|
||||
|
||||
if (status === "ok") {
|
||||
return (
|
||||
<p className="mb-4 inline-flex items-center gap-2 rounded-md bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 px-3 py-2 text-base">
|
||||
<Check className="size-4" />
|
||||
Connected your {name} account.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (status === "claimed") {
|
||||
return (
|
||||
<p className="mb-4 inline-flex items-center gap-2 rounded-md bg-destructive/10 text-destructive px-3 py-2 text-base">
|
||||
<AlertCircle className="size-4" />
|
||||
That {name} account is already linked to another Prabhupāda Says
|
||||
account.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<p className="mb-4 inline-flex items-center gap-2 rounded-md bg-destructive/10 text-destructive px-3 py-2 text-base">
|
||||
<AlertCircle className="size-4" />
|
||||
Couldn't connect your {name} account. Please try again.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function ConnectedPill() {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 px-2.5 py-0.5 text-sm font-medium">
|
||||
<Check className="size-3.5" />
|
||||
Connected
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Legal ─────────────────────────────────────────────────────────────
|
||||
|
||||
function LegalSection() {
|
||||
@@ -159,12 +371,12 @@ function LegalLink({ href, label }: { href: string; label: string }) {
|
||||
<li>
|
||||
<Link
|
||||
href={href}
|
||||
className="flex items-center justify-between py-3 group"
|
||||
className="flex items-center justify-between py-3.5 group"
|
||||
>
|
||||
<span className="text-sm text-foreground group-hover:text-primary transition-colors">
|
||||
<span className="text-base text-foreground group-hover:text-primary transition-colors">
|
||||
{label}
|
||||
</span>
|
||||
<ChevronRight className="size-4 text-muted-foreground group-hover:text-foreground transition-colors" />
|
||||
<ChevronRight className="size-5 text-muted-foreground group-hover:text-foreground transition-colors" />
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
@@ -175,7 +387,7 @@ function LegalLink({ href, label }: { href: string; label: string }) {
|
||||
function GoogleGlyph() {
|
||||
return (
|
||||
<svg
|
||||
className="size-4"
|
||||
className="size-5"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden
|
||||
@@ -203,7 +415,7 @@ function GoogleGlyph() {
|
||||
function FacebookGlyph() {
|
||||
return (
|
||||
<svg
|
||||
className="size-4"
|
||||
className="size-5"
|
||||
viewBox="0 0 24 24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden
|
||||
@@ -228,18 +440,17 @@ function Row({
|
||||
action: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<li className="flex items-center justify-between gap-4 py-3">
|
||||
<li className="flex items-center justify-between gap-4 py-3.5">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-2.5">
|
||||
{icon ? <span className="shrink-0">{icon}</span> : null}
|
||||
<span className="text-sm text-foreground truncate">{label}</span>
|
||||
<span className="text-base text-foreground truncate">{label}</span>
|
||||
</div>
|
||||
{description ? (
|
||||
<p className="text-xs text-muted-foreground mt-0.5">{description}</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="shrink-0">{action}</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* AddEmailModal — centred portal dialog with a single email input for
|
||||
* users who signed up via OAuth and never shared an address. Mirrors
|
||||
* the ChangePasswordModal pattern so the look and feel matches.
|
||||
*
|
||||
* On success: closes itself and updates the auth-provider's user so the
|
||||
* rest of the app immediately sees the new email. The BFF stores the
|
||||
* address as unverified and fires a verification link to it; the user
|
||||
* sees that as the existing "verify your email" banner on the next
|
||||
* render.
|
||||
*
|
||||
* Entry points:
|
||||
* • VerifyEmailBanner — top-of-page "Add an email" button
|
||||
* • /settings → Authentication → Add your email row
|
||||
*/
|
||||
|
||||
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 AddEmailModal({
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { setUser } = useAuth();
|
||||
const [email, setEmail] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
// Blank slate every time the modal opens.
|
||||
useEffect(() => {
|
||||
if (open) return;
|
||||
setEmail("");
|
||||
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 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);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const updated = await auth.setEmail(email);
|
||||
setUser(updated);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError ? err.message : "Could not save email.");
|
||||
} 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="add-email-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="add-email-title"
|
||||
className="font-[family-name:var(--font-title)] font-semibold text-xl text-foreground"
|
||||
>
|
||||
Add your email
|
||||
</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">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Add an email to enable password recovery and notifications.
|
||||
We'll send a verification link to confirm it's yours.
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ae-email">Email address</Label>
|
||||
<Input
|
||||
id="ae-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
/>
|
||||
</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 || email.trim() === ""}
|
||||
className="h-10 px-4 text-sm"
|
||||
>
|
||||
{submitting ? "Saving…" : "Save email"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -21,11 +21,22 @@ import { auth, type User } from "@/lib/auth";
|
||||
* After a successful login/signup/logout the provider re-fetches /auth/me
|
||||
* to keep state in sync with the cookie.
|
||||
*/
|
||||
/**
|
||||
* LogInResult is either a completed session (regular case) or a signal
|
||||
* that the BFF wants a one-time code before completing the login. Callers
|
||||
* should branch on `kind` and, for `otp_required`, present an OTP field
|
||||
* and call `verifyLoginOTP`.
|
||||
*/
|
||||
export type LogInResult =
|
||||
| { kind: "session"; user: User }
|
||||
| { kind: "otp_required" };
|
||||
|
||||
type AuthContextValue = {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
signUp: (email: string, password: string, name: string) => Promise<User>;
|
||||
logIn: (email: string, password: string) => Promise<User>;
|
||||
logIn: (email: string, password: string) => Promise<LogInResult>;
|
||||
verifyLoginOTP: (email: string, password: string, otp: string) => Promise<User>;
|
||||
logOut: () => Promise<void>;
|
||||
refresh: () => Promise<void>;
|
||||
/** Replace the user state without a network round-trip (after profile edit). */
|
||||
@@ -58,19 +69,42 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
}, []);
|
||||
|
||||
const logIn = useCallback(async (email: string, password: string) => {
|
||||
const u = await auth.logIn(email, password);
|
||||
setUser(u);
|
||||
return u;
|
||||
const res = await auth.logIn(email, password);
|
||||
if (res.kind === "session") {
|
||||
setUser(res.user);
|
||||
}
|
||||
// For `otp_required` we deliberately leave `user` null so the rest of
|
||||
// the app keeps showing the signed-out state until VerifyLoginOTP
|
||||
// completes.
|
||||
return res;
|
||||
}, []);
|
||||
|
||||
const verifyLoginOTP = useCallback(
|
||||
async (email: string, password: string, otp: string) => {
|
||||
const u = await auth.verifyLoginOTP(email, password, otp);
|
||||
setUser(u);
|
||||
return u;
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const logOut = useCallback(async () => {
|
||||
await auth.logOut();
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({ user, loading, signUp, logIn, logOut, refresh, setUser }),
|
||||
[user, loading, signUp, logIn, logOut, refresh],
|
||||
() => ({
|
||||
user,
|
||||
loading,
|
||||
signUp,
|
||||
logIn,
|
||||
verifyLoginOTP,
|
||||
logOut,
|
||||
refresh,
|
||||
setUser,
|
||||
}),
|
||||
[user, loading, signUp, logIn, verifyLoginOTP, logOut, refresh],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
|
||||
+125
-44
@@ -5,12 +5,16 @@
|
||||
* the AuthGate modal that pops up when an unauthenticated user tries to use
|
||||
* a protected feature.
|
||||
*
|
||||
* `onSuccess` is invoked once login completes. Callers decide what happens
|
||||
* next (a page redirect, a modal close, etc.). The form itself doesn't
|
||||
* navigate — that keeps it environment-agnostic.
|
||||
* Two stages:
|
||||
* 1. Password — email + password. If the BFF signals `otp_required`
|
||||
* (account unverified for >30 days), the form advances to stage 2.
|
||||
* 2. OTP — 6-digit code emailed to the user. Submitting verifies the
|
||||
* code, marks the email verified, and completes the session.
|
||||
*
|
||||
* `forgotPasswordHref` is configurable so the modal can override (it may
|
||||
* want to dismiss itself or open a different mode).
|
||||
* `onSuccess` fires after the session is finalised (either at stage 1 for
|
||||
* verified accounts or stage 2 for the OTP-gated path). Callers decide
|
||||
* what happens next (page redirect, modal close, etc.) — the form itself
|
||||
* doesn't navigate.
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
@@ -34,18 +38,26 @@ export function LoginForm({
|
||||
/** Post-OAuth redirect path on the frontend. */
|
||||
oauthNext?: string;
|
||||
}) {
|
||||
const { logIn } = useAuth();
|
||||
const { logIn, verifyLoginOTP } = useAuth();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [otp, setOTP] = useState("");
|
||||
// Two-stage state machine. "password" is the default; we advance to
|
||||
// "otp" only after the BFF signals otp_required.
|
||||
const [stage, setStage] = useState<"password" | "otp">("password");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
async function onSubmit(e: React.SyntheticEvent) {
|
||||
async function onPasswordSubmit(e: React.SyntheticEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await logIn(email, password);
|
||||
const res = await logIn(email, password);
|
||||
if (res.kind === "otp_required") {
|
||||
setStage("otp");
|
||||
return;
|
||||
}
|
||||
onSuccess?.();
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError ? err.message : "Login failed.");
|
||||
@@ -54,46 +66,115 @@ export function LoginForm({
|
||||
}
|
||||
}
|
||||
|
||||
async function onOTPSubmit(e: React.SyntheticEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await verifyLoginOTP(email, password, otp);
|
||||
onSuccess?.();
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof AuthError ? err.message : "Could not verify the code.",
|
||||
);
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (stage === "otp") {
|
||||
return (
|
||||
<form onSubmit={onOTPSubmit} className="space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="login-otp">Enter the 6-digit code</Label>
|
||||
<Input
|
||||
id="login-otp"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]{6}"
|
||||
maxLength={6}
|
||||
required
|
||||
value={otp}
|
||||
onChange={(e) =>
|
||||
setOTP(e.target.value.replace(/\D/g, "").slice(0, 6))
|
||||
}
|
||||
placeholder="123456"
|
||||
className="tracking-[0.4em] text-center text-lg"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
We sent a code to <span className="font-medium">{email}</span>.
|
||||
Your account has been unverified for a while, so we need this
|
||||
extra step. The code expires in 10 minutes.
|
||||
</p>
|
||||
</div>
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={submitting || otp.length !== 6}
|
||||
className="w-full h-11 text-base"
|
||||
>
|
||||
{submitting ? "Verifying…" : "Verify and log in"}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setStage("password");
|
||||
setOTP("");
|
||||
setError(null);
|
||||
}}
|
||||
className="block mx-auto text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
← Use a different email
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<OAuthButtons next={oauthNext} />
|
||||
<form onSubmit={onSubmit} className="space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="login-email">Email</Label>
|
||||
<Input
|
||||
id="login-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="login-password">Password</Label>
|
||||
{showForgotLink ? (
|
||||
<Link
|
||||
href={forgotPasswordHref}
|
||||
className="text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Forgot?
|
||||
</Link>
|
||||
) : null}
|
||||
<form onSubmit={onPasswordSubmit} className="space-y-5">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="login-email">Email</Label>
|
||||
<Input
|
||||
id="login-email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
id="login-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
<Button type="submit" disabled={submitting} className="w-full h-11 text-base">
|
||||
{submitting ? "Logging in…" : "Log in"}
|
||||
</Button>
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="login-password">Password</Label>
|
||||
{showForgotLink ? (
|
||||
<Link
|
||||
href={forgotPasswordHref}
|
||||
className="text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Forgot?
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
<Input
|
||||
id="login-password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{error ? <p className="text-sm text-destructive">{error}</p> : null}
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={submitting}
|
||||
className="w-full h-11 text-base"
|
||||
>
|
||||
{submitting ? "Logging in…" : "Log in"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState } from "react";
|
||||
import { auth, AuthError } from "@/lib/auth";
|
||||
import { AddEmailModal } from "./add-email-modal";
|
||||
import { useAuth } from "./auth-provider";
|
||||
|
||||
/**
|
||||
@@ -9,10 +10,11 @@ import { useAuth } from "./auth-provider";
|
||||
* 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.
|
||||
* • Missing email — "Add an email" button that opens AddEmailModal.
|
||||
* The modal POSTs to /auth/email and refreshes the user; on success
|
||||
* this banner flips into the verify-your-email mode automatically.
|
||||
* • Unverified email — "Resend verification" button calls
|
||||
* auth.resendVerification().
|
||||
*
|
||||
* Renders nothing when:
|
||||
* - auth state is still loading
|
||||
@@ -22,12 +24,12 @@ import { useAuth } from "./auth-provider";
|
||||
* but reset on full page refresh)
|
||||
*/
|
||||
export function VerifyEmailBanner() {
|
||||
const { user, loading, setUser } = useAuth();
|
||||
const { user, loading } = 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("");
|
||||
const [emailModalOpen, setEmailModalOpen] = useState(false);
|
||||
|
||||
if (loading || !user || user.email_verified_at || dismissed) return null;
|
||||
|
||||
@@ -48,87 +50,55 @@ 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">
|
||||
{sent ? (
|
||||
<>
|
||||
<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>
|
||||
{needsEmail
|
||||
? "✓ Email saved — check your inbox for a verification link."
|
||||
: "✓ Verification email sent — check your inbox."}
|
||||
{sent
|
||||
? "✓ Verification email sent — check your inbox."
|
||||
: error
|
||||
? error
|
||||
: needsEmail
|
||||
? "Add an email to enable password recovery and notifications."
|
||||
: `Verify your email (${user.email}) to secure your account.`}
|
||||
</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>
|
||||
<div className="flex items-center gap-2">
|
||||
{!sent ? (
|
||||
needsEmail ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEmailModalOpen(true)}
|
||||
className="font-medium underline-offset-2 hover:underline"
|
||||
>
|
||||
Add email
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={busy}
|
||||
className="font-medium underline-offset-2 hover:underline disabled:opacity-60"
|
||||
>
|
||||
{busy ? "Sending…" : "Resend email"}
|
||||
</button>
|
||||
)
|
||||
) : null}
|
||||
</form>
|
||||
) : (
|
||||
<p>
|
||||
{error ?? `Verify your email (${user.email}) to secure your account.`}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{!sent && !needsEmail ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={busy}
|
||||
className="font-medium underline-offset-2 hover:underline disabled:opacity-60"
|
||||
onClick={() => setDismissed(true)}
|
||||
aria-label="Dismiss"
|
||||
className="opacity-70 hover:opacity-100"
|
||||
>
|
||||
{busy ? "Sending…" : "Resend email"}
|
||||
✕
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDismissed(true)}
|
||||
aria-label="Dismiss"
|
||||
className="opacity-70 hover:opacity-100"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AddEmailModal
|
||||
open={emailModalOpen}
|
||||
onClose={() => setEmailModalOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
+44
-3
@@ -83,10 +83,43 @@ export const auth = {
|
||||
body: JSON.stringify({ email, password, name }),
|
||||
}),
|
||||
|
||||
logIn: (email: string, password: string) =>
|
||||
authFetch<User>("/auth/login", {
|
||||
/**
|
||||
* Submits email/password. Three outcomes:
|
||||
* - kind: "session" → fully signed in; auth-provider sets the user.
|
||||
* - kind: "otp_required" → account has been unverified for >30 days;
|
||||
* a 6-digit code was emailed. Caller must show an OTP form and call
|
||||
* `verifyLoginOTP(email, password, otp)` to complete sign-in.
|
||||
* Throws AuthError on credential / server errors.
|
||||
*/
|
||||
logIn: async (
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<
|
||||
| { kind: "session"; user: User }
|
||||
| { kind: "otp_required" }
|
||||
> => {
|
||||
const data = await authFetch<User | { otp_required: true }>(
|
||||
"/auth/login",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
},
|
||||
);
|
||||
if (data && typeof data === "object" && "otp_required" in data) {
|
||||
return { kind: "otp_required" };
|
||||
}
|
||||
return { kind: "session", user: data as User };
|
||||
},
|
||||
|
||||
/**
|
||||
* Completes a login that was paused by the OTP gate. Re-checks the
|
||||
* password (the OTP alone isn't enough — defence in depth), validates
|
||||
* the code, marks the email verified, and sets the session cookie.
|
||||
*/
|
||||
verifyLoginOTP: (email: string, password: string, otp: string) =>
|
||||
authFetch<User>("/auth/verify-login-otp", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify({ email, password, otp }),
|
||||
}),
|
||||
|
||||
logOut: () => authFetch<{ ok: boolean }>("/auth/logout", { method: "POST" }),
|
||||
@@ -133,6 +166,14 @@ export const auth = {
|
||||
body: JSON.stringify({ email }),
|
||||
}),
|
||||
|
||||
/**
|
||||
* Returns the list of OAuth provider names already linked to the
|
||||
* signed-in user (e.g. `["google", "facebook"]`). The settings page
|
||||
* uses this to flip per-provider rows between "Connect" / "Connected".
|
||||
*/
|
||||
linkedProviders: () =>
|
||||
authFetch<{ providers: string[] }>("/auth/linked-providers"),
|
||||
|
||||
/**
|
||||
* Replaces the signed-in user's password. The BFF verifies the current
|
||||
* password, hashes the new one, and re-issues the session cookie so this
|
||||
|
||||
Reference in New Issue
Block a user