70 lines
2.7 KiB
TypeScript
70 lines
2.7 KiB
TypeScript
"use client";
|
|
|
|
import { useState, type FormEvent } from "react";
|
|
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({ 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();
|
|
setError(null);
|
|
setLoading(true);
|
|
|
|
const data = new FormData(e.currentTarget);
|
|
const email = String(data.get("email") ?? "");
|
|
const password = String(data.get("password") ?? "");
|
|
|
|
try {
|
|
const res = await fetch("/api/customers/login", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
credentials: "include",
|
|
body: JSON.stringify({ email, password, token }),
|
|
});
|
|
if (!res.ok) {
|
|
const body = await res.json().catch(() => null);
|
|
setError(body?.error || "E-Mail oder Passwort ist nicht korrekt.");
|
|
setLoading(false);
|
|
return;
|
|
}
|
|
router.push(safeLoginRedirect(searchParams.get("next")));
|
|
router.refresh();
|
|
} catch {
|
|
setError("Verbindung fehlgeschlagen. Bitte versuche es erneut.");
|
|
setLoading(false);
|
|
} finally {
|
|
setResetKey((key) => key + 1);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<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 || !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"}
|
|
</button>
|
|
<ResendVerificationButton variant="email-prompt" className="pt-1" />
|
|
</form>
|
|
);
|
|
}
|