GoTrue redirige con #error=...&error_code=... cuando el token de invitación/recovery ya fue usado o venció, en vez de emitir PASSWORD_RECOVERY. Antes esto se descubría recién a los 8s (timeout genérico); ahora se lee el fragmento al montar y se muestra un mensaje específico (otp_expired, access_denied, etc.) al instante. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
192 lines
6.8 KiB
TypeScript
192 lines
6.8 KiB
TypeScript
'use client'
|
|
|
|
import { useEffect, useState } from 'react'
|
|
import { createBrowserClient } from '@supabase/ssr'
|
|
import { useRouter } from 'next/navigation'
|
|
|
|
type Stage = 'validating' | 'ready' | 'submitting' | 'error'
|
|
|
|
const DEFAULT_LINK_ERROR = 'Pedile al administrador que te envíe una nueva invitación.'
|
|
|
|
// GoTrue redirige con #error=...&error_code=...&error_description=... cuando
|
|
// el token ya fue usado, venció, o es inválido — en vez de emitir PASSWORD_RECOVERY.
|
|
// Mapeo a mensajes accionables; default cubre códigos no contemplados acá.
|
|
function describeLinkError(errorCode: string | null): string {
|
|
switch (errorCode) {
|
|
case 'otp_expired':
|
|
return 'Este link ya fue usado o venció. ' + DEFAULT_LINK_ERROR
|
|
case 'access_denied':
|
|
return 'El acceso fue denegado para este link. ' + DEFAULT_LINK_ERROR
|
|
default:
|
|
return 'El link de invitación no es válido. ' + DEFAULT_LINK_ERROR
|
|
}
|
|
}
|
|
|
|
export default function ConfirmPage() {
|
|
const [stage, setStage] = useState<Stage>('validating')
|
|
const [error, setError] = useState<string | null>(null)
|
|
const [linkErrorMessage, setLinkErrorMessage] = useState(DEFAULT_LINK_ERROR)
|
|
const [showPassword, setShowPassword] = useState(false)
|
|
const router = useRouter()
|
|
|
|
const supabase = createBrowserClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
|
|
)
|
|
|
|
useEffect(() => {
|
|
// GoTrue ya nos dice en el fragmento si el token es inválido/vencido/usado
|
|
// (#error=...&error_code=...) — leerlo evita esperar el timeout genérico.
|
|
const hash = window.location.hash.startsWith('#')
|
|
? window.location.hash.slice(1)
|
|
: window.location.hash
|
|
const hashParams = new URLSearchParams(hash)
|
|
const errorCode = hashParams.get('error_code')
|
|
|
|
if (errorCode) {
|
|
setLinkErrorMessage(describeLinkError(errorCode))
|
|
setStage('error')
|
|
return
|
|
}
|
|
|
|
// Supabase emite PASSWORD_RECOVERY tanto para recovery como para invite
|
|
// cuando el token de la URL (#access_token) es válido.
|
|
const { data: listener } = supabase.auth.onAuthStateChange((event) => {
|
|
if (event === 'PASSWORD_RECOVERY') setStage('ready')
|
|
})
|
|
|
|
// Carrera posible: si el token ya se procesó antes de montar el listener,
|
|
// ya hay sesión activa aunque el evento no se vuelva a emitir.
|
|
supabase.auth.getSession().then(({ data: { session } }) => {
|
|
setStage((s) => (s === 'validating' && session ? 'ready' : s))
|
|
})
|
|
|
|
// Sin evento ni sesión tras unos segundos = token inválido/vencido/ausente
|
|
// sin que GoTrue haya mandado un error explícito en el fragmento.
|
|
const timeout = setTimeout(() => {
|
|
setStage((s) => (s === 'validating' ? 'error' : s))
|
|
}, 8000)
|
|
|
|
return () => {
|
|
listener.subscription.unsubscribe()
|
|
clearTimeout(timeout)
|
|
}
|
|
}, [supabase])
|
|
|
|
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
|
e.preventDefault()
|
|
const fd = new FormData(e.currentTarget)
|
|
const password = String(fd.get('password') ?? '')
|
|
const confirmPassword = String(fd.get('confirmPassword') ?? '')
|
|
|
|
if (password.length < 8) {
|
|
setError('La contraseña debe tener al menos 8 caracteres.')
|
|
return
|
|
}
|
|
if (password !== confirmPassword) {
|
|
setError('Las contraseñas no coinciden.')
|
|
return
|
|
}
|
|
|
|
setError(null)
|
|
setStage('submitting')
|
|
|
|
const { error: updateErr } = await supabase.auth.updateUser({ password })
|
|
|
|
if (updateErr) {
|
|
setError('No pudimos guardar tu contraseña. Probá de nuevo.')
|
|
setStage('ready')
|
|
return
|
|
}
|
|
|
|
router.push('/dashboard')
|
|
router.refresh()
|
|
}
|
|
|
|
if (stage === 'validating') {
|
|
return (
|
|
<div className="login-page">
|
|
<div className="login-card">
|
|
<h1 className="login-title">Validando tu invitación...</h1>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
if (stage === 'error') {
|
|
return (
|
|
<div className="login-page">
|
|
<div className="login-card">
|
|
<h1 className="login-title">Link inválido o vencido</h1>
|
|
<p role="alert" className="field-error login-error">
|
|
{linkErrorMessage}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="login-page">
|
|
<div className="login-card">
|
|
<h1 className="login-title">Creá tu contraseña</h1>
|
|
<form onSubmit={handleSubmit} className="login-form" noValidate>
|
|
<div className="login-field">
|
|
<label htmlFor="password" className="login-label">Contraseña</label>
|
|
<div className="login-password-wrapper">
|
|
<input
|
|
id="password"
|
|
name="password"
|
|
type={showPassword ? 'text' : 'password'}
|
|
autoComplete="new-password"
|
|
required
|
|
minLength={8}
|
|
disabled={stage === 'submitting'}
|
|
className="text-short-input"
|
|
/>
|
|
<button
|
|
type="button"
|
|
className="login-password-toggle"
|
|
onClick={() => setShowPassword((v) => !v)}
|
|
aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
|
|
>
|
|
{showPassword ? (
|
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
|
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" />
|
|
<circle cx="12" cy="12" r="3" />
|
|
</svg>
|
|
) : (
|
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
|
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" />
|
|
<circle cx="12" cy="12" r="3" />
|
|
<path d="M3 3l18 18" />
|
|
</svg>
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<div className="login-field">
|
|
<label htmlFor="confirmPassword" className="login-label">Confirmar contraseña</label>
|
|
<input
|
|
id="confirmPassword"
|
|
name="confirmPassword"
|
|
type={showPassword ? 'text' : 'password'}
|
|
autoComplete="new-password"
|
|
required
|
|
minLength={8}
|
|
disabled={stage === 'submitting'}
|
|
className="text-short-input"
|
|
/>
|
|
</div>
|
|
{error && (
|
|
<p role="alert" className="field-error login-error">{error}</p>
|
|
)}
|
|
<button type="submit" disabled={stage === 'submitting'} className="login-submit">
|
|
{stage === 'submitting' ? 'Guardando…' : 'Crear contraseña'}
|
|
</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|