Files
sgse-app/FASE1_COMPLETA.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.6 KiB

FASE 1 COMPLETA: Configurar Auth Provider no Convex

🎯 Objetivo

Configurar Custom Auth Provider no Convex que funciona com o sistema atual (tokens customizados) e prepara para Better Auth.

O que foi implementado:

1. packages/backend/convex/convex.config.ts

  • Adicionado Custom Auth Provider
  • getToken() - Extrai token do header Authorization: Bearer <token>
  • getIdentity() - Valida token buscando sessão na tabela sessoes
  • Retorna identity formatada compatível com Better Auth
  • Valida expiração e status ativo

2. packages/backend/convex/chat.ts

  • Atualizado getUsuarioAutenticado() para usar Custom Auth Provider
  • Adicionado logs de debug em desenvolvimento
  • Mantida compatibilidade com sistema atual

3. packages/backend/convex/usuarios.ts

  • Atualizado getUsuarioAutenticado() para usar Custom Auth Provider
  • Mantida compatibilidade

🔍 Como funciona agora:

  1. Frontend envia token: ConvexHttpClient.setAuth(token) → header Authorization: Bearer <token>

  2. Convex recebe: O Custom Auth Provider extrai o token do header

  3. Provider valida:

    • Busca sessão na tabela sessoes por token
    • Verifica se está ativa e não expirada
    • Busca usuário e retorna identity
  4. Backend usa: ctx.auth.getUserIdentity() agora retorna identity válida!

Garantias de segurança:

  • Busca sessão por token específico (não mais recente)
  • Valida expiração do token
  • Verifica se usuário está ativo
  • Retorna null se token inválido (não assume usuário errado)

🧪 Como testar:

  1. Iniciar backend:

    cd packages/backend
    npm run dev
    
  2. Fazer login no sistema (como sempre)

  3. Verificar logs:

    • Deve aparecer: ✅ [getUsuarioAutenticado] Usuário identificado via Custom Auth Provider
    • Enviar mensagem no chat deve funcionar
    • Ver perfil deve funcionar
  4. Testar mutations críticas:

    • Enviar mensagem no chat
    • Ver perfil do usuário
    • Criar conversa
    • Qualquer mutation que use getUsuarioAutenticado()

⚠️ Se algo der errado:

Rollback rápido: Comentar o bloco auth: { ... } no convex.config.ts:

const app = defineApp();
// auth: { ... } // Comentado temporariamente

📝 Próximos passos (Fase 2):

  • Configurar Better Auth no frontend para funcionar junto
  • Migrar login gradualmente
  • Adicionar suporte a tokens Better Auth no provider

Status: FASE 1 COMPLETA

O sistema atual deve funcionar normalmente, mas agora com ctx.auth.getUserIdentity() funcionando corretamente!