"use client"; import { useState } from "react"; import TextField from "@/components/ui/TextField"; import LoadingSpinner from "@/components/icons/LoadingSpinner"; import { computeVdfInWorker } from "@/lib/vdf"; import useSWR from "swr"; import { ApiRequestError } from "@/lib/net"; interface CaptchaSessionResponse { g: string; n: string; t: string; id: string; } interface CaptchaResultResponse { token: string; } async function fetcher(input: RequestInfo, init?: RequestInit): Promise { const res = await fetch(input, init); if (!res.ok) { const error = new ApiRequestError("An error occurred while fetching the data."); error.response = await res.json(); error.code = res.status; throw error; } return res.json(); } interface RegistrationFormProps { backendURL: string; } const SignUpForm: React.FC = ({ backendURL }) => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [nickname, setNickname] = useState(""); const [loading, setLoading] = useState(false); const { data: captchaSession, error: captchaSessionError, mutate: createCaptchaSession } = useSWR( `${backendURL}/captcha/session`, (url) => fetcher(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ route: "POST-/user" }) }), { revalidateOnFocus: false, revalidateOnReconnect: false } ); const getCaptchaResult = async (id: string, ans: string): Promise => { const url = new URL(`${backendURL}/captcha/${id}/result`); url.searchParams.set("ans", ans); return fetcher(url.toString()); }; const register = async () => { setLoading(true); try { if (!captchaSession?.g || !captchaSession?.n || !captchaSession?.t || !captchaSession?.id) { console.error("Captcha session data is missing."); return; } const ans = await computeVdfInWorker( BigInt(captchaSession.g), BigInt(captchaSession.n), BigInt(captchaSession.t) ); const captchaResult = await getCaptchaResult(captchaSession.id, ans.result.toString()); if (!captchaResult.token) { } // Proceed with user registration using username, password, and nickname const registrationUrl = new URL(`${backendURL}/user`); const registrationResponse = await fetch(registrationUrl.toString(), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password, nickname, // Include the captcha result if needed by the backend captchaId: captchaSession.id, captchaAnswer: ans.result.toString() }) }); if (registrationResponse.ok) { console.log("Registration successful!"); // Optionally redirect the user or show a success message //router.push("/login"); // Example redirection } else { console.error("Registration failed:", await registrationResponse.json()); // Handle registration error } } catch (error) { console.error("Registration process error:", error); // Handle general error } finally { setLoading(false); } }; return (
{ e.preventDefault(); await register(); }} > ); }; export default SignUpForm;