feat(auth): recover a password with a code sent by email
Enable BetterAuth's emailOTP plugin for password resets: a 6-digit code, valid for 10 minutes with 3 attempts, stored hashed in `verifications` (no migration). The code goes out through the existing Resend mailer with a new Spanish template, and other sessions are revoked after the reset. The web app gets a two-step /forgot-password route (request the code, then set the new password) linked from sign-in. Unknown emails get the same responses as known ones so the form doesn't reveal accounts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { emailOTPClient } from 'better-auth/client/plugins'
|
||||
import { createAuthClient } from 'better-auth/react'
|
||||
|
||||
/**
|
||||
@@ -7,6 +8,7 @@ import { createAuthClient } from 'better-auth/react'
|
||||
*/
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
|
||||
plugins: [emailOTPClient()],
|
||||
})
|
||||
|
||||
export const { signIn, signUp, signOut, useSession } = authClient
|
||||
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient
|
||||
|
||||
288
apps/web/src/routes/(auth)/forgot-password.tsx
Normal file
288
apps/web/src/routes/(auth)/forgot-password.tsx
Normal file
@@ -0,0 +1,288 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
||||
import { useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { toast } from 'sonner'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { AppBrand } from '@/components/app-logo'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { emailOtp } from '@/lib/auth-client'
|
||||
|
||||
type ForgotPasswordSearch = { redirect?: string; email?: string }
|
||||
|
||||
export const Route = createFileRoute('/(auth)/forgot-password')({
|
||||
validateSearch: (search: Record<string, unknown>): ForgotPasswordSearch => ({
|
||||
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
||||
email: typeof search.email === 'string' ? search.email : undefined,
|
||||
}),
|
||||
component: ForgotPasswordPage,
|
||||
})
|
||||
|
||||
const requestSchema = z.object({
|
||||
email: z.email('Introduce un correo electrónico válido'),
|
||||
})
|
||||
|
||||
const resetSchema = z
|
||||
.object({
|
||||
otp: z.string().regex(/^\d{6}$/, 'El código tiene 6 dígitos'),
|
||||
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((values) => values.password === values.confirmPassword, {
|
||||
message: 'Las contraseñas no coinciden',
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
|
||||
// BetterAuth answers in English; an unknown email reads like a wrong code so the
|
||||
// form doesn't reveal which addresses have an account.
|
||||
const resetErrorMessages: Record<string, string> = {
|
||||
INVALID_OTP: 'El código no es correcto.',
|
||||
USER_NOT_FOUND: 'El código no es correcto.',
|
||||
OTP_EXPIRED: 'El código venció. Pide uno nuevo.',
|
||||
TOO_MANY_ATTEMPTS: 'Demasiados intentos fallidos. Pide un código nuevo.',
|
||||
}
|
||||
|
||||
type RequestValues = z.infer<typeof requestSchema>
|
||||
type ResetValues = z.infer<typeof resetSchema>
|
||||
|
||||
function ForgotPasswordPage() {
|
||||
const { redirect, email: initialEmail } = Route.useSearch()
|
||||
const [email, setEmail] = useState<string | null>(null)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
|
||||
<AppBrand />
|
||||
<Card className="w-full max-w-sm">
|
||||
{email ? (
|
||||
<ResetPasswordStep
|
||||
email={email}
|
||||
redirect={redirect}
|
||||
onChangeEmail={() => setEmail(null)}
|
||||
/>
|
||||
) : (
|
||||
<RequestCodeStep
|
||||
defaultEmail={initialEmail ?? ''}
|
||||
redirect={redirect}
|
||||
onSent={setEmail}
|
||||
/>
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type RequestCodeStepProps = {
|
||||
defaultEmail: string
|
||||
redirect?: string
|
||||
onSent: (email: string) => void
|
||||
}
|
||||
|
||||
function RequestCodeStep({ defaultEmail, redirect, onSent }: RequestCodeStepProps) {
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const form = useForm<RequestValues>({
|
||||
resolver: zodResolver(requestSchema),
|
||||
defaultValues: { email: defaultEmail },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ email }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
|
||||
if (requestError) {
|
||||
setError(requestError.message ?? 'No pudimos enviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
onSent(email)
|
||||
})
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Recuperar contraseña</CardTitle>
|
||||
<CardDescription>Te enviaremos un código por correo para elegir una nueva.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos enviar el código</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.email}>
|
||||
<FieldLabel htmlFor="email">Correo electrónico</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="ada@ejemplo.com"
|
||||
{...form.register('email')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.email]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Enviando…' : 'Enviar código'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
type ResetPasswordStepProps = {
|
||||
email: string
|
||||
redirect?: string
|
||||
onChangeEmail: () => void
|
||||
}
|
||||
|
||||
function ResetPasswordStep({ email, redirect, onChangeEmail }: ResetPasswordStepProps) {
|
||||
const navigate = useNavigate()
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [resending, setResending] = useState(false)
|
||||
|
||||
const form = useForm<ResetValues>({
|
||||
resolver: zodResolver(resetSchema),
|
||||
defaultValues: { otp: '', password: '', confirmPassword: '' },
|
||||
})
|
||||
|
||||
const onSubmit = form.handleSubmit(async ({ otp, password }) => {
|
||||
setError(null)
|
||||
|
||||
const { error: resetError } = await emailOtp.resetPassword({ email, otp, password })
|
||||
|
||||
if (resetError) {
|
||||
setError(
|
||||
(resetError.code && resetErrorMessages[resetError.code]) ??
|
||||
resetError.message ??
|
||||
'No pudimos cambiar tu contraseña',
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Contraseña actualizada. Ya puedes iniciar sesión.')
|
||||
await navigate({ to: '/sign-in', search: redirect ? { redirect } : {} })
|
||||
})
|
||||
|
||||
const resend = async () => {
|
||||
setResending(true)
|
||||
const { error: requestError } = await emailOtp.requestPasswordReset({ email })
|
||||
setResending(false)
|
||||
|
||||
if (requestError) {
|
||||
toast.error(requestError.message ?? 'No pudimos reenviar el código')
|
||||
return
|
||||
}
|
||||
|
||||
toast.success('Te enviamos un código nuevo')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CardHeader>
|
||||
<CardTitle>Elige una nueva contraseña</CardTitle>
|
||||
<CardDescription>
|
||||
Si existe una cuenta con <span className="text-foreground font-medium">{email}</span>, te
|
||||
enviamos un código de 6 dígitos. Vence en 10 minutos.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTitle>No pudimos cambiar tu contraseña</AlertTitle>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FieldGroup>
|
||||
<Field data-invalid={!!form.formState.errors.otp}>
|
||||
<FieldLabel htmlFor="otp">Código</FieldLabel>
|
||||
<Input
|
||||
id="otp"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
placeholder="123456"
|
||||
className="font-mono tracking-widest"
|
||||
{...form.register('otp')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.otp]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<FieldLabel htmlFor="password">Nueva contraseña</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('password')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.password]} />
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.confirmPassword}>
|
||||
<FieldLabel htmlFor="confirmPassword">Repite la contraseña</FieldLabel>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...form.register('confirmPassword')}
|
||||
/>
|
||||
<FieldError errors={[form.formState.errors.confirmPassword]} />
|
||||
</Field>
|
||||
|
||||
<Button type="submit" disabled={form.formState.isSubmitting}>
|
||||
{form.formState.isSubmitting ? 'Guardando…' : 'Cambiar contraseña'}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<Button type="button" variant="link" className="h-auto p-0" onClick={onChangeEmail}>
|
||||
Usar otro correo
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto p-0"
|
||||
disabled={resending}
|
||||
onClick={resend}
|
||||
>
|
||||
{resending ? 'Reenviando…' : 'Reenviar código'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<BackToSignIn redirect={redirect} />
|
||||
</form>
|
||||
</CardContent>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function BackToSignIn({ redirect }: { redirect?: string }) {
|
||||
return (
|
||||
<p className="text-muted-foreground text-center text-sm">
|
||||
¿Recordaste tu contraseña?{' '}
|
||||
<Link
|
||||
to="/sign-in"
|
||||
search={redirect ? { redirect } : {}}
|
||||
className="text-foreground font-medium underline-offset-4 hover:underline"
|
||||
>
|
||||
Inicia sesión
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -85,7 +85,19 @@ function SignInPage() {
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!form.formState.errors.password}>
|
||||
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||
<div className="flex items-center justify-between">
|
||||
<FieldLabel htmlFor="password">Contraseña</FieldLabel>
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
search={() => {
|
||||
const email = form.getValues('email')
|
||||
return { redirect, email: email || undefined }
|
||||
}}
|
||||
className="text-muted-foreground text-sm underline-offset-4 hover:text-foreground hover:underline"
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</Link>
|
||||
</div>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
|
||||
Reference in New Issue
Block a user