Files
buzz-sheet/components/auth/account-form.tsx
T
gunshiz 1ed9ea29eb
CI / Verify (push) Successful in 1m57s
CI / Build immutable images and deploy (push) Successful in 2m20s
feat: update
2026-10-02 18:28:23 +07:00

179 lines
6.4 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 image = register ? form.get("image") : null;
const fetchOptions = {
headers: captcha ? { "x-captcha-response": token } : undefined,
};
try {
if (image instanceof File && image.size > 0 &&
(image.size > 6 * 1024 * 1024 || !["image/png", "image/jpeg", "image/webp"].includes(image.type))) {
throw new Error("ใช้รูป PNG, JPEG หรือ WebP ขนาดไม่เกิน 6 MB");
}
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 ?? "เข้าสู่ระบบไม่สำเร็จ");
if (register && image instanceof File && image.size > 0) {
const profile = new FormData();
profile.set("name", String(form.get("name") ?? "").trim());
profile.set("image", image);
const uploaded = await fetch("/api/profile", { method: "POST", body: profile })
.then((response) => response.ok).catch(() => false);
if (!uploaded) {
router.push(`/profile?setup=1&upload=failed&next=${encodeURIComponent(nextPath)}`);
router.refresh();
return;
}
}
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
minLength={2}
maxLength={80}
autoComplete="name"
/>
</Field>
)}
{register && (
<Field>
<FieldLabel htmlFor="register-image">รูปโปรไฟล์ (ไม่บังคับ)</FieldLabel>
<Input id="register-image" name="image" type="file" accept="image/png,image/jpeg,image/webp" />
</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={6}
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>
);
}