diff --git a/susconecta/app/(auth)/login-admin/page-new.tsx b/susconecta/app/(auth)/login-admin/page-new.tsx new file mode 100644 index 0000000..6327e34 --- /dev/null +++ b/susconecta/app/(auth)/login-admin/page-new.tsx @@ -0,0 +1,17 @@ +'use client' +import { useEffect } from 'react' +import { useRouter } from 'next/navigation' + +export default function LoginAdminRedirect() { + const router = useRouter() + + useEffect(() => { + router.replace('/login') + }, [router]) + + return ( +
+

Redirecionando para a página de login...

+
+ ) +} diff --git a/susconecta/app/(auth)/login-admin/page.tsx b/susconecta/app/(auth)/login-admin/page.tsx index 03260c8..571ee04 100644 --- a/susconecta/app/(auth)/login-admin/page.tsx +++ b/susconecta/app/(auth)/login-admin/page.tsx @@ -1,128 +1,17 @@ 'use client' -import { useState } from 'react' +import { useEffect } from 'react' import { useRouter } from 'next/navigation' -import Link from 'next/link' -import { useAuth } from '@/hooks/useAuth' -import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' -import { Alert, AlertDescription } from '@/components/ui/alert' -import { AuthenticationError } from '@/lib/auth' -export default function LoginAdminPage() { - const [credentials, setCredentials] = useState({ email: '', password: '' }) - const [error, setError] = useState('') - - const [loading, setLoading] = useState(false) +export default function LoginAdminRedirect() { const router = useRouter() - const { login } = useAuth() - const handleLogin = async (e: React.FormEvent) => { - e.preventDefault() - setLoading(true) - setError('') - - try { - // Tentar fazer login usando o contexto com tipo administrador - const success = await login(credentials.email, credentials.password, 'administrador') - - if (success) { - console.log('[LOGIN-ADMIN] Login bem-sucedido, redirecionando...') - - // Redirecionamento direto - solução que funcionou - window.location.href = '/dashboard' - } - } catch (err) { - console.error('[LOGIN-ADMIN] Erro no login:', err) - - if (err instanceof AuthenticationError) { - setError(err.message) - } else { - setError('Erro inesperado. Tente novamente.') - } - } finally { - setLoading(false) - } - } - - + useEffect(() => { + router.replace('/login') + }, [router]) return ( -
-
-
-

- Login Administrador de Clínica -

-

- Entre com suas credenciais para acessar o sistema administrativo -

-
- - - - Acesso Administrativo - - -
-
- - setCredentials({...credentials, email: e.target.value})} - required - className="mt-1" - disabled={loading} - /> -
- -
- - setCredentials({...credentials, password: e.target.value})} - required - className="mt-1" - disabled={loading} - /> -
- - {error && ( - - {error} - - )} - - -
- - -
- -
-
-
-
+
+

Redirecionando para a página de login...

) } \ No newline at end of file diff --git a/susconecta/app/(auth)/login-paciente/page.tsx b/susconecta/app/(auth)/login-paciente/page.tsx index 0927014..18c43bf 100644 --- a/susconecta/app/(auth)/login-paciente/page.tsx +++ b/susconecta/app/(auth)/login-paciente/page.tsx @@ -1,138 +1,17 @@ 'use client' -import { useState } from 'react' +import { useEffect } from 'react' import { useRouter } from 'next/navigation' -import Link from 'next/link' -import { useAuth } from '@/hooks/useAuth' -import { Button } from '@/components/ui/button' -import { Input } from '@/components/ui/input' -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' -import { Alert, AlertDescription } from '@/components/ui/alert' -import { AuthenticationError } from '@/lib/auth' -export default function LoginPacientePage() { - const [credentials, setCredentials] = useState({ email: '', password: '' }) - const [error, setError] = useState('') - - const [loading, setLoading] = useState(false) +export default function LoginPacienteRedirect() { const router = useRouter() - const { login } = useAuth() - const handleLogin = async (e: React.FormEvent) => { - e.preventDefault() - setLoading(true) - setError('') - - try { - // Tentar fazer login usando o contexto com tipo paciente - const success = await login(credentials.email, credentials.password, 'paciente') - - if (success) { - // Redirecionar para a página do paciente - router.push('/paciente') - } - } catch (err) { - console.error('[LOGIN-PACIENTE] Erro no login:', err) - - if (err instanceof AuthenticationError) { - // Verificar se é erro de credenciais inválidas (pode ser email não confirmado) - if (err.code === '400' || err.details?.error_code === 'invalid_credentials') { - setError( - '⚠️ Email ou senha incorretos. Se você acabou de se cadastrar, ' + - 'verifique sua caixa de entrada e clique no link de confirmação ' + - 'que foi enviado para ' + credentials.email - ) - } else { - setError(err.message) - } - } else { - setError('Erro inesperado. Tente novamente.') - } - } finally { - setLoading(false) - } - } - - - - // Auto-cadastro foi removido (UI + client-side endpoint call) + useEffect(() => { + router.replace('/login') + }, [router]) return ( -
-
-
-

- Sou Paciente -

-

- Acesse sua área pessoal e gerencie suas consultas -

-
- - - - Entrar como Paciente - - -
-
- - setCredentials({...credentials, email: e.target.value})} - required - className="mt-1" - disabled={loading} - /> -
- -
- - setCredentials({...credentials, password: e.target.value})} - required - className="mt-1" - disabled={loading} - /> -
- - {error && ( - - {error} - - )} - - -
- - -
- -
- {/* Auto-cadastro UI removed */} -
-
-
+
+

Redirecionando...

) } \ No newline at end of file diff --git a/susconecta/app/(auth)/login-profissional/page.tsx b/susconecta/app/(auth)/login-profissional/page.tsx new file mode 100644 index 0000000..5a42390 --- /dev/null +++ b/susconecta/app/(auth)/login-profissional/page.tsx @@ -0,0 +1,17 @@ +'use client' +import { useEffect } from 'react' +import { useRouter } from 'next/navigation' + +export default function LoginProfissionalRedirect() { + const router = useRouter() + + useEffect(() => { + router.replace('/login') + }, [router]) + + return ( +
+

Redirecionando para a página de login...

+
+ ) +} diff --git a/susconecta/app/(auth)/login/page.tsx b/susconecta/app/(auth)/login/page.tsx index 2a55ba9..0fd6d34 100644 --- a/susconecta/app/(auth)/login/page.tsx +++ b/susconecta/app/(auth)/login/page.tsx @@ -12,10 +12,23 @@ import { AuthenticationError } from '@/lib/auth' export default function LoginPage() { const [credentials, setCredentials] = useState({ email: '', password: '' }) const [error, setError] = useState('') - const [loading, setLoading] = useState(false) const router = useRouter() - const { login } = useAuth() + const { login, user } = useAuth() + + // Mapeamento de redirecionamento baseado em role + const getRoleRedirectPath = (userType: string): string => { + switch (userType) { + case 'paciente': + return '/paciente' + case 'profissional': + return '/profissional' + case 'administrador': + return '/dashboard' + default: + return '/' + } + } const handleLogin = async (e: React.FormEvent) => { e.preventDefault() @@ -23,32 +36,73 @@ export default function LoginPage() { setError('') try { - // Tentar fazer login usando o contexto com tipo profissional - const success = await login(credentials.email, credentials.password, 'profissional') + // Tentar fazer login com cada tipo de usuário até conseguir + // Ordem de prioridade: profissional (inclui médico), paciente, administrador + const userTypes: Array<'paciente' | 'profissional' | 'administrador'> = [ + 'profissional', // Tentar profissional PRIMEIRO pois inclui médicos + 'paciente', + 'administrador' + ] + + let lastError: AuthenticationError | Error | null = null + let loginAttempted = false + + for (const userType of userTypes) { + try { + console.log(`[LOGIN] Tentando login como ${userType}...`) + const loginSuccess = await login(credentials.email, credentials.password, userType) + + if (loginSuccess) { + loginAttempted = true + console.log('[LOGIN] Login bem-sucedido como', userType) + console.log('[LOGIN] User state:', user) + + // Aguardar um pouco para o state do usuário ser atualizado + await new Promise(resolve => setTimeout(resolve, 500)) + + // Obter o userType atualizado do localStorage (que foi salvo pela função login) + const storedUser = localStorage.getItem('auth_user') + if (storedUser) { + try { + const userData = JSON.parse(storedUser) + const redirectPath = getRoleRedirectPath(userData.userType) + console.log('[LOGIN] Redirecionando para:', redirectPath) + router.push(redirectPath) + } catch (parseErr) { + console.error('[LOGIN] Erro ao parsear user do localStorage:', parseErr) + router.push('/') + } + } else { + console.warn('[LOGIN] Usuário não encontrado no localStorage') + router.push('/') + } + return + } + } catch (err) { + lastError = err as AuthenticationError | Error + const errorMsg = err instanceof Error ? err.message : String(err) + console.log(`[LOGIN] Falha ao tentar como ${userType}:`, errorMsg) + continue + } + } + + // Se chegou aqui, nenhum tipo funcionou + console.error('[LOGIN] Nenhum tipo de usuário funcionou. Erro final:', lastError) - if (success) { - console.log('[LOGIN-PROFISSIONAL] Login bem-sucedido, redirecionando...') - - // Redirecionamento direto - solução que funcionou - window.location.href = '/profissional' + if (lastError instanceof AuthenticationError) { + const errorMsg = lastError.message || lastError.details?.error_code || '' + if (lastError.code === '400' || errorMsg.includes('invalid_credentials') || errorMsg.includes('Email or password')) { + setError('❌ Email ou senha incorretos. Verifique suas credenciais.') + } else { + setError(lastError.message || 'Erro ao fazer login. Tente novamente.') + } + } else if (lastError instanceof Error) { + setError(lastError.message || 'Erro desconhecido ao fazer login.') + } else { + setError('Falha ao fazer login. Credenciais inválidas ou conta não encontrada.') } } catch (err) { - console.error('[LOGIN-PROFISSIONAL] Erro no login:', err) - - if (err instanceof AuthenticationError) { - // Verificar se é erro de credenciais inválidas (pode ser email não confirmado) - if (err.code === '400' || err.details?.error_code === 'invalid_credentials') { - setError( - '⚠️ Email ou senha incorretos. Se você acabou de se cadastrar, ' + - 'verifique sua caixa de entrada e clique no link de confirmação ' + - 'que foi enviado para ' + credentials.email - ) - } else { - setError(err.message) - } - } else { - setError('Erro inesperado. Tente novamente.') - } + console.error('[LOGIN] Erro no login:', err) } finally { setLoading(false) } @@ -61,7 +115,7 @@ export default function LoginPage() {

- Login Profissional de Saúde + Entrar

Entre com suas credenciais para acessar o sistema @@ -70,7 +124,7 @@ export default function LoginPage() { - Acesso ao Sistema + Login

@@ -121,9 +175,8 @@ export default function LoginPage() {
-
-