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
+257 -46
View File
@@ -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&apos;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>
);
}