Sign in with Face ID, Touch ID, Windows Hello or a security key, keeping email + password as the primary method. - API: BetterAuth passkey plugin deriving rpID/origin from WEB_APP_URL (the browser origin), with residentKey "required" because sign-in is username-less. New Passkey model mapped to the passkeys table. - Web: conditional UI in the email field plus an explicit "Entrar con passkey" button; cancelled ceremonies are ignored. - Settings: create, rename and delete passkeys with TanStack Query. - Pin @better-auth/passkey to 1.7.7: its peers lock better-call, so newer versions break the API.
224 lines
7.6 KiB
TypeScript
224 lines
7.6 KiB
TypeScript
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
|
|
import { FingerprintIcon } from 'lucide-react'
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import { useForm } from 'react-hook-form'
|
|
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 { authClient, signIn } from '@/lib/auth-client'
|
|
|
|
export const Route = createFileRoute('/(auth)/sign-in')({
|
|
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
|
|
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
|
|
}),
|
|
component: SignInPage,
|
|
})
|
|
|
|
const signInSchema = z.object({
|
|
email: z.email('Introduce un correo electrónico válido'),
|
|
password: z.string().min(8, 'La contraseña debe tener al menos 8 caracteres'),
|
|
})
|
|
|
|
type SignInValues = z.infer<typeof signInSchema>
|
|
|
|
const PASSKEY_ERROR_MESSAGE = 'No pudimos iniciar tu sesión con passkey.'
|
|
|
|
/** The user dismissed the system sheet: not worth showing an error for. */
|
|
function isPasskeyCancellation(error: unknown) {
|
|
return (
|
|
typeof error === 'object' &&
|
|
error !== null &&
|
|
'code' in error &&
|
|
error.code === 'AUTH_CANCELLED'
|
|
)
|
|
}
|
|
|
|
function SignInPage() {
|
|
const navigate = useNavigate()
|
|
const { redirect } = Route.useSearch()
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [passkeyPending, setPasskeyPending] = useState(false)
|
|
const conditionalUiStarted = useRef(false)
|
|
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
|
|
|
|
const form = useForm<SignInValues>({
|
|
resolver: zodResolver(signInSchema),
|
|
defaultValues: { email: '', password: '' },
|
|
})
|
|
|
|
const completeSignIn = useCallback(async () => {
|
|
if (redirect) {
|
|
window.location.assign(redirect)
|
|
return
|
|
}
|
|
|
|
await navigate({ to: '/' })
|
|
}, [navigate, redirect])
|
|
|
|
// Conditional UI: the browser offers the user's passkeys in the email field's
|
|
// autofill. Guarded with a ref because StrictMode mounts effects twice in dev
|
|
// and a second ceremony would abort the first one.
|
|
useEffect(() => {
|
|
if (conditionalUiStarted.current || !supportsPasskeys) return
|
|
if (typeof window.PublicKeyCredential.isConditionalMediationAvailable !== 'function') return
|
|
|
|
conditionalUiStarted.current = true
|
|
|
|
void (async () => {
|
|
if (!(await window.PublicKeyCredential.isConditionalMediationAvailable())) return
|
|
|
|
try {
|
|
const { error: passkeyError } = await authClient.signIn.passkey({ autoFill: true })
|
|
|
|
if (passkeyError) {
|
|
if (!isPasskeyCancellation(passkeyError)) {
|
|
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
|
}
|
|
return
|
|
}
|
|
|
|
await completeSignIn()
|
|
} catch {
|
|
setError(PASSKEY_ERROR_MESSAGE)
|
|
}
|
|
})()
|
|
}, [completeSignIn, supportsPasskeys])
|
|
|
|
const onSubmit = form.handleSubmit(async (values) => {
|
|
setError(null)
|
|
|
|
const { error: signInError } = await signIn.email(values)
|
|
|
|
if (signInError) {
|
|
setError(signInError.message ?? 'No pudimos iniciar tu sesión')
|
|
return
|
|
}
|
|
|
|
await completeSignIn()
|
|
})
|
|
|
|
const onPasskeySignIn = async () => {
|
|
setError(null)
|
|
setPasskeyPending(true)
|
|
|
|
try {
|
|
const { error: passkeyError } = await authClient.signIn.passkey()
|
|
|
|
if (passkeyError) {
|
|
if (!isPasskeyCancellation(passkeyError)) {
|
|
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
|
|
}
|
|
return
|
|
}
|
|
|
|
await completeSignIn()
|
|
} catch {
|
|
setError(PASSKEY_ERROR_MESSAGE)
|
|
} finally {
|
|
setPasskeyPending(false)
|
|
}
|
|
}
|
|
|
|
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">
|
|
<CardHeader>
|
|
<CardTitle>Iniciar sesión</CardTitle>
|
|
<CardDescription>Usa tu cuenta de Superlist para continuar.</CardDescription>
|
|
</CardHeader>
|
|
<CardContent>
|
|
<form onSubmit={onSubmit} className="flex flex-col gap-6">
|
|
{error && (
|
|
<Alert variant="destructive">
|
|
<AlertTitle>No pudimos iniciar tu sesión</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"
|
|
// `webauthn` lets the browser offer passkeys in autofill
|
|
// (conditional UI); `username` is what login forms use.
|
|
autoComplete="username webauthn"
|
|
placeholder="ada@ejemplo.com"
|
|
{...form.register('email')}
|
|
/>
|
|
<FieldError errors={[form.formState.errors.email]} />
|
|
</Field>
|
|
|
|
<Field data-invalid={!!form.formState.errors.password}>
|
|
<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"
|
|
autoComplete="current-password"
|
|
{...form.register('password')}
|
|
/>
|
|
<FieldError errors={[form.formState.errors.password]} />
|
|
</Field>
|
|
|
|
<Button type="submit" disabled={form.formState.isSubmitting || passkeyPending}>
|
|
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
|
|
</Button>
|
|
</FieldGroup>
|
|
|
|
{supportsPasskeys && (
|
|
<>
|
|
<div className="flex items-center gap-3" aria-hidden>
|
|
<span className="bg-border h-px flex-1" />
|
|
<span className="text-muted-foreground text-xs uppercase">o</span>
|
|
<span className="bg-border h-px flex-1" />
|
|
</div>
|
|
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={onPasskeySignIn}
|
|
disabled={passkeyPending || form.formState.isSubmitting}
|
|
>
|
|
<FingerprintIcon />
|
|
{passkeyPending ? 'Esperando a tu passkey…' : 'Entrar con passkey'}
|
|
</Button>
|
|
</>
|
|
)}
|
|
|
|
<p className="text-muted-foreground text-center text-sm">
|
|
¿Todavía no tienes cuenta?{' '}
|
|
<Link
|
|
to="/sign-up"
|
|
search={redirect ? { redirect } : {}}
|
|
className="text-foreground font-medium underline-offset-4 hover:underline"
|
|
>
|
|
Crea una
|
|
</Link>
|
|
</p>
|
|
</form>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
)
|
|
}
|