Add Turnstile protection to user actions
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { track } from "@/lib/analytics/client";
|
||||
import { TextField, TextAreaField } from "@/components/FormField";
|
||||
import { TurnstileWidget } from "@/components/TurnstileWidget";
|
||||
|
||||
type ContactFormProps = {
|
||||
toEmail?: string;
|
||||
@@ -12,12 +13,15 @@ type ContactFormProps = {
|
||||
};
|
||||
|
||||
export function ContactForm({
|
||||
siteKey,
|
||||
subjectPrefix = "Allgemeine Anfrage",
|
||||
type = "contact",
|
||||
submitLabel = "Nachricht senden",
|
||||
}: ContactFormProps) {
|
||||
}: ContactFormProps & { siteKey: string }) {
|
||||
const [state, setState] = useState<{ sent: boolean; error?: string }>({ sent: false });
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
@@ -31,7 +35,7 @@ export function ContactForm({
|
||||
const response = await fetch("/api/contact/inquiry", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, email, message, subject: `${subjectPrefix} von ${name}`, type }),
|
||||
body: JSON.stringify({ name, email, message, subject: `${subjectPrefix} von ${name}`, type, token }),
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
@@ -46,6 +50,7 @@ export function ContactForm({
|
||||
setState({ sent: false, error: "Verbindung fehlgeschlagen. Bitte versuche es erneut." });
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
setResetKey((key) => key + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +59,10 @@ export function ContactForm({
|
||||
<TextField label="Name" id="name" name="name" type="text" required autoComplete="name" />
|
||||
<TextField label="E-Mail" id="email" name="email" type="email" required autoComplete="email" />
|
||||
<TextAreaField label="Deine Nachricht" id="message" name="message" required rows={5} />
|
||||
<TurnstileWidget siteKey={siteKey} action="contact" resetKey={resetKey} onTokenChange={setToken} />
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting || !token}
|
||||
className="inline-flex items-center justify-center 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"
|
||||
>
|
||||
{submitting ? "Wird gesendet …" : submitLabel}
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { TextField, TextAreaField } from "@/components/FormField";
|
||||
import { TurnstileWidget } from "@/components/TurnstileWidget";
|
||||
|
||||
export function GroupRegistrationForm({ offerSlug }: { offerSlug: string }) {
|
||||
export function GroupRegistrationForm({ offerSlug, siteKey }: { offerSlug: string; siteKey: string }) {
|
||||
const [state, setState] = useState<{ sent: boolean; error?: string }>({ sent: false });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
@@ -22,13 +25,14 @@ export function GroupRegistrationForm({ offerSlug }: { offerSlug: string }) {
|
||||
email: data.get("email"),
|
||||
phone: data.get("phone"),
|
||||
message: data.get("message"),
|
||||
token,
|
||||
}),
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (!response.ok) setState({ sent: false, error: result.error || "Die Anmeldung konnte nicht gesendet werden." });
|
||||
else { setState({ sent: true }); event.currentTarget.reset(); }
|
||||
} catch { setState({ sent: false, error: "Verbindung fehlgeschlagen. Bitte versuche es erneut." }); }
|
||||
finally { setBusy(false); }
|
||||
finally { setBusy(false); setResetKey((key) => key + 1); }
|
||||
}
|
||||
|
||||
if (state.sent) return <p className="rounded-2xl bg-anouma-cream-light p-5 text-sm leading-relaxed text-anouma-olive" role="status">Danke, deine Anmeldung ist angekommen. Anna meldet sich, sobald sie die Plätze geprüft hat.</p>;
|
||||
@@ -39,8 +43,9 @@ export function GroupRegistrationForm({ offerSlug }: { offerSlug: string }) {
|
||||
<TextField label="E-Mail" id="group-email" name="email" type="email" required autoComplete="email" />
|
||||
<TextField label="Telefon (optional)" id="group-phone" name="phone" type="tel" autoComplete="tel" />
|
||||
<TextAreaField label="Nachricht / Motivation (optional)" id="group-message" name="message" rows={4} />
|
||||
<TurnstileWidget siteKey={siteKey} action="group-registration" resetKey={resetKey} onTokenChange={setToken} />
|
||||
{state.error && <p className="text-sm text-red-700" role="alert">{state.error}</p>}
|
||||
<button type="submit" disabled={busy} className="rounded-full bg-anouma-mauve-dark px-7 py-3.5 text-sm font-medium text-white transition-colors hover:bg-anouma-plum disabled:opacity-60">{busy ? "Wird gesendet …" : "Anmeldung senden"}</button>
|
||||
<button type="submit" disabled={busy || !token} className="rounded-full bg-anouma-mauve-dark px-7 py-3.5 text-sm font-medium text-white transition-colors hover:bg-anouma-plum disabled:opacity-60">{busy ? "Wird gesendet …" : "Anmeldung senden"}</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"use client";
|
||||
|
||||
import Script from "next/script";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
type TurnstileWidgetId = string;
|
||||
type TurnstileApi = {
|
||||
render: (
|
||||
container: HTMLElement,
|
||||
options: {
|
||||
sitekey: string;
|
||||
action: string;
|
||||
callback: (token: string) => void;
|
||||
"expired-callback": () => void;
|
||||
"error-callback": () => void;
|
||||
},
|
||||
) => TurnstileWidgetId;
|
||||
reset: (widgetId: TurnstileWidgetId) => void;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi;
|
||||
}
|
||||
}
|
||||
|
||||
type TurnstileWidgetProps = {
|
||||
siteKey: string;
|
||||
action: string;
|
||||
resetKey: number;
|
||||
onTokenChange: (token: string | null) => void;
|
||||
};
|
||||
|
||||
export function TurnstileWidget({ siteKey, action, resetKey, onTokenChange }: TurnstileWidgetProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const widgetIdRef = useRef<TurnstileWidgetId | null>(null);
|
||||
const onTokenChangeRef = useRef(onTokenChange);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [verificationStatus, setVerificationStatus] = useState<"idle" | "ready" | "expired">("idle");
|
||||
|
||||
useEffect(() => {
|
||||
onTokenChangeRef.current = onTokenChange;
|
||||
}, [onTokenChange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (resetKey === 0) return;
|
||||
if (widgetIdRef.current !== null && window.turnstile) {
|
||||
window.turnstile.reset(widgetIdRef.current);
|
||||
}
|
||||
onTokenChangeRef.current(null);
|
||||
}, [resetKey]);
|
||||
|
||||
const render = useCallback(() => {
|
||||
if (!siteKey || !containerRef.current || widgetIdRef.current !== null) return;
|
||||
if (!window.turnstile) {
|
||||
setLoadError(true);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
widgetIdRef.current = window.turnstile.render(containerRef.current, {
|
||||
sitekey: siteKey,
|
||||
action,
|
||||
callback: (token) => {
|
||||
setVerificationStatus("ready");
|
||||
onTokenChangeRef.current(token);
|
||||
},
|
||||
"expired-callback": () => {
|
||||
setVerificationStatus("expired");
|
||||
onTokenChangeRef.current(null);
|
||||
},
|
||||
"error-callback": () => {
|
||||
onTokenChangeRef.current(null);
|
||||
setLoadError(true);
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
setLoadError(true);
|
||||
onTokenChangeRef.current(null);
|
||||
}
|
||||
}, [action, siteKey]);
|
||||
|
||||
return (
|
||||
<div className="space-y-2" aria-live="polite">
|
||||
<Script
|
||||
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"
|
||||
strategy="afterInteractive"
|
||||
onReady={render}
|
||||
onError={() => setLoadError(true)}
|
||||
/>
|
||||
<div ref={containerRef} />
|
||||
{!siteKey || loadError ? (
|
||||
<p className="text-sm text-red-700" role="alert">
|
||||
Die Sicherheitsprüfung ist momentan nicht verfügbar. Bitte lade die Seite neu und versuche es erneut.
|
||||
</p>
|
||||
) : verificationStatus === "expired" ? (
|
||||
<p className="text-sm text-red-700" role="alert">
|
||||
Die Sicherheitsprüfung ist abgelaufen. Bitte bestätige sie erneut.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,12 +5,15 @@ import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { ResendVerificationButton } from "./ResendVerificationButton";
|
||||
import { TextField, FormError } from "@/components/FormField";
|
||||
import { safeLoginRedirect } from "@/lib/auth/redirect";
|
||||
import { TurnstileWidget } from "@/components/TurnstileWidget";
|
||||
|
||||
export function LoginForm() {
|
||||
export function LoginForm({ siteKey }: { siteKey: string }) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
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();
|
||||
@@ -26,10 +29,11 @@ export function LoginForm() {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify({ email, password, token }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setError("E-Mail oder Passwort ist nicht korrekt.");
|
||||
const body = await res.json().catch(() => null);
|
||||
setError(body?.error || "E-Mail oder Passwort ist nicht korrekt.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -38,6 +42,8 @@ export function LoginForm() {
|
||||
} catch {
|
||||
setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
|
||||
setLoading(false);
|
||||
} finally {
|
||||
setResetKey((key) => key + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,10 +51,14 @@ export function LoginForm() {
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<TextField label="E-Mail" id="email" name="email" type="email" required autoComplete="email" />
|
||||
<TextField label="Passwort" id="password" name="password" type="password" required autoComplete="current-password" />
|
||||
{searchParams.get("registered") === "1" && (
|
||||
<p className="text-sm text-anouma-olive" role="status">Dein Konto wurde erstellt. Melde dich jetzt an.</p>
|
||||
)}
|
||||
<TurnstileWidget siteKey={siteKey} action="login" 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 geprüft …" : "Anmelden"}
|
||||
|
||||
@@ -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"}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { fieldClass, TextField, FormError } from "@/components/FormField";
|
||||
import { TurnstileWidget } from "@/components/TurnstileWidget";
|
||||
|
||||
export const MEETING_SESSION_KEY = "anouma-meeting-session";
|
||||
const MEETING_CLIENT_ID_KEY = "anouma-meeting-client-id";
|
||||
@@ -37,13 +38,15 @@ export type StoredMeetingSession = {
|
||||
eventSlug: string;
|
||||
};
|
||||
|
||||
export function JoinForm({ slug }: { slug: string }) {
|
||||
export function JoinForm({ slug, siteKey }: { slug: string; siteKey: string }) {
|
||||
const router = useRouter();
|
||||
const [name, setName] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
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();
|
||||
@@ -53,7 +56,7 @@ export function JoinForm({ slug }: { slug: string }) {
|
||||
const res = await fetch(`/api/meetings/${slug}/join`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, password, clientId: getOrCreateClientId() }),
|
||||
body: JSON.stringify({ name, password, clientId: getOrCreateClientId(), token }),
|
||||
credentials: "include",
|
||||
});
|
||||
const data = await res.json();
|
||||
@@ -78,6 +81,8 @@ export function JoinForm({ slug }: { slug: string }) {
|
||||
} catch {
|
||||
setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
|
||||
setLoading(false);
|
||||
} finally {
|
||||
setResetKey((key) => key + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,10 +123,11 @@ export function JoinForm({ slug }: { slug: string }) {
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
<TurnstileWidget siteKey={siteKey} action="meeting-join" 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 geprüft …" : "Meeting betreten"}
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { TextField, FormError } from "@/components/FormField";
|
||||
import { TurnstileWidget } from "@/components/TurnstileWidget";
|
||||
|
||||
export function RegisterForm({ slug }: { slug: string }) {
|
||||
export function RegisterForm({ slug, siteKey }: { slug: string; siteKey: string }) {
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState("");
|
||||
const [status, setStatus] = useState<"idle" | "loading" | "done" | "error">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [token, setToken] = useState<string | null>(null);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
|
||||
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault();
|
||||
@@ -17,7 +20,7 @@ export function RegisterForm({ slug }: { slug: string }) {
|
||||
const res = await fetch(`/api/meetings/${slug}/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, email }),
|
||||
body: JSON.stringify({ name, email, token }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
@@ -29,6 +32,8 @@ export function RegisterForm({ slug }: { slug: string }) {
|
||||
} catch {
|
||||
setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
|
||||
setStatus("error");
|
||||
} finally {
|
||||
setResetKey((key) => key + 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,10 +65,11 @@ export function RegisterForm({ slug }: { slug: string }) {
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoComplete="email"
|
||||
/>
|
||||
<TurnstileWidget siteKey={siteKey} action="meeting-registration" resetKey={resetKey} onTokenChange={setToken} />
|
||||
{error && <FormError>{error}</FormError>}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={status === "loading"}
|
||||
disabled={status === "loading" || !token}
|
||||
className="rounded-full bg-anouma-mauve-dark px-6 py-3 text-sm font-medium text-white transition-colors duration-300 hover:bg-anouma-plum disabled:opacity-60"
|
||||
>
|
||||
{status === "loading" ? "Wird gesendet …" : "Zum Termin anmelden"}
|
||||
|
||||
Reference in New Issue
Block a user