"use client"; import { useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { z } from "zod"; import { Loader2, ShieldCheck } from "lucide-react"; import { toast } from "sonner"; import { useRouter } from "next/navigation"; import { authClient } from "@/lib/auth-client"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Checkbox } from "@/components/ui/checkbox"; const formSchema = z.object({ code: z.string().length(6, "Code must be 6 digits").regex(/^\d+$/, "Code must be numeric"), trustDevice: z.boolean(), }); type FormData = z.infer; interface TwoFactorFormProps { callbackURL?: string; } export function TwoFactorForm({ callbackURL = "/" }: TwoFactorFormProps) { const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { code: "", trustDevice: true, }, }); async function onSubmit(data: FormData) { setIsLoading(true); try { const result = await authClient.twoFactor.verifyTotp({ code: data.code, trustDevice: data.trustDevice, }); if (result.error) { toast.error(result.error.message || "Invalid verification code"); form.setError("code", { message: "Invalid code" }); return; } toast.success("Verified successfully!"); router.push(callbackURL); } catch (error) { toast.error("An unexpected error occurred"); console.error("2FA verification error:", error); } finally { setIsLoading(false); } } return (
( Verification Code )} /> (
Trust this device for 30 days
)} /> ); }