"use client"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { ErrorText } from "@/components/forms"; import { Button } from "@/components/ui/button"; import { Field, FieldDescription, FieldGroup, FieldLabel, } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { authClient } from "@/lib/auth-client"; /** Signs in with Better Auth (then a code, if two-factor sign-in is on), then goes to next (already checked to be a * path on this site). */ export function SignInForm({ next }: { next: string }) { const router = useRouter(); const [error, setError] = useState(""); const [pending, setPending] = useState(false); // After the password, when two-factor sign-in is on: a code from the app, or a backup code. const [step, setStep] = useState<"password" | "code" | "backup">("password"); const done = () => { router.push(next); router.refresh(); }; async function signIn(form: FormData) { const { data, error } = await authClient.signIn.username({ username: String(form.get("username")), password: String(form.get("password")), }); if (error) return setError(error.message ?? "That didn't work. Try again."); if (data && "twoFactorRedirect" in data && data.twoFactorRedirect) return setStep("code"); done(); } async function verify(form: FormData) { const code = String(form.get("code")).replace(/\s+/g, ""); const { error } = step === "code" ? await authClient.twoFactor.verifyTotp({ code }) : await authClient.twoFactor.verifyBackupCode({ code }); if (error) return setError(error.message ?? "That code didn't work. Try again."); done(); } async function submit(form: FormData) { setError(""); setPending(true); await (step === "password" ? signIn(form) : verify(form)); setPending(false); } return (
); }