feat: social auth account linking

This commit is contained in:
gosangam
2026-06-02 22:55:09 +05:30
parent 086f1dd8aa
commit ec67ddf852
6 changed files with 675 additions and 177 deletions
+161
View File
@@ -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&apos;ll send a verification link to confirm it&apos;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,
);
}
+40 -6
View File
@@ -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
View File
@@ -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>
);
+48 -78
View File
@@ -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)}
/>
</>
);
}