286 lines
12 KiB
TypeScript
286 lines
12 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 { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
|
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";
|
|
import { ProfileImageInput } from "./profile-image-input";
|
|
|
|
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 [pendingName, setPendingName] = useState("");
|
|
const [notice, setNotice] = useState("");
|
|
const [token, setToken] = useState("");
|
|
const [profileImage, setProfileImage] = useState<File | null>(null);
|
|
const [profilePreview, setProfilePreview] = useState<string | null>(null);
|
|
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 (profilePreview) URL.revokeObjectURL(profilePreview);
|
|
}, [profilePreview]);
|
|
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 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("");
|
|
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);
|
|
setPendingName(name);
|
|
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("รหัสไม่ถูกต้องหรือหมดอายุ กรุณาลองอีกครั้ง");
|
|
if (profileImage) {
|
|
const profile = new FormData();
|
|
profile.set("name", pendingName);
|
|
profile.set("image", profileImage);
|
|
const response = await fetch("/api/profile", { method: "POST", body: profile });
|
|
if (!response.ok) {
|
|
router.replace(`/profile?setup=1&upload=failed&next=${encodeURIComponent(nextPath)}`);
|
|
router.refresh();
|
|
return;
|
|
}
|
|
}
|
|
router.replace(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 ? "สมัครสมาชิก" : "เข้าสู่ระบบ"}</CardTitle>
|
|
</CardHeader>
|
|
<CardContent className="flex flex-col gap-4">
|
|
{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>
|
|
<FieldLabel htmlFor="name">ชื่อที่แสดง</FieldLabel>
|
|
<Input
|
|
id="name"
|
|
name="name"
|
|
required
|
|
minLength={2}
|
|
maxLength={80}
|
|
autoComplete="name"
|
|
disabled={busy || Boolean(pendingEmail)}
|
|
/>
|
|
</Field>
|
|
)}
|
|
{register && <Field>
|
|
<FieldLabel htmlFor="register-image">รูปโปรไฟล์ (ไม่บังคับ)</FieldLabel>
|
|
<div className="flex items-center gap-4">
|
|
<Avatar size="lg" className="size-16">
|
|
{profilePreview && <AvatarImage src={profilePreview} alt="รูปโปรไฟล์" />}
|
|
<AvatarFallback>?</AvatarFallback>
|
|
</Avatar>
|
|
<ProfileImageInput id="register-image" disabled={busy}
|
|
onChange={(cropped) => {
|
|
setProfileImage(cropped);
|
|
setProfilePreview(URL.createObjectURL(cropped));
|
|
setError("");
|
|
}} onError={setError} />
|
|
</div>
|
|
</Field>}
|
|
<Field>
|
|
<FieldLabel htmlFor="email">อีเมล</FieldLabel>
|
|
<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>
|
|
<Input
|
|
id="password"
|
|
name="password"
|
|
type="password"
|
|
required
|
|
minLength={6}
|
|
autoComplete={register ? "new-password" : "current-password"}
|
|
disabled={busy || Boolean(pendingEmail)}
|
|
/>
|
|
</Field>
|
|
{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} />}
|
|
<Button type="submit" disabled={busy || (register && !pendingEmail) || (!register && captcha && !token)}>
|
|
{busy
|
|
? "กำลังดำเนินการ..."
|
|
: register
|
|
? "สมัครสมาชิก"
|
|
: "เข้าสู่ระบบ"}
|
|
</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" />}>
|
|
ลืมรหัสผ่าน?
|
|
</Button>
|
|
</div>}
|
|
{error && (
|
|
<Alert variant="destructive">
|
|
<AlertDescription>{error}</AlertDescription>
|
|
</Alert>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
);
|
|
}
|