feat(auth): add Supabase auth with Google, GitHub, and email OTP login

Introduce user registration/login gated behind optional NEXT_PUBLIC_SUPABASE_*
env vars (leave blank to disable — app behaves exactly as before). Adds
proxy.ts for automatic cookie session refresh, requireUser() API route
guards on all 7 compute-consuming routes, AuthModal (Google/GitHub OAuth +
6-digit email OTP), UserChip header component, and login_success analytics
event. Identity is fully decoupled from Session/engine — no type changes.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
yuanzonghao
2026-06-13 17:33:55 +08:00
parent 2a2d58a64f
commit 87a2f93edb
22 changed files with 646 additions and 11 deletions
+240
View File
@@ -0,0 +1,240 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { track } from "@/lib/analytics";
type AuthStep = "pick" | "email-input" | "otp-verify";
export function AuthModal({
onClose,
onSuccess,
}: {
onClose: () => void;
onSuccess: () => void;
}) {
const [step, setStep] = useState<AuthStep>("pick");
const [email, setEmail] = useState("");
const [otp, setOtp] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [onClose]);
const handleOAuth = useCallback(
async (provider: "google" | "github") => {
setLoading(true);
setError("");
const supabase = createClient();
const { error: oauthError } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(window.location.pathname + window.location.search)}`,
},
});
if (oauthError) {
setError(oauthError.message);
setLoading(false);
}
},
[],
);
const handleSendOtp = useCallback(async () => {
const trimmed = email.trim();
if (!trimmed) return;
setLoading(true);
setError("");
const supabase = createClient();
const { error: otpError } = await supabase.auth.signInWithOtp({
email: trimmed,
});
setLoading(false);
if (otpError) {
setError(otpError.message);
} else {
setStep("otp-verify");
}
}, [email]);
const handleVerifyOtp = useCallback(async () => {
const trimmedOtp = otp.trim();
if (!trimmedOtp) return;
setLoading(true);
setError("");
const supabase = createClient();
const { error: verifyError } = await supabase.auth.verifyOtp({
email: email.trim(),
token: trimmedOtp,
type: "email",
});
setLoading(false);
if (verifyError) {
setError(verifyError.message);
} else {
track("login_success", { provider: "email" });
onSuccess();
}
}, [email, otp, onSuccess]);
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center px-4"
style={{ background: "rgba(0,0,0,0.55)" }}
onClick={onClose}
>
<div
className="w-full max-w-sm overflow-hidden"
onClick={(e) => e.stopPropagation()}
style={{
background: "rgba(14, 10, 6, 0.92)",
border: "1.5px solid rgba(175, 138, 72, 0.72)",
borderRadius: "8px",
backdropFilter: "blur(14px)",
WebkitBackdropFilter: "blur(14px)",
boxShadow:
"0 10px 42px rgba(0,0,0,0.62), inset 0 1px 0 rgba(200,165,90,0.12)",
}}
role="dialog"
aria-modal="true"
aria-label="登录"
>
{/* header */}
<div className="flex items-center justify-between border-b border-cream-50/10 px-5 py-3.5">
<div className="flex items-center gap-2 text-[11px] smallcaps text-cream-50/70">
<i className="fa-solid fa-right-to-bracket text-[11px]" />
{step === "pick" && "登录以继续"}
{step === "email-input" && "邮箱登录"}
{step === "otp-verify" && "验证码"}
</div>
<button
type="button"
onClick={onClose}
className="flex h-7 w-7 items-center justify-center text-cream-50/60 transition-colors hover:text-cream-50"
aria-label="关闭"
>
<i className="fa-solid fa-xmark text-[12px]" />
</button>
</div>
<div className="px-5 py-5 space-y-3">
{error && (
<p className="text-[12px] text-red-400/90 leading-snug">{error}</p>
)}
{step === "pick" && (
<>
<button
type="button"
disabled={loading}
onClick={() => handleOAuth("google")}
className="flex w-full items-center justify-center gap-2.5 rounded-md border border-cream-50/15 bg-cream-50/[0.06] px-4 py-2.5 text-[13px] text-cream-50/90 transition-colors hover:bg-cream-50/[0.12] disabled:opacity-50"
>
<i className="fa-brands fa-google text-[14px]" />
Google
</button>
<button
type="button"
disabled={loading}
onClick={() => handleOAuth("github")}
className="flex w-full items-center justify-center gap-2.5 rounded-md border border-cream-50/15 bg-cream-50/[0.06] px-4 py-2.5 text-[13px] text-cream-50/90 transition-colors hover:bg-cream-50/[0.12] disabled:opacity-50"
>
<i className="fa-brands fa-github text-[14px]" />
GitHub
</button>
<div className="flex items-center gap-3 py-1">
<div className="h-px flex-1 bg-cream-50/10" />
<span className="text-[10px] text-cream-50/40"></span>
<div className="h-px flex-1 bg-cream-50/10" />
</div>
<button
type="button"
onClick={() => setStep("email-input")}
className="flex w-full items-center justify-center gap-2.5 rounded-md border border-cream-50/15 bg-cream-50/[0.06] px-4 py-2.5 text-[13px] text-cream-50/90 transition-colors hover:bg-cream-50/[0.12]"
>
<i className="fa-solid fa-envelope text-[13px]" />
</button>
</>
)}
{step === "email-input" && (
<>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleSendOtp()}
placeholder="your@email.com"
autoFocus
className="w-full rounded-md border border-cream-50/15 bg-cream-50/[0.06] px-3.5 py-2.5 text-[13px] text-cream-50/90 placeholder:text-cream-50/30 outline-none focus:border-[rgba(175,138,72,0.6)]"
/>
<button
type="button"
disabled={loading || !email.trim()}
onClick={handleSendOtp}
className="w-full rounded-md bg-[rgba(175,138,72,0.85)] px-4 py-2.5 text-[13px] font-medium text-cream-50 transition-colors hover:bg-[rgba(175,138,72,1)] disabled:opacity-50"
>
{loading ? "发送中..." : "发送验证码"}
</button>
<button
type="button"
onClick={() => {
setStep("pick");
setError("");
}}
className="w-full text-center text-[12px] text-cream-50/50 transition-colors hover:text-cream-50/80"
>
</button>
</>
)}
{step === "otp-verify" && (
<>
<p className="text-[12px] text-cream-50/60 leading-snug">
<span className="text-cream-50/90">{email.trim()}</span>
</p>
<input
type="text"
inputMode="numeric"
maxLength={6}
value={otp}
onChange={(e) => setOtp(e.target.value.replace(/\D/g, ""))}
onKeyDown={(e) => e.key === "Enter" && handleVerifyOtp()}
placeholder="6 位验证码"
autoFocus
className="w-full rounded-md border border-cream-50/15 bg-cream-50/[0.06] px-3.5 py-2.5 text-center text-[16px] tracking-[0.35em] text-cream-50/90 placeholder:text-cream-50/30 placeholder:tracking-normal outline-none focus:border-[rgba(175,138,72,0.6)]"
/>
<button
type="button"
disabled={loading || otp.length < 6}
onClick={handleVerifyOtp}
className="w-full rounded-md bg-[rgba(175,138,72,0.85)] px-4 py-2.5 text-[13px] font-medium text-cream-50 transition-colors hover:bg-[rgba(175,138,72,1)] disabled:opacity-50"
>
{loading ? "验证中..." : "确认"}
</button>
<button
type="button"
onClick={() => {
setStep("email-input");
setOtp("");
setError("");
}}
className="w-full text-center text-[12px] text-cream-50/50 transition-colors hover:text-cream-50/80"
>
</button>
</>
)}
</div>
</div>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { AUTH_ENABLED } from "@/lib/supabase/config";
import { createClient } from "@/lib/supabase/client";
import type { AuthChangeEvent, Session, User } from "@supabase/supabase-js";
export function UserChip({
onLoginClick,
}: {
onLoginClick: () => void;
}) {
const [user, setUser] = useState<User | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
useEffect(() => {
if (!AUTH_ENABLED) return;
const supabase = createClient();
supabase.auth.getUser().then(({ data }: { data: { user: User | null } }) => setUser(data.user));
const {
data: { subscription },
} = supabase.auth.onAuthStateChange((_event: AuthChangeEvent, session: Session | null) => {
setUser(session?.user ?? null);
});
return () => subscription.unsubscribe();
}, []);
const handleLogout = useCallback(async () => {
const supabase = createClient();
await supabase.auth.signOut();
setUser(null);
setMenuOpen(false);
}, []);
if (!AUTH_ENABLED) return null;
if (!user) {
return (
<button
type="button"
onClick={onLoginClick}
className="flex items-center gap-1.5 rounded-full border border-cream-50/15 bg-cream-50/[0.06] px-3 py-1.5 text-[11px] text-cream-50/70 transition-colors hover:bg-cream-50/[0.12] hover:text-cream-50/90"
>
<i className="fa-solid fa-right-to-bracket text-[10px]" />
</button>
);
}
const label =
user.user_metadata?.full_name ??
user.email?.split("@")[0] ??
"User";
const avatarUrl = user.user_metadata?.avatar_url as string | undefined;
const initial = label.charAt(0).toUpperCase();
return (
<div className="relative">
<button
type="button"
onClick={() => setMenuOpen((v) => !v)}
className="flex items-center gap-2 rounded-full border border-cream-50/15 bg-cream-50/[0.06] pl-1.5 pr-3 py-1 text-[11px] text-cream-50/80 transition-colors hover:bg-cream-50/[0.12]"
>
{avatarUrl ? (
<img
src={avatarUrl}
alt=""
className="h-5 w-5 rounded-full object-cover"
referrerPolicy="no-referrer"
/>
) : (
<span className="flex h-5 w-5 items-center justify-center rounded-full bg-[rgba(175,138,72,0.6)] text-[10px] font-medium text-cream-50">
{initial}
</span>
)}
<span className="max-w-[100px] truncate">{label}</span>
</button>
{menuOpen && (
<>
<div
className="fixed inset-0 z-40"
onClick={() => setMenuOpen(false)}
/>
<div
className="absolute right-0 top-full z-50 mt-1 min-w-[120px] overflow-hidden rounded-md"
style={{
background: "rgba(14, 10, 6, 0.92)",
border: "1px solid rgba(175, 138, 72, 0.5)",
backdropFilter: "blur(12px)",
WebkitBackdropFilter: "blur(12px)",
}}
>
<button
type="button"
onClick={handleLogout}
className="flex w-full items-center gap-2 px-3.5 py-2.5 text-[12px] text-cream-50/70 transition-colors hover:bg-cream-50/[0.08] hover:text-cream-50/90"
>
<i className="fa-solid fa-right-from-bracket text-[11px]" />
退
</button>
</div>
</>
)}
</div>
);
}