292 lines
15 KiB
TypeScript
292 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import Link from "next/link";
|
|
import { useRouter } from "next/navigation";
|
|
import { useEffect, useRef, useState, type FormEvent } from "react";
|
|
import { EyeClosedIcon, EyeIcon } from "lucide-react";
|
|
import { REGEXP_ONLY_DIGITS } from "input-otp";
|
|
import { Alert, AlertDescription } from "@/components/ui/alert";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { Field, FieldGroup, FieldLabel, FieldDescription } from "@/components/ui/field";
|
|
import { Input } from "@/components/ui/input";
|
|
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
|
|
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from "@/components/ui/input-group";
|
|
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;
|
|
remove(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 [captchaError, setCaptchaError] = useState("");
|
|
const [captchaAttempt, setCaptchaAttempt] = useState(0);
|
|
const [showPassword, setShowPassword] = useState(false);
|
|
const [resendSeconds, setResendSeconds] = useState(0);
|
|
const formRef = useRef<HTMLFormElement>(null);
|
|
const container = useRef<HTMLDivElement>(null);
|
|
const widget = useRef<string | null>(null);
|
|
const captcha = process.env.NODE_ENV !== "development";
|
|
useEffect(() => {
|
|
if (!resendSeconds) return;
|
|
const timer = window.setTimeout(() => setResendSeconds((seconds) => seconds - 1), 1000);
|
|
return () => window.clearTimeout(timer);
|
|
}, [resendSeconds]);
|
|
useEffect(() => {
|
|
if (!captcha || pendingEmail) return;
|
|
let active = true;
|
|
const script = document.createElement("script");
|
|
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
|
script.async = true;
|
|
const failed = () => {
|
|
if (!active) return;
|
|
window.clearTimeout(timeout);
|
|
setToken("");
|
|
setCaptchaError("โหลดการตรวจสอบความปลอดภัยไม่สำเร็จ กรุณาลองอีกครั้ง");
|
|
};
|
|
const timeout = window.setTimeout(failed, 15000);
|
|
script.onerror = failed;
|
|
script.onload = () => {
|
|
if (!active) return;
|
|
if (!container.current || !window.turnstile) return failed();
|
|
try {
|
|
widget.current = window.turnstile.render(container.current, {
|
|
sitekey: siteKey,
|
|
callback: (value: string) => {
|
|
if (!active) return;
|
|
window.clearTimeout(timeout);
|
|
setCaptchaError("");
|
|
setToken(value);
|
|
},
|
|
"expired-callback": () => {
|
|
if (!active) return;
|
|
setToken("");
|
|
setCaptchaError("การตรวจสอบหมดอายุ กรุณาตรวจสอบอีกครั้ง");
|
|
},
|
|
"error-callback": failed,
|
|
});
|
|
window.clearTimeout(timeout);
|
|
} catch { failed(); }
|
|
};
|
|
if (window.turnstile) script.onload(new Event("load"));
|
|
else document.head.append(script);
|
|
return () => {
|
|
active = false;
|
|
window.clearTimeout(timeout);
|
|
script.remove();
|
|
if (widget.current) window.turnstile?.remove(widget.current);
|
|
widget.current = null;
|
|
};
|
|
}, [captcha, siteKey, pendingEmail, captchaAttempt]);
|
|
|
|
async function sendRegistrationOtp() {
|
|
if (!register || busy || (pendingEmail && resendSeconds > 0)) 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("ส่งรหัสใหม่แล้ว กรุณาตรวจสอบอีเมลของคุณ");
|
|
setResendSeconds(60);
|
|
} 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("");
|
|
setNotice("");
|
|
try {
|
|
const fields = new FormData(form);
|
|
const email = String(fields.get("email") ?? "").trim();
|
|
const name = String(fields.get("name") ?? "").trim();
|
|
const result = await authClient.signUp.email({
|
|
name,
|
|
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);
|
|
setResendSeconds(60);
|
|
setNotice("ส่งรหัส 6 หลักแล้ว กรุณาตรวจสอบอีเมลและกรอกรหัสภายใน 5 นาที");
|
|
} catch (cause) {
|
|
setError(cause instanceof Error ? cause.message : "ลองอีกครั้ง");
|
|
setToken("");
|
|
if (widget.current) window.turnstile?.reset(widget.current);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
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("รหัสไม่ถูกต้องหรือหมดอายุ กรุณาลองอีกครั้ง");
|
|
router.replace(`/profile?setup=1&next=${encodeURIComponent(nextPath)}`);
|
|
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(`/auth/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 ? pendingEmail ? "ยืนยันอีเมล" : "สร้างบัญชี Buzz Guide" : "เข้าสู่ระบบ"}</CardTitle>
|
|
{nextPath.startsWith("/commission") && <CardDescription>เข้าสู่ระบบเพื่อบันทึกคำขอ รับผล และพูดคุยกับทีมงาน</CardDescription>}
|
|
{register && <CardDescription>ขั้นตอน {pendingEmail ? "2 จาก 2 - ยืนยันอีเมล" : "1 จาก 2 - ข้อมูลบัญชี"}</CardDescription>}
|
|
</CardHeader>
|
|
<CardContent className="flex flex-col gap-4">
|
|
{verified && <Alert><AlertDescription>ยืนยันอีเมลแล้ว กรุณาเข้าสู่ระบบ</AlertDescription></Alert>}
|
|
{verificationError && <Alert variant="destructive"><AlertDescription>ลิงก์ยืนยันไม่ถูกต้องหรือหมดอายุ กรุณาขอลิงก์ใหม่</AlertDescription></Alert>}
|
|
{notice && <Alert role="status"><AlertDescription>{notice}</AlertDescription></Alert>}
|
|
<form ref={formRef} onSubmit={submit}>
|
|
<FieldGroup>
|
|
{!pendingEmail ? <>
|
|
{register && <Field>
|
|
<FieldLabel htmlFor="name">ชื่อที่แสดง</FieldLabel>
|
|
<Input id="name" name="name" required minLength={2} maxLength={80}
|
|
autoComplete="name" disabled={busy} />
|
|
</Field>}
|
|
<Field>
|
|
<FieldLabel htmlFor="email">อีเมล</FieldLabel>
|
|
<Input id="email" name="email" type="email" required
|
|
autoComplete="email" disabled={busy} />
|
|
</Field>
|
|
<Field>
|
|
<FieldLabel htmlFor="password">รหัสผ่าน</FieldLabel>
|
|
<InputGroup>
|
|
<InputGroupInput id="password" name="password" type={showPassword ? "text" : "password"}
|
|
required minLength={6} autoComplete={register ? "new-password" : "current-password"}
|
|
aria-describedby={register ? "password-help" : undefined} disabled={busy} />
|
|
<InputGroupAddon align="inline-end" className="py-0">
|
|
<InputGroupButton size="icon-xs" disabled={busy}
|
|
aria-label={showPassword ? "ซ่อนรหัสผ่าน" : "แสดงรหัสผ่าน"}
|
|
aria-controls="password" aria-pressed={showPassword}
|
|
onClick={() => setShowPassword((current) => !current)}>
|
|
{showPassword ? <EyeIcon aria-hidden="true" /> : <EyeClosedIcon aria-hidden="true" />}
|
|
</InputGroupButton>
|
|
</InputGroupAddon>
|
|
</InputGroup>
|
|
{register && <FieldDescription id="password-help">ใช้รหัสผ่านอย่างน้อย 6 ตัวอักษร</FieldDescription>}
|
|
</Field>
|
|
{captcha && <Field>
|
|
<p className="text-sm text-muted-foreground">ตรวจสอบความปลอดภัยก่อนดำเนินการ</p>
|
|
<div ref={container} />
|
|
{captchaError && <Alert variant="destructive" role="alert"><AlertDescription>{captchaError}</AlertDescription></Alert>}
|
|
{captchaError && <Button type="button" variant="outline" disabled={busy} onClick={() => {
|
|
setToken(""); setCaptchaError(""); setCaptchaAttempt((attempt) => attempt + 1);
|
|
}}>ลองตรวจสอบอีกครั้ง</Button>}
|
|
</Field>}
|
|
</> : <>
|
|
<p className="text-sm">ส่งรหัสไปที่ <strong className="break-all">{pendingEmail}</strong></p>
|
|
<p className="text-sm text-muted-foreground">หากกรอกอีเมลผิด ให้เริ่มสมัครด้วยอีเมลที่ใช้งานได้ บัญชีเดิมจะยังไม่ยืนยันอีเมล</p>
|
|
<Button type="button" variant="outline" disabled={busy} onClick={() => {
|
|
setPendingEmail(""); setNotice(""); setError(""); setToken("");
|
|
setCaptchaError(""); setResendSeconds(0); setCaptchaAttempt((attempt) => attempt + 1);
|
|
}}>ใช้อีเมลอื่น</Button>
|
|
<Field>
|
|
<FieldLabel htmlFor="otp">รหัสยืนยัน 6 หลัก</FieldLabel>
|
|
<InputOTP id="otp" name="otp" containerClassName="w-full" inputMode="numeric" autoComplete="one-time-code"
|
|
pattern={REGEXP_ONLY_DIGITS} minLength={6} maxLength={6} required autoFocus
|
|
aria-describedby="otp-help" disabled={busy}>
|
|
<InputOTPGroup className="w-full">
|
|
{Array.from({ length: 6 }, (_, index) => <InputOTPSlot key={index} index={index} className="flex-1" />)}
|
|
</InputOTPGroup>
|
|
</InputOTP>
|
|
<FieldDescription id="otp-help">รหัสมีอายุ 5 นาที หากไม่พบอีเมล ลองดูในโฟลเดอร์สแปม</FieldDescription>
|
|
</Field>
|
|
<Button type="button" variant="outline" onClick={() => void sendRegistrationOtp()}
|
|
disabled={busy || resendSeconds > 0}>
|
|
{resendSeconds > 0 ? `ส่งรหัสใหม่ได้ใน ${resendSeconds} วินาที` : "ส่งรหัสอีกครั้ง"}
|
|
</Button>
|
|
</>}
|
|
{error && <Alert variant="destructive" role="alert"><AlertDescription>{error}</AlertDescription></Alert>}
|
|
<Button type="submit" disabled={busy || (captcha && !token && !pendingEmail)}>
|
|
{busy ? "กำลังดำเนินการ…" : register ? pendingEmail ? "ยืนยันและสร้างบัญชี" : "ถัดไป - ส่งรหัสยืนยัน" : "เข้าสู่ระบบ"}
|
|
</Button>
|
|
</FieldGroup>
|
|
</form>
|
|
{register ? <Button variant="link" nativeButton={false}
|
|
render={<Link href={`/auth/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={`/auth/register${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
|
|
สมัครสมาชิก
|
|
</Button>
|
|
<Button variant="link" size="sm" className="px-0" nativeButton={false}
|
|
render={<Link href={`/auth/forgot-password${nextPath === "/" ? "" : `?next=${encodeURIComponent(nextPath)}`}`} />}>
|
|
ลืมรหัสผ่าน?
|
|
</Button>
|
|
</div>}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|