Skip to content
This repository was archived by the owner on Feb 12, 2026. It is now read-only.

chore: created OAUTH_SUCCESS_REDIRECT_URL for the FrontEnd URL - #38

Open
cleberjamaral wants to merge 1 commit into
developfrom
chore/oath-redirect-url
Open

cleberjamaral wants to merge 1 commit into
developfrom
chore/oath-redirect-url

Conversation

@cleberjamaral

@cleberjamaral cleberjamaral commented Dec 16, 2025 •

Copy link
Copy Markdown
Contributor

Descrição

Cria variavel de ambiente para indicar a URL (geralmente do FrontEnd) a qual o google/callback deve redirecionar após a autenticação bem sucedida.

Creio que manter o endpoint google/callback é uma boa prática, pois facilita indicar uma URL que fallback e deixa o endereço de retorno fixo para agentes externos, sendo que o redirecionamento a um endereço variável fica no caso em uma varenv.

Tipos de Mudanças

  • fix: correção de bug
  • feat: nova funcionalidade
  • docs: mudanças na documentação
  • chore: mudanças no processo de build ou ferramentas auxiliares
  • refactor: refatoração de código existente
  • test: adição ou modificação de testes
  • perf: melhorias de performance
  • ci: mudanças em arquivos de configuração de CI/CD

Como o teste foi realizado?

  • Testes unitários (sucesso e falha)
  • Teste em máquina local
  • Teste em ambiente de homologação
  • Teste em ambiente de produção

Checklist:

  • Meu código segue as diretrizes de estilo deste projeto
  • Eu realizei uma autoavaliação do meu próprio código
  • Eu comentei meu código, especialmente em áreas de difícil compreensão
  • Eu adicionei documentação conforme necessário
  • Minhas mudanças não geram novos avisos de compilação (warnings)
  • Eu adicionei testes para cobrir minhas mudanças
  • Todos os testes novos e existentes passam localmente com minhas mudanças
  • Qualquer dependência de terceiros foi atualizada e documentada

Summary by CodeRabbit

  • Chores
    • Added configurable OAuth redirect URL support through environment variable, allowing flexible deployment configuration. The redirect URL now derives from OAUTH_SUCCESS_REDIRECT_URL with a fallback to default value if unset.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 16, 2025 •

Copy link
Copy Markdown

Walkthrough

This PR introduces environment-driven OAuth redirect configuration by adding a new OAUTH_SUCCESS_REDIRECT_URL environment variable and updating the auth route to use it instead of a hardcoded fallback value, allowing runtime customization of the OAuth success redirect destination.

Changes

Cohort / File(s) Change Summary
OAuth Redirect Configuration
.env.example
Added new OAUTH_SUCCESS_REDIRECT_URL environment variable set to http://localhost:3001/ for configuring the default OAuth callback redirect destination.
Auth Route Redirect Logic
src/routes/auth.js
Modified Google OAuth callback redirect to use OAUTH_SUCCESS_REDIRECT_URL environment variable as the default fallback instead of the hardcoded /default value; state parameter decoding logic remains unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Verify that OAUTH_SUCCESS_REDIRECT_URL is properly loaded from environment and accessible in src/routes/auth.js
  • Confirm the fallback behavior to /default functions correctly when the environment variable is not set
  • Ensure the state parameter override logic still takes precedence over the environment-driven default value

Possibly related PRs

  • fix: remove redirect validation #37: Modifies redirect validation in auth routes, working in tandem with this PR's redirect configuration changes.
  • Makes redirect route dynamic #36: Previously introduced dynamic redirect via state encoding and /default fallback; this PR builds on that foundation by replacing the hardcoded fallback with an environment variable.

Suggested reviewers

  • ederson-torresini
  • kauanrfontana
  • arthurlorenzon

Poem

🐰 A redirect flows from the environment's keep,
No hardcoded paths in the secrets so deep,
OAuth now speaks through variables clear,
Configuration whispers what callbacks should hear! 🔐

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: creating the OAUTH_SUCCESS_REDIRECT_URL environment variable for frontend URL redirect purposes.
Description check ✅ Passed The description is well-structured, follows the repository template, includes a brief explanation, specifies the change type as chore, indicates local testing, and all checklist items are marked complete.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/oath-redirect-url

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/routes/auth.js (1)

32-46: Add validation for the OAuth redirect URL.

The OAUTH_SUCCESS_REDIRECT_URL environment variable is used directly as a redirect target without validation. This creates a potential open redirect vulnerability if the environment variable is misconfigured to point to an external malicious site.

Consider validating that the URL is either a relative path or matches an allowed domain:

 router.get('/auth/google/callback',
   passport.authenticate('google', {
     failureRedirect: '/login'
   }),
   (req, res) => {
     // Recupera o redirectTo do state parameter
     const state = req.query.state;
-    let finalUrl = process.env.OAUTH_SUCCESS_REDIRECT_URL || '/default';
+    let finalUrl = validateRedirectUrl(process.env.OAUTH_SUCCESS_REDIRECT_URL) || '/default';

     if (state) {
       try {
         const decoded = Buffer.from(state, 'base64').toString('utf-8');
-        // Valida se o resultado é um path relativo seguro (não permite URLs externas)
-        if (decoded) {
+        const validatedDecoded = validateRedirectUrl(decoded);
+        if (validatedDecoded) {
-          finalUrl = decoded;
+          finalUrl = validatedDecoded;
         }
       } catch (err) {
         console.error('Error decoding state:', err);
       }
     }

     res.redirect(finalUrl);
   }
 );

Add a validation helper at the top of the file:

/**
 * Validates redirect URL to prevent open redirect vulnerabilities
 * @param {string} url - URL to validate
 * @returns {string|null} - Validated URL or null if invalid
 */
function validateRedirectUrl(url) {
  if (!url || typeof url !== 'string') return null;
  
  // Allow relative paths
  if (url.startsWith('/')) {
    return url;
  }
  
  // Allow specific whitelisted domains (configure via environment)
  const allowedDomains = (process.env.ALLOWED_REDIRECT_DOMAINS || 'localhost:3001').split(',');
  try {
    const urlObj = new URL(url);
    const hostWithPort = urlObj.port ? `${urlObj.hostname}:${urlObj.port}` : urlObj.hostname;
    
    if (allowedDomains.some(domain => hostWithPort === domain.trim())) {
      return url;
    }
  } catch (err) {
    // Invalid URL format
    return null;
  }
  
  return null;
}

Note: The existing validation at line 38 also needs improvement—it currently only checks if decoded is truthy rather than validating it's a safe redirect target. The suggestion above addresses both issues.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d2d4378 and 5f03d6a.

📒 Files selected for processing (2)
  • .env.example (1 hunks)
  • src/routes/auth.js (1 hunks)
🧰 Additional context used
🪛 dotenv-linter (4.0.0)
.env.example

[warning] 14-14: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key

(UnorderedKey)


[warning] 15-15: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)

Comment thread .env.example
Comment on lines +14 to +15
GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback
OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/ No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Environment variable added correctly.

The new OAUTH_SUCCESS_REDIRECT_URL variable is properly added to the OAuth configuration section. The localhost URL is appropriate for development.

Note: Static analysis indicates a missing blank line at the end of the file. Consider adding one for consistency:

 GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback
 OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/
+
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback
OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/
GOOGLE_CALLBACK_URL=http://localhost:3000/api/v1/auth/google/callback
OAUTH_SUCCESS_REDIRECT_URL=http://localhost:3001/
🧰 Tools
🪛 dotenv-linter (4.0.0)

[warning] 14-14: [UnorderedKey] The GOOGLE_CALLBACK_URL key should go before the GOOGLE_CLIENT_ID key

(UnorderedKey)


[warning] 15-15: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)

🤖 Prompt for AI Agents
In .env.example around lines 14 to 15, the file is missing a trailing blank line
at EOF; fix by adding a single newline (blank line) at the end of the file so
the file ends with a newline character for consistency with POSIX conventions.

@ederson-torresini ederson-torresini 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.

O PR melhora o código, embora não resolva todos os problemas de autenticação. Deve-se usar o parâmetro redirect_uri (ref.: Google) para atender plenamente à demanda do sistema.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants