"use client"; import * as React from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { AlertTriangle, LockKeyhole } from "lucide-react"; import { authClient } from "@/lib/auth-client"; import { Button } from "@/components/ui/button"; import { Field } from "@/components/ui/input"; import { toast } from "@/components/ui/toast"; import { AuthCard, FormError } from "./auth-card"; import { PasswordInput } from "./password-input"; import { PasswordStrength, scorePassword } from "./password-strength"; import { humanAuthError, passwordLengthError, type AuthClientError } from "./auth-errors"; export function ResetForm({ token, errorCode }: { token: string | null; errorCode: string | null }) { const router = useRouter(); const [password, setPassword] = React.useState(""); const [confirm, setConfirm] = React.useState(""); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); const [fieldErrors, setFieldErrors] = React.useState<{ password?: string; confirm?: string }>({}); const [invalidLink, setInvalidLink] = React.useState(errorCode ? humanAuthError({ code: errorCode }, "reset") : token ? null : "This reset link is missing its token. Request a new one."); async function onSubmit(e: React.FormEvent) { e.preventDefault(); setError(null); const fe: typeof fieldErrors = {}; const pwErr = passwordLengthError(password); if (pwErr) fe.password = pwErr; else if (scorePassword(password).score < 2) fe.password = "That password is too easy to guess. Try a longer or less common one."; if (confirm !== password) fe.confirm = "The passwords don't match."; setFieldErrors(fe); if (Object.keys(fe).length || !token) return; setLoading(true); try { const { error: err } = await authClient.resetPassword({ newPassword: password, token }); if (err) { const ae = err as AuthClientError; if (ae.code === "INVALID_TOKEN" || ae.code === "TOKEN_EXPIRED") { setInvalidLink(humanAuthError(ae, "reset")); return; } setError(humanAuthError(ae, "reset")); return; } toast.success("Password updated", "Sign in with your new password."); router.push("/login?notice=reset"); } catch { setError("We couldn't reach the server. Check your connection and try again."); } finally { setLoading(false); } } if (invalidLink) { return ( } title="This link doesn't work" description={invalidLink} footer={ Back to sign in } > ); } return ( } title="Choose a new password" description="For your security, all other sessions will be signed out once the password changes.">
{error} setPassword(e.target.value)} placeholder="10 to 128 characters" invalid={!!fieldErrors.password} aria-describedby="reset-password-strength" autoFocus /> setConfirm(e.target.value)} placeholder="Type it once more" invalid={!!fieldErrors.confirm} />
); }