Skip to content

[Refactor] google oauth - #550

Merged
Fermionic-Lyu merged 2 commits into
mainfrom
refactor-google-oauth
Nov 3, 2025
Merged

Fermionic-Lyu merged 2 commits into
mainfrom
refactor-google-oauth

Conversation

@Fermionic-Lyu

@Fermionic-Lyu Fermionic-Lyu commented Nov 3, 2025 •

Copy link
Copy Markdown
Member

Summary

Refactored google oauth into a separate service file.

How did you test this change?

Tested on cloud.

Summary by CodeRabbit

  • Refactor
    • Google OAuth flow consolidated into a dedicated service and third-party sign-ins unified under a single handler for simpler maintenance.
  • Bug Fixes
    • Improved reliability of Google sign-in with protection against duplicate exchanges, short-lived token caching, and clearer error handling for misconfigurations or failed exchanges.

@coderabbitai

coderabbitai Bot commented Nov 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Google OAuth logic was extracted from AuthService into a new singleton GoogleOAuthService. AuthService now delegates Google OAuth URL generation and callback handling to GoogleOAuthService. The OAuth route now uses a generic third-party user creation call for provider data.

Changes

Cohort / File(s) Summary
Google OAuth service extraction
backend/src/core/auth/auth.ts, backend/src/core/auth/oauth.google.ts
Moved Google OAuth flow (consent URL generation, code→token exchange, ID token verification, callback handling) into a new GoogleOAuthService singleton. AuthService now delegates Google-related methods to GoogleOAuthService.getInstance(). New service adds token caching (1min TTL), processed-code tracking, and centralized errors/logging.
Auth route: third-party user creation
backend/src/api/routes/auth.oauth.ts
Replaced Google-specific user creation flow with a generic findOrCreateThirdPartyUser(...) call, packaging provider, providerId, email, name (fallback to email local-part), avatar, and raw payload for multi-provider handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthService
    participant GoogleOAuthService
    participant GoogleOAuth2Client
    participant DB

    Client->>AuthService: request generateOAuthUrl(provider=google, state?)
    AuthService->>GoogleOAuthService: getInstance().generateOAuthUrl(state)
    GoogleOAuthService->>DB: load google oauth config
    GoogleOAuthService->>GoogleOAuth2Client: build consent URL
    GoogleOAuthService-->>AuthService: consent URL
    AuthService-->>Client: redirect URL

    Client->>AuthService: callback with code/token
    AuthService->>GoogleOAuthService: getInstance().handleCallback({code|token}, findOrCreateUser)
    GoogleOAuthService->>GoogleOAuthService: check processedCodes / tokenCache
    alt code provided
      GoogleOAuthService->>GoogleOAuth2Client: exchange code -> tokens
      GoogleOAuthService->>GoogleOAuthService: cache tokens (1min)
    end
    GoogleOAuthService->>GoogleOAuth2Client: verify id_token -> userInfo
    GoogleOAuthService->>AuthService: invoke findOrCreateUser(userInfo)
    AuthService-->>GoogleOAuthService: CreateSessionResponse
    GoogleOAuthService-->>AuthService: session response
    AuthService-->>Client: session established / redirect
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Focus review on:
    • oauth.google.ts singleton correctness, token caching TTL, and race-condition handling for concurrent exchanges.
    • Delegation wiring in auth.ts to ensure error propagation and compatibility with existing findOrCreateThirdPartyUser.
    • Route changes in auth.oauth.ts to confirm payload shape and name/email fallback logic.

Possibly related PRs

Suggested reviewers

  • tonychang04

Poem

🐰 I hopped through code with nimble paws,

Pulled Google out with careful laws.
Now flows are tidy, caches small,
Delegation answers the call.
A happy rabbit hops and twirls — hooray for cleaner walls! 🥕

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "[Refactor] google oauth" directly and clearly summarizes the main change in this pull request. The core work involves extracting Google OAuth functionality from the AuthService class into a new, dedicated GoogleOAuthService class, which is precisely what the title communicates. The title is concise, specific, and avoids vague terminology or noise, making it easy for teammates scanning the commit history to understand the primary change at a glance.
✨ 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 refactor-google-oauth

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.

@Fermionic-Lyu
Fermionic-Lyu marked this pull request as ready for review November 3, 2025 07:46

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e148d2 and 26cef43.

📒 Files selected for processing (2)
  • backend/src/core/auth/auth.ts (6 hunks)
  • backend/src/core/auth/oauth.google.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let; avoid var
Use template literals for string interpolation
Maintain 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.google.ts
backend/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.google.ts
backend/src/{controllers,core}/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper database transaction handling

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.google.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.google.ts
**/[a-z][a-z0-9-]*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Utility files should use kebab-case or camelCase (kebab-case validated here)

Files:

  • backend/src/core/auth/auth.ts
  • backend/src/core/auth/oauth.google.ts
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware

Applied to files:

  • backend/src/core/auth/auth.ts
🧬 Code graph analysis (2)
backend/src/core/auth/auth.ts (1)
backend/src/core/auth/oauth.google.ts (1)
  • GoogleOAuthService (13-224)
backend/src/core/auth/oauth.google.ts (5)
backend/src/app.config.ts (1)
  • config (30-54)
backend/src/utils/environment.ts (1)
  • getApiBaseUrl (39-41)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/types/auth.ts (1)
  • GoogleUserInfo (66-75)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (285-285)

Comment thread backend/src/core/auth/oauth.google.ts Resolved
@Fermionic-Lyu Fermionic-Lyu changed the title refactor google oauth [Refactor] google oauth Nov 3, 2025
@Fermionic-Lyu
Fermionic-Lyu merged commit b29d6e9 into main Nov 3, 2025
@Fermionic-Lyu
Fermionic-Lyu deleted the refactor-google-oauth branch November 3, 2025 08:33
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