feat : update
This commit is contained in:
@@ -10,20 +10,41 @@ import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { authClient } from "@/lib/auth/client";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
render(container: HTMLElement, options: {
|
||||
sitekey: string;
|
||||
callback: (token: string) => void;
|
||||
"expired-callback": () => void;
|
||||
"error-callback": () => void;
|
||||
}): string;
|
||||
reset(widgetId: string): void;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function AccountForm({
|
||||
mode,
|
||||
siteKey,
|
||||
nextPath,
|
||||
verified,
|
||||
verificationError,
|
||||
}: {
|
||||
mode: "login" | "register";
|
||||
siteKey: string;
|
||||
nextPath: string;
|
||||
verified?: boolean;
|
||||
verificationError?: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const register = mode === "register";
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [pendingEmail, setPendingEmail] = useState("");
|
||||
const [notice, setNotice] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const widget = useRef<string | null>(null);
|
||||
const captcha = process.env.NODE_ENV !== "development";
|
||||
@@ -48,47 +69,40 @@ export function AccountForm({
|
||||
};
|
||||
}, [captcha, siteKey]);
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (captcha && !token) return;
|
||||
async function sendRegistrationOtp() {
|
||||
if (!register || busy) return;
|
||||
if (pendingEmail) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setNotice("");
|
||||
try {
|
||||
const result = await authClient.emailOtp.sendVerificationOtp({
|
||||
email: pendingEmail, type: "email-verification",
|
||||
});
|
||||
if (result.error) throw new Error("ส่งรหัสใหม่ไม่สำเร็จ กรุณาลองอีกครั้ง");
|
||||
setNotice("ส่งรหัสใหม่แล้ว กรุณาตรวจสอบอีเมลของคุณ");
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "ส่งรหัสใหม่ไม่สำเร็จ");
|
||||
} finally { setBusy(false); }
|
||||
return;
|
||||
}
|
||||
const form = formRef.current;
|
||||
if (!form?.reportValidity() || (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,
|
||||
};
|
||||
setNotice("");
|
||||
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();
|
||||
const fields = new FormData(form);
|
||||
const email = String(fields.get("email") ?? "").trim();
|
||||
const result = await authClient.signUp.email({
|
||||
name: String(fields.get("name") ?? "").trim(),
|
||||
email,
|
||||
password: String(fields.get("password") ?? ""),
|
||||
fetchOptions: { headers: captcha ? { "x-captcha-response": token } : undefined },
|
||||
});
|
||||
if (result.error) throw new Error(result.error.message ?? "ส่งรหัสไม่สำเร็จ กรุณาลองอีกครั้ง");
|
||||
setPendingEmail(email);
|
||||
setNotice("ส่งรหัส 6 หลักแล้ว กรุณาตรวจสอบอีเมลและกรอกรหัสภายใน 5 นาที");
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง");
|
||||
setToken("");
|
||||
@@ -98,13 +112,59 @@ export function AccountForm({
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (register && !pendingEmail) return sendRegistrationOtp();
|
||||
if (busy || (!register && captcha && !token)) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
if (register) {
|
||||
const form = new FormData(event.currentTarget);
|
||||
const result = await authClient.emailOtp.verifyEmail({
|
||||
email: pendingEmail, otp: String(form.get("otp") ?? "").trim(),
|
||||
});
|
||||
if (result.error) throw new Error("รหัสไม่ถูกต้องหรือหมดอายุ กรุณาลองอีกครั้ง");
|
||||
const setupPath = `/profile?setup=1&next=${encodeURIComponent(nextPath)}`;
|
||||
router.push(`/login?verified=1&next=${encodeURIComponent(setupPath)}`);
|
||||
router.refresh();
|
||||
return;
|
||||
}
|
||||
const form = new FormData(event.currentTarget);
|
||||
const email = String(form.get("email") ?? "").trim();
|
||||
const result = await authClient.signIn.email({
|
||||
email, password: String(form.get("password") ?? ""),
|
||||
fetchOptions: { headers: captcha ? { "x-captcha-response": token } : undefined },
|
||||
});
|
||||
if (result.error?.code === "EMAIL_NOT_VERIFIED") {
|
||||
router.push(`/check-email?email=${encodeURIComponent(email)}&next=${encodeURIComponent(nextPath)}`);
|
||||
return;
|
||||
}
|
||||
if (result.error) throw new Error(result.error.message ?? "เข้าสู่ระบบไม่สำเร็จ");
|
||||
router.push(nextPath);
|
||||
router.refresh();
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง");
|
||||
if (!register) {
|
||||
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}>
|
||||
{verified && <Alert><AlertDescription>ยืนยันอีเมลแล้ว กรุณาเข้าสู่ระบบ</AlertDescription></Alert>}
|
||||
{verificationError && <Alert variant="destructive"><AlertDescription>ลิงก์ยืนยันไม่ถูกต้องหรือหมดอายุ กรุณาขอลิงก์ใหม่</AlertDescription></Alert>}
|
||||
{notice && <Alert><AlertDescription>{notice}</AlertDescription></Alert>}
|
||||
{register && !pendingEmail && <p className="text-sm text-muted-foreground">
|
||||
กรอกชื่อ อีเมล และรหัสผ่าน แล้วกดส่ง OTP
|
||||
</p>}
|
||||
<form ref={formRef} onSubmit={submit}>
|
||||
<FieldGroup>
|
||||
{register && (
|
||||
<Field>
|
||||
@@ -116,24 +176,27 @@ export function AccountForm({
|
||||
minLength={2}
|
||||
maxLength={80}
|
||||
autoComplete="name"
|
||||
disabled={busy || Boolean(pendingEmail)}
|
||||
/>
|
||||
</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"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
className="min-w-0 flex-1"
|
||||
required
|
||||
autoComplete="email"
|
||||
disabled={busy || Boolean(pendingEmail)}
|
||||
/>
|
||||
{register && <Button type="button" variant="outline" className="shrink-0"
|
||||
onClick={sendRegistrationOtp} disabled={busy || (captcha && !token && !pendingEmail)}>
|
||||
{busy ? "กำลังส่ง..." : pendingEmail ? "ส่งอีกครั้ง" : "ส่ง OTP"}
|
||||
</Button>}
|
||||
</div>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">รหัสผ่าน</FieldLabel>
|
||||
@@ -144,29 +207,38 @@ export function AccountForm({
|
||||
required
|
||||
minLength={6}
|
||||
autoComplete={register ? "new-password" : "current-password"}
|
||||
disabled={busy || Boolean(pendingEmail)}
|
||||
/>
|
||||
</Field>
|
||||
{captcha && <div ref={container} />}
|
||||
<Button type="submit" disabled={busy || (captcha && !token)}>
|
||||
{register && <Field>
|
||||
<FieldLabel htmlFor="otp">รหัส OTP</FieldLabel>
|
||||
<Input id="otp" name="otp" inputMode="numeric" autoComplete="one-time-code"
|
||||
pattern="[0-9]{6}" minLength={6} maxLength={6} required={Boolean(pendingEmail)}
|
||||
placeholder="กดส่ง OTP ก่อน" disabled={busy || !pendingEmail} />
|
||||
</Field>}
|
||||
{captcha && !pendingEmail && <div ref={container} />}
|
||||
{(!register || pendingEmail) && <Button type="submit" disabled={busy || (!register && captcha && !token)}>
|
||||
{busy
|
||||
? "กำลังดำเนินการ..."
|
||||
: register
|
||||
? "สมัครสมาชิก"
|
||||
? "ยืนยันอีเมล"
|
||||
: "เข้าสู่ระบบ"}
|
||||
</Button>
|
||||
</Button>}
|
||||
</FieldGroup>
|
||||
</form>
|
||||
<Button
|
||||
variant="link"
|
||||
nativeButton={false}
|
||||
render={
|
||||
<Link
|
||||
href={`${register ? "/login" : "/register"}${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{register ? "มีบัญชีแล้ว? เข้าสู่ระบบ" : "ยังไม่มีบัญชี? สมัครสมาชิก"}
|
||||
</Button>
|
||||
{register ? <Button variant="link" nativeButton={false}
|
||||
render={<Link href={`/login${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
|
||||
มีบัญชีแล้ว? เข้าสู่ระบบ
|
||||
</Button> : <div className="flex items-center justify-between gap-2">
|
||||
<Button variant="link" size="sm" className="px-0" nativeButton={false}
|
||||
render={<Link href={`/register${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
|
||||
สมัครสมาชิก
|
||||
</Button>
|
||||
<Button variant="link" size="sm" className="px-0" nativeButton={false}
|
||||
render={<Link href="/forgot-password" />}>
|
||||
ลืมรหัสผ่าน?
|
||||
</Button>
|
||||
</div>}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
|
||||
Reference in New Issue
Block a user