feat(admin): onboarding por invitación — /admin/usuarios + /auth/confirm
Platform admin invita usuarios de empresa desde /admin/usuarios. inviteUserByEmail + insert inmediato en user_roles (org_admin). Rollback explícito si falla el insert. /auth/confirm maneja el link de invitación con PASSWORD_RECOVERY event. Middleware no requirió cambios — /auth/confirm ya queda fuera del matcher de rutas protegidas. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
159
app/auth/confirm/page.tsx
Normal file
159
app/auth/confirm/page.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { createBrowserClient } from '@supabase/ssr'
|
||||
import { useRouter } from 'next/navigation'
|
||||
|
||||
type Stage = 'validating' | 'ready' | 'submitting' | 'error'
|
||||
|
||||
export default function ConfirmPage() {
|
||||
const [stage, setStage] = useState<Stage>('validating')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
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(() => {
|
||||
// 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.
|
||||
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">
|
||||
Pedile al administrador que te envíe una nueva invitación.
|
||||
</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>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user