Files
sgse-app/CORRECAO_AUTENTICACAO.md
deyvisonwanderley 06f03b53e5 feat: integrate Better Auth and enhance authentication flow
- Added Better Auth integration to the web application, allowing for dual login support with both custom and Better Auth systems.
- Updated authentication client configuration to dynamically set the base URL based on the environment.
- Enhanced chat components to utilize user authentication status, improving user experience and security.
- Refactored various components to support Better Auth, including error handling and user identity management.
- Improved notification handling and user feedback mechanisms during authentication processes.
2025-11-06 09:35:36 -03:00

2.2 KiB

🔧 Correção Crítica: Autenticação no Chat

🐛 Problema Identificado

Erros no console:

  • [getUsuarioAutenticado] Usuário não autenticado - Better Auth não configurado ou token inválido
  • Uncaught Error: Não autenticado at handler (../convex/chat.ts:757:14)
  • Chat não abre conversas (tela branca)

Causa Raiz: Token não está sendo passado nas requisições Convex do convex-svelte

Correções Aplicadas

1. apps/web/src/routes/+layout.svelte

  • Monkey patch no ConvexHttpClient.prototype para adicionar token automaticamente
  • Token é injetado em todas chamadas mutation() e query()

2. apps/web/src/lib/components/chat/PresenceManager.svelte

  • Configuração manual do token no onMount
  • Garante que atualizarStatusPresenca tenha token

3. apps/web/src/lib/components/chat/ChatWindow.svelte

  • Configuração manual do token no cliente
  • Garante que queries de conversas funcionem

4. Backend (packages/backend/convex/convex.config.ts)

  • Custom Auth Provider já configurado com logs extensivos
  • Busca sessão por token específico (seguro)

🧪 Como Testar

  1. Limpar cache do navegador (importante!)
  2. Fazer login novamente
  3. Abrir console do navegador e verificar:
    • Não deve aparecer mais "Não autenticado"
    • Deve aparecer logs do Custom Auth Provider no backend
  4. Testar chat:
    • Abrir conversa
    • Verificar se mensagens carregam
    • Enviar mensagem

🔍 Verificar Logs do Backend

No terminal do Convex, deve aparecer:

  • 🔍 [Custom Auth] Headers recebidos: - Se token está chegando
  • ✅ [Custom Auth] Token extraído: - Se token foi encontrado
  • ✅ [Custom Auth] Identity criada: - Se usuário foi identificado

⚠️ Se Ainda Não Funcionar

  1. Verificar se token está no authStore: console.log(authStore.token)
  2. Verificar logs do backend Convex para ver qual etapa está falhando
  3. Verificar se sessão ainda está ativa no banco

📝 Arquivos Modificados

  • apps/web/src/routes/+layout.svelte
  • apps/web/src/lib/components/chat/PresenceManager.svelte
  • apps/web/src/lib/components/chat/ChatWindow.svelte
  • Backend já estava correto desde Fase 1