feat(auth) : protect admin login with turnstile
This commit is contained in:
@@ -12,6 +12,10 @@ BETTER_AUTH_SECRET=replace-with-at-least-32-random-bytes
|
||||
# Separate trusted browser origins with commas for local development or proxies.
|
||||
BETTER_AUTH_TRUSTED_ORIGINS=http://localhost:3000
|
||||
|
||||
# Cloudflare Turnstile administrator login protection
|
||||
TURNSTILE_SITE_KEY=replace-with-turnstile-site-key
|
||||
TURNSTILE_SECRET_KEY=replace-with-turnstile-secret-key
|
||||
|
||||
# Redis remote cache, event transport, and outbox worker
|
||||
REDIS_URL=rediss://default:[email protected]:6379
|
||||
REDIS_CACHE_PREFIX=buzz:next-cache
|
||||
|
||||
@@ -9,11 +9,16 @@ export default async function AdminLoginPage() {
|
||||
await connection();
|
||||
if (await getAdminSession()) redirect("/admin");
|
||||
|
||||
const turnstileSiteKey = process.env.TURNSTILE_SITE_KEY;
|
||||
if (!turnstileSiteKey) {
|
||||
throw new Error("TURNSTILE_SITE_KEY is required for administrator login.");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-svh">
|
||||
<SiteHeader />
|
||||
<main className="grid min-h-[calc(100svh-4rem)] place-items-center px-4 py-12">
|
||||
<LoginCard />
|
||||
<LoginCard turnstileSiteKey={turnstileSiteKey} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { CircleAlertIcon, LogInIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { type FormEvent, useState } from "react";
|
||||
import Script from "next/script";
|
||||
import { type FormEvent, useCallback, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
Alert,
|
||||
@@ -24,13 +25,73 @@ import { Input } from "@/components/ui/input";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
|
||||
export function LoginCard() {
|
||||
interface TurnstileApi {
|
||||
render(
|
||||
container: HTMLElement,
|
||||
options: {
|
||||
sitekey: string;
|
||||
callback: (token: string) => void;
|
||||
"expired-callback": () => void;
|
||||
"error-callback": () => void;
|
||||
},
|
||||
): string;
|
||||
reset(widgetId: string): void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi;
|
||||
}
|
||||
}
|
||||
|
||||
interface LoginCardProps {
|
||||
turnstileSiteKey: string;
|
||||
}
|
||||
|
||||
export function LoginCard({ turnstileSiteKey }: LoginCardProps) {
|
||||
const router = useRouter();
|
||||
const turnstileContainerRef = useRef<HTMLDivElement>(null);
|
||||
const turnstileWidgetIdRef = useRef<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
|
||||
|
||||
const renderTurnstile = useCallback(() => {
|
||||
if (
|
||||
!window.turnstile ||
|
||||
!turnstileContainerRef.current ||
|
||||
turnstileWidgetIdRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
turnstileWidgetIdRef.current = window.turnstile.render(
|
||||
turnstileContainerRef.current,
|
||||
{
|
||||
sitekey: turnstileSiteKey,
|
||||
callback: (token) => {
|
||||
setTurnstileToken(token);
|
||||
setError(null);
|
||||
},
|
||||
"expired-callback": () => setTurnstileToken(null),
|
||||
"error-callback": () => {
|
||||
setTurnstileToken(null);
|
||||
setError("ยืนยันตัวตนไม่สำเร็จ โปรดลองอีกครั้ง");
|
||||
},
|
||||
},
|
||||
);
|
||||
}, [turnstileSiteKey]);
|
||||
|
||||
function resetTurnstile() {
|
||||
setTurnstileToken(null);
|
||||
if (window.turnstile && turnstileWidgetIdRef.current) {
|
||||
window.turnstile.reset(turnstileWidgetIdRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
async function signIn(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!turnstileToken) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
@@ -43,6 +104,9 @@ export function LoginCard() {
|
||||
email,
|
||||
password,
|
||||
rememberMe: true,
|
||||
fetchOptions: {
|
||||
headers: { "x-captcha-response": turnstileToken },
|
||||
},
|
||||
});
|
||||
if (result.error) {
|
||||
setError(
|
||||
@@ -57,6 +121,7 @@ export function LoginCard() {
|
||||
} catch {
|
||||
setError("เชื่อมต่อระบบเข้าสู่ระบบไม่ได้ โปรดลองอีกครั้ง");
|
||||
} finally {
|
||||
resetTurnstile();
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
@@ -96,6 +161,19 @@ export function LoginCard() {
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<div ref={turnstileContainerRef} className="min-h-[65px]" />
|
||||
<Script
|
||||
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
|
||||
strategy="afterInteractive"
|
||||
onLoad={renderTurnstile}
|
||||
onReady={renderTurnstile}
|
||||
onError={() => {
|
||||
setTurnstileToken(null);
|
||||
setError("โหลดระบบยืนยันตัวตนไม่สำเร็จ โปรดลองอีกครั้ง");
|
||||
}}
|
||||
/>
|
||||
</Field>
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<CircleAlertIcon aria-hidden="true" />
|
||||
@@ -103,7 +181,12 @@ export function LoginCard() {
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
<Button className="w-full" size="lg" type="submit" disabled={loading}>
|
||||
<Button
|
||||
className="w-full"
|
||||
size="lg"
|
||||
type="submit"
|
||||
disabled={loading || !turnstileToken}
|
||||
>
|
||||
{loading ? (
|
||||
<Spinner data-icon="inline-start" />
|
||||
) : (
|
||||
|
||||
+10
-2
@@ -3,7 +3,7 @@ import "server-only";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { nextCookies } from "better-auth/next-js";
|
||||
import { admin } from "better-auth/plugins";
|
||||
import { admin, captcha } from "better-auth/plugins";
|
||||
import { headers } from "next/headers";
|
||||
|
||||
import { getDb } from "@/db";
|
||||
@@ -60,7 +60,15 @@ function createAuth() {
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [admin({ defaultRole: "admin" }), nextCookies()],
|
||||
plugins: [
|
||||
captcha({
|
||||
provider: "cloudflare-turnstile",
|
||||
secretKey: required("TURNSTILE_SECRET_KEY"),
|
||||
endpoints: ["/sign-in/email"],
|
||||
}),
|
||||
admin({ defaultRole: "admin" }),
|
||||
nextCookies(),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -33,4 +33,25 @@ describe("administrative security boundaries", () => {
|
||||
source.lastIndexOf("getAdminSession"),
|
||||
);
|
||||
});
|
||||
|
||||
it("enforces Cloudflare Turnstile on email sign-in", async () => {
|
||||
const source = await readFile(
|
||||
new URL("../lib/auth/server.ts", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
expect(source).toContain('provider: "cloudflare-turnstile"');
|
||||
expect(source).toContain('secretKey: required("TURNSTILE_SECRET_KEY")');
|
||||
expect(source).toContain('endpoints: ["/sign-in/email"]');
|
||||
});
|
||||
|
||||
it("requires a Turnstile token before submitting administrator login", async () => {
|
||||
const source = await readFile(
|
||||
new URL("../components/admin/login-card.tsx", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
expect(source).toContain('headers: { "x-captcha-response": turnstileToken }');
|
||||
expect(source).toContain("disabled={loading || !turnstileToken}");
|
||||
expect(source).toContain('"expired-callback": () => setTurnstileToken(null)');
|
||||
expect(source).toContain("resetTurnstile();");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user