Add Turnstile protection to user actions

This commit is contained in:
2026-09-18 00:39:14 +02:00
parent 79cd7f7475
commit 1970be29e7
25 changed files with 406 additions and 39 deletions
+12 -16
View File
@@ -3,11 +3,14 @@
import { useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { TextField, FormError } from "@/components/FormField";
import { TurnstileWidget } from "@/components/TurnstileWidget";
export function RegisterForm() {
export function RegisterForm({ siteKey }: { siteKey: string }) {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [token, setToken] = useState<string | null>(null);
const [resetKey, setResetKey] = useState(0);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
@@ -23,30 +26,22 @@ export function RegisterForm() {
const createRes = await fetch("/api/customers", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, email, password }),
body: JSON.stringify({ name, email, password, token }),
});
if (!createRes.ok) {
const body = await createRes.json().catch(() => null);
setError(body?.errors?.[0]?.message || "Die Registrierung ist fehlgeschlagen. Ist die E-Mail-Adresse schon vergeben?");
setError(body?.error || body?.errors?.[0]?.message || "Die Registrierung ist fehlgeschlagen. Ist die E-Mail-Adresse schon vergeben?");
setLoading(false);
return;
}
const loginRes = await fetch("/api/customers/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ email, password }),
});
if (!loginRes.ok) {
router.push("/login");
return;
}
router.push("/konto");
router.refresh();
// Login is separately protected by its own single-use Turnstile token.
router.push("/login?registered=1");
} catch {
setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
setLoading(false);
} finally {
setResetKey((key) => key + 1);
}
}
@@ -63,10 +58,11 @@ export function RegisterForm() {
minLength={8}
autoComplete="new-password"
/>
<TurnstileWidget siteKey={siteKey} action="registration" resetKey={resetKey} onTokenChange={setToken} />
{error && <FormError>{error}</FormError>}
<button
type="submit"
disabled={loading}
disabled={loading || !token}
className="w-full rounded-full bg-anouma-mauve-dark px-7 py-3.5 text-sm font-medium tracking-wide text-white transition-colors duration-300 hover:bg-anouma-plum disabled:opacity-60"
>
{loading ? "Wird erstellt …" : "Konto erstellen"}