74 lines
2.8 KiB
TypeScript
74 lines
2.8 KiB
TypeScript
"use client"
|
|
import { useEffect, useState } from 'react'
|
|
import { useRouter } from 'next/navigation'
|
|
import { getCurrentUser, AuthenticationError } from '@/lib/auth'
|
|
import { AUTH_STORAGE_KEYS, USER_TYPE_ROUTES } from '@/types/auth'
|
|
|
|
function parseHashOrQuery() {
|
|
// Try fragment first (#access_token=...&refresh_token=...)
|
|
const hash = typeof window !== 'undefined' ? window.location.hash.replace(/^#/, '') : ''
|
|
const query = typeof window !== 'undefined' ? window.location.search.replace(/^\?/, '') : ''
|
|
|
|
const params = new URLSearchParams(hash || query)
|
|
const access_token = params.get('access_token')
|
|
const refresh_token = params.get('refresh_token')
|
|
const expires_in = params.get('expires_in')
|
|
return { access_token, refresh_token, expires_in }
|
|
}
|
|
|
|
export default function AuthCallbackPage() {
|
|
const router = useRouter()
|
|
const [message, setMessage] = useState('Processando autenticação...')
|
|
|
|
useEffect(() => {
|
|
async function run() {
|
|
try {
|
|
const { access_token, refresh_token } = parseHashOrQuery()
|
|
if (!access_token) {
|
|
setMessage('Não foi possível detectar o token de acesso. Verifique o link enviado por email.');
|
|
return
|
|
}
|
|
|
|
setMessage('Validando token e obtendo dados do usuário...')
|
|
|
|
// Buscar dados do usuário com o token recebido
|
|
const user = await getCurrentUser(access_token)
|
|
|
|
// Persistir no localStorage com as chaves esperadas
|
|
if (typeof window !== 'undefined') {
|
|
localStorage.setItem(AUTH_STORAGE_KEYS.TOKEN, access_token)
|
|
if (refresh_token) localStorage.setItem(AUTH_STORAGE_KEYS.REFRESH_TOKEN, refresh_token)
|
|
try { localStorage.setItem(AUTH_STORAGE_KEYS.USER, JSON.stringify(user)) } catch {}
|
|
try { localStorage.setItem(AUTH_STORAGE_KEYS.USER_TYPE, user.userType || 'paciente') } catch {}
|
|
}
|
|
|
|
setMessage('Autenticação concluída! Redirecionando...')
|
|
|
|
// Determinar rota com base no tipo do usuário
|
|
const target = (user?.userType && USER_TYPE_ROUTES[user.userType]) || '/paciente'
|
|
|
|
// Pequeno delay para UX
|
|
setTimeout(() => router.replace(target), 600)
|
|
} catch (err) {
|
|
console.error('[AUTH CALLBACK] Erro ao processar callback:', err)
|
|
if (err instanceof AuthenticationError) {
|
|
setMessage(err.message)
|
|
} else {
|
|
setMessage('Erro ao processar o link de autenticação. Tente novamente.')
|
|
}
|
|
}
|
|
}
|
|
|
|
run()
|
|
}, [router])
|
|
|
|
return (
|
|
<div className="min-h-screen flex items-center justify-center bg-background px-4">
|
|
<div className="max-w-lg w-full text-center">
|
|
<h2 className="text-2xl font-semibold mb-4">Autenticando...</h2>
|
|
<p className="text-sm text-muted-foreground">{message}</p>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|