Skip to content

Implementa autenticação social via Google OAuth2 no fluxo de login da plataforma. - #470

Open
RafaelFantinel wants to merge 11 commits into
developfrom
feature/google-login
Open

Implementa autenticação social via Google OAuth2 no fluxo de login da plataforma.#470
RafaelFantinel wants to merge 11 commits into
developfrom
feature/google-login

Conversation

@RafaelFantinel

Copy link
Copy Markdown
Contributor

Descrição

Implementa autenticação social via Google OAuth2 no fluxo de login da plataforma.

O que foi feito

  • Google Strategy (passport-google-oauth20): valida o token e retorna dados do perfil (id,
    email, nome)
  • GoogleAuthGuard: guard Passport para proteger as rotas OAuth
  • Novos endpoints:
    • GET /user/auth/google/callback — callback do Google, redireciona com JWT
    • PATCH /user/complete-profile — completa dados obrigatórios para usuários novos via Google
  • Migração de banco (1778250000000-google-social-login):
    • Adiciona coluna google_id (unique) na tabela users
    • Adiciona coluna profile_complete (nullable)
    • Torna opcionais as colunas password, phone, gender, birthday, state, city
  • Lógica de callback:
    • Usuário existente com mesmo e-mail: vincula googleId e autentica
    • Usuário novo: cria conta com perfil incompleto e redireciona para /onboarding
    • Perfil incompleto → redireciona com token para /onboarding?token=...
    • Perfil completo → redireciona para /auth/callback?token=...
    • Falha no OAuth → redireciona para /login?error=oauth_failed

Variáveis de ambiente necessárias

GOOGLE_CLIENT_ID=                                                                                 
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL= 
CLIENT_URL=         

Como testar

  1. Configurar credenciais Google OAuth no .env
  2. Rodar a migração: yarn migration:run
  3. Acessar GET /user/auth/google — deve redirecionar para tela de login do Google
  4. Após autenticar, verificar redirecionamento correto:
    - Usuário novo → /onboarding?token=...
    - Usuário existente com perfil completo → /auth/callback?token=...
  5. Para usuário novo, chamar PATCH /user/complete-profile com os dados obrigatórios e verificar
    que retorna novo JWT

FernandoAlmeidaPinto and others added 2 commits April 15, 2026 23:33
Adiciona autenticação via Google OAuth2: strategy Passport, guard, migração para colunas googleId/socialLogin na entidade User, endpoint de callback e fluxo de completar perfil para usuários novos.

Co-Authored-By: Rafael Fantinel <rafaeldeoliveirafantinel@hotmail.com>

@FernandoAlmeidaPinto FernandoAlmeidaPinto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review — Login Social com Google

Review automatizado focado nos arquivos alterados pela branch feature/google-login.

Resumo: 4 críticos · 4 altos · 10 médios · 4 baixos

Sev Quantidade Comportamento
Crítico 4 requer alteração antes do merge
Alto 4 recomendado tratar antes do merge
Médio 10 revisar caso a caso
Baixo 4 nitpick / cleanup

Ver comentários inline em cada finding. Pontos sistêmicos sem linha específica:

[ALTA] Sem cobertura de testes e2e

Não há test/google-oauth.e2e-spec.ts nessa branch (uma versão anterior em feat/google-social-login-v2 continha 12 testes cobrindo: novo user, link existente, login bloqueado, complete-profile happy path, 403 e 400). Reintroduzir.

[MÉDIA] JWT em query string (callbacks)

Linhas ?token=${access_token} em redirects expõem JWT em logs de servidor (Nginx, CDN), referer headers e histórico do browser. Padrão mais seguro: setar httpOnly cookie no callback (consistente com refresh token já existente) e redirecionar sem token na URL.

[MÉDIA] User.password agora nullable — auditar consumidores

Mudança password: string | null afeta chamadores. Auditar:

  • user.repository.ts (queries com password)
  • handlers de reset/forgot que assumem password não-null
  • DTOs de output que possam vazar password
    Revisar mesmo phone, gender, birthday, state, city.

[BAIXA] LGPD não consentida entre Google login e onboarding

No fluxo Google → callback → onboarding, usuário é persistido com lgpd: false antes de aceitar termos. Se fechar navegador no meio, conta fica criada sem aceite. Considerar não persistir até completar onboarding (sessão temp via Redis) ou exibir aceite junto do botão Google.


Review baseado em origin/develop...HEAD apenas.

Comment thread src/modules/user/user.service.ts Outdated
Comment thread src/db/migrations/1778250000000-google-social-login.ts
Comment thread .env.example Outdated
Comment thread src/shared/modules/env/env.ts Outdated
Comment thread src/modules/user/strategy/google.strategy.ts Outdated
Comment thread src/modules/user/dto/complete-profile.dto.ts
Comment thread src/modules/user/dto/user.dto.output.ts
Comment thread src/modules/user/strategy/google.strategy.ts Outdated
Comment thread .env.example Outdated
Comment thread src/modules/user/guards/google-auth.guard.ts
RafaelFantinel and others added 9 commits May 12, 2026 20:54
- Validate that email exists and is verified in GoogleStrategy before
  allowing OAuth flow to proceed
- Guard against undefined email at start of handleGoogleCallback
- Only auto-link Google account to existing local account when local
  email is already confirmed (emailConfirmSended === null), preventing
  account takeover via unconfirmed email
- Remove emailConfirmSended clearing on auto-link (it was already null)
- Remove monolithic try/catch that swallowed DB and internal errors;
  let unexpected errors propagate to the global exception filter
- Use URL constructor for redirect URLs to handle special characters
- Fix profileComplete to be true for legacy users (null -> true) so
  JWT payload is semantically correct
- Fix role-not-found to return 500 instead of 400 (config error)
- Replace auth-method-revealing 401 message with generic 'invalid credentials'
- Add @equals(true) to lgpd field so backend rejects false explicitly,
  preventing a client from bypassing LGPD acceptance
- Add @maxlength(255) to phone, state and city to match varchar(255)
  column length and return 400 instead of 500 on oversized input
Add backfill updates before each MODIFY ... NOT NULL so rollback does
not fail on rows created via Google OAuth (which have null password,
phone, etc.). Also delete Google-only users before dropping google_id
since those rows cannot satisfy the restored NOT NULL constraints.
Controller is @controller('user'), so the real path is
/user/auth/google/callback. Without the prefix the Google redirect
hits 404. Also change GOOGLE_CLIENT_ID/SECRET default from empty string
to 'dev-disabled' so passport-google-oauth20 does not throw at boot
when env vars are not set in CI or local dev environments.
- Add @apioperation to /auth/google and /complete-profile
- Add @ApiExcludeEndpoint to /auth/google/callback (not called directly)
- Remove @httpcode(200) from googleAuth (ignored; guard issues 302)
- Add @Injectable() to GoogleAuthGuard following project convention
Adds missing type declarations that were declared in package.json but
not present in node_modules, causing TypeScript compilation to fail.
…le callback

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants