74 lines
4.2 KiB
TypeScript
74 lines
4.2 KiB
TypeScript
"use client";
|
|
|
|
import Link from "next/link";
|
|
import { useRouter } from "next/navigation";
|
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
|
|
import { Input } from "@/components/ui/input";
|
|
import { authClient } from "@/lib/auth/client";
|
|
|
|
export function AccountForm({ mode, siteKey, nextPath }: {
|
|
mode: "login" | "register"; siteKey: string; nextPath: string;
|
|
}) {
|
|
const router = useRouter();
|
|
const register = mode === "register";
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState("");
|
|
const [token, setToken] = useState("");
|
|
const container = useRef<HTMLDivElement>(null);
|
|
const widget = useRef<string | null>(null);
|
|
const captcha = process.env.NODE_ENV !== "development";
|
|
useEffect(() => {
|
|
if (!captcha) return;
|
|
const script = document.createElement("script");
|
|
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
|
script.async = true;
|
|
script.onload = () => {
|
|
if (container.current && window.turnstile && !widget.current) widget.current = window.turnstile.render(container.current, {
|
|
sitekey: siteKey, callback: (value: string) => setToken(value),
|
|
"expired-callback": () => setToken(""), "error-callback": () => setToken(""),
|
|
});
|
|
};
|
|
document.head.append(script);
|
|
return () => { script.remove(); };
|
|
}, [captcha, siteKey]);
|
|
|
|
async function submit(event: FormEvent<HTMLFormElement>) {
|
|
event.preventDefault();
|
|
if (captcha && !token) return;
|
|
setBusy(true); setError("");
|
|
const form = new FormData(event.currentTarget);
|
|
const email = String(form.get("email") ?? "").trim();
|
|
const password = String(form.get("password") ?? "");
|
|
const fetchOptions = { headers: captcha ? { "x-captcha-response": token } : undefined };
|
|
try {
|
|
const result = register
|
|
? await authClient.signUp.email({ name: String(form.get("name") ?? "").trim(), email, password, fetchOptions })
|
|
: await authClient.signIn.email({ email, password, fetchOptions });
|
|
if (result.error) throw new Error(result.error.message ?? "เข้าสู่ระบบไม่สำเร็จ");
|
|
router.push(nextPath); router.refresh();
|
|
} catch (cause) {
|
|
setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง");
|
|
setToken("");
|
|
if (widget.current) window.turnstile?.reset(widget.current);
|
|
} finally { setBusy(false); }
|
|
}
|
|
|
|
return <Card className="w-full max-w-sm"><CardHeader><CardTitle>{register ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</CardTitle></CardHeader>
|
|
<CardContent className="flex flex-col gap-4"><form onSubmit={submit}><FieldGroup>
|
|
{register && <Field><FieldLabel htmlFor="name">ชื่อ</FieldLabel><Input id="name" name="name" required maxLength={100} /></Field>}
|
|
<Field><FieldLabel htmlFor="email">อีเมล</FieldLabel><Input id="email" name="email" type="email" required autoComplete="email" /></Field>
|
|
<Field><FieldLabel htmlFor="password">รหัสผ่าน</FieldLabel><Input id="password" name="password" type="password" required minLength={12} autoComplete={register ? "new-password" : "current-password"} /></Field>
|
|
{captcha && <div ref={container} />}
|
|
<Button type="submit" disabled={busy || (captcha && !token)}>{busy ? "กำลังดำเนินการ..." : register ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</Button>
|
|
</FieldGroup></form>
|
|
<Button variant="link" nativeButton={false} render={<Link href={`${register ? "/login" : "/register"}${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
|
|
{register ? "มีบัญชีแล้ว? เข้าสู่ระบบ" : "ยังไม่มีบัญชี? สมัครสมาชิก"}
|
|
</Button>
|
|
{error && <Alert variant="destructive"><AlertDescription>{error}</AlertDescription></Alert>}
|
|
</CardContent></Card>;
|
|
}
|