Skip to content

fix(oauth): Update tokens when duplicate account detected for same user#1219

Merged
elie222 merged 3 commits intomainfrom
fix/oauth-token-update-on-duplicate
Jan 6, 2026
Merged

fix(oauth): Update tokens when duplicate account detected for same user#1219
elie222 merged 3 commits intomainfrom
fix/oauth-token-update-on-duplicate

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 6, 2026

User description

oauth: Fix refresh token not being saved on re-authentication

When a user re-authenticates (e.g., after password change), the OAuth callback could hit a unique constraint error if the account already exists. Previously, the duplicate handler just logged and continued without updating the tokens, leaving refresh_token as NULL.

  • Update tokens when duplicate account is detected for same user
  • Refactor token update logic into colocated helper functions
  • Fixes issue where Microsoft users couldn't re-authenticate after password changes

Generated description

Below is a concise technical summary of the changes proposed in this PR:
Rectify OAuth callback handlers for Google and Outlook to ensure access and refresh tokens are consistently updated during user re-authentication, preventing refresh_token from becoming NULL and resolving authentication failures. Refactor token update logic into dedicated helper functions (updateGoogleAccountTokens, updateMicrosoftAccountTokens) to centralize persistence mechanisms and improve code maintainability.

TopicDetails
OAuth Token Persistence Enhance OAuth callback logic for Google and Outlook to correctly persist access and refresh tokens during re-authentication, specifically addressing cases where an existing account is detected. This includes updating the select clause to retrieve accountId and invoking new helper functions (updateGoogleAccountTokens, updateMicrosoftAccountTokens) to ensure tokens are saved, preventing refresh_token from being NULL. The refactoring centralizes token update operations, including conditional refresh token updates to preserve existing tokens if not provided by the provider, and extracts date parsing for Microsoft tokens.
Modified files (2)
  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
Latest Contributors(2)
UserCommitDate
elie222provider-account-id-mi...January 04, 2026
eduardoleliss@gmail.comPR-feedbackAugust 29, 2025
Developer Tooling Doc Update the .claude/commands/create-pr.md documentation to include a new instruction to display the name of the created branch after executing the gh pr create command. This improves the user experience by providing more immediate feedback on the branch used for the pull request.
Modified files (1)
  • .claude/commands/create-pr.md
Latest Contributors(1)
UserCommitDate
elie222feat-show-internal-tea...January 05, 2026
This pull request is reviewed by Baz. Review like a pro on (Baz).

Summary by CodeRabbit

  • Documentation

    • Updated pull request workflow documentation with additional output requirements
  • Bug Fixes

    • Improved reliability in Google account linking with enhanced token management
    • Enhanced Outlook account linking with refined account handling and token updates
    • Better error recovery during concurrent account operations

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

@vercel
Copy link

vercel bot commented Jan 6, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Jan 6, 2026 11:05pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 6, 2026

📝 Walkthrough

Walkthrough

Three files updated: documentation for PR workflows now includes branch name display instruction; Google and Outlook OAuth callback routes refactored to centralize token update logic via new internal helper functions that handle account token persistence more consistently.

Changes

Cohort / File(s) Summary
Documentation Update
.claude/commands/create-pr.md
Added instruction to display branch name in Step 3 PR workflow, complementing existing PR URL display directive.
Google OAuth Token Refactoring
apps/web/app/api/google/linking/callback/route.ts
Introduced GoogleTokens interface and updateGoogleAccountTokens helper function to centralize token updates (access_token, refresh_token, expires_at, scope, token_type, id_token). Replaced inline token updates in concurrent-account-creation path with helper call; improves logging specificity for existing account scenarios.
Outlook OAuth Token Refactoring
apps/web/app/api/outlook/linking/callback/route.ts
Introduced MicrosoftTokens interface, parseMicrosoftExpiresAt, and updateMicrosoftAccountTokens helpers to centralize token updates. Refactored multiple code paths to use the new helper; improved logging to include accountId. Preserves existing refresh_token when new one not provided.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 Token helpers bloom, so tidy and clean,
Google and Outlook, a refactoring scene,
No more scattered updates scattered about,
One function per provider, without a doubt!
The branch name's displayed, docs shine ever bright,
A rabbit's delight—code organized right! 🌿

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 directly reflects the main purpose of the PR—updating tokens when a duplicate OAuth account is detected for the same user, which is the core fix across both Google and Outlook OAuth handlers.
✨ Finishing touches
  • 📝 Generate docstrings

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.

@macroscopeapp
Copy link
Contributor

macroscopeapp bot commented Jan 6, 2026

Update Google and Microsoft account token handling on duplicate account detection in GET handlers at apps/web/app/api/google/linking/callback/route.ts and apps/web/app/api/outlook/linking/callback/route.ts

Add updateGoogleAccountTokens and updateMicrosoftAccountTokens helpers and call them when a duplicate account for the same user is detected; extract Microsoft expiry parsing into parseMicrosoftExpiresAt; log with accountId and replace inline Prisma updates with helper calls.

📍Where to Start

Start with the GET handler logic for duplicate account handling in apps/web/app/api/google/linking/callback/route.ts, then review the helper implementations updateGoogleAccountTokens and updateMicrosoftAccountTokens in their respective files.


📊 Macroscope summarized 7f69321. 2 files reviewed, 4 issues evaluated, 3 issues filtered, 1 comment posted. View details

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 2 files

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
.claude/commands/create-pr.md (1)

61-62: Capitalize "Markdown" as a proper noun.

The static analysis tool flagged that "markdown" should be capitalized as "Markdown" when referring to the markup language. Minor documentation clarity improvement.

🔎 Proposed fix
-Display the returned PR URL as a markdown link on its own line, formatted as: `[PR #<number>](<url>)` so it's clickable.
+Display the returned PR URL as a Markdown link on its own line, formatted as: `[PR #<number>](<url>)` so it's clickable.
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e745a15 and c8e945e.

📒 Files selected for processing (3)
  • .claude/commands/create-pr.md
  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
🧰 Additional context used
📓 Path-based instructions (20)
!(pages/_document).{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • .claude/commands/create-pr.md
  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Don't export imported variables
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions
Don't use TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/api/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)

apps/web/app/api/**/route.ts: Create GET API routes using withAuth or withEmailAccount middleware in apps/web/app/api/*/route.ts, export response types as GetExampleResponse type alias for client-side type safety
Always export response types from GET routes as Get[Feature]Response using type inference from the data fetching function for type-safe client consumption
Do NOT use POST API routes for mutations - always use server actions with next-safe-action instead

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/app/**/route.ts

📄 CodeRabbit inference engine (.cursor/rules/get-api-route.mdc)

**/app/**/route.ts: Always wrap GET API route handlers with withAuth or withEmailAccount middleware for consistent error handling and authentication in Next.js App Router
Infer and export response type for GET API routes using Awaited<ReturnType<typeof functionName>> pattern in Next.js
Use Prisma for database queries in GET API routes
Return responses using NextResponse.json() in GET API routes
Do not use try/catch blocks in GET API route handlers when using withAuth or withEmailAccount middleware, as the middleware handles error handling

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/**/[!.]*/route.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Use kebab-case for route directories in Next.js App Router (e.g., api/hello-world/route)

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/api/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/security-audit.mdc)

apps/web/app/api/**/*.{ts,tsx}: API routes must use withAuth, withEmailAccount, or withError middleware for authentication
All database queries must include user scoping with emailAccountId or userId filtering in WHERE clauses
Request parameters must be validated before use; avoid direct parameter usage without type checking
Use generic error messages instead of revealing internal details; throw SafeError instead of exposing user IDs, resource IDs, or system information
API routes should only return necessary fields using select in database queries to prevent unintended information disclosure
Cron endpoints must use hasCronSecret or hasPostCronSecret to validate cron requests and prevent unauthorized access
Request bodies should use Zod schemas for validation to ensure type safety and prevent injection attacks

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/app/api/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/app/api/**/*.ts: ALL API routes that handle user data MUST use appropriate middleware: use withEmailAccount for email-scoped operations, use withAuth for user-scoped operations, or use withError with proper validation for public/custom auth endpoints
Use withEmailAccount middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using emailAccountId
Use withAuth middleware for user-level operations such as user settings, API keys, and referrals that use only userId
Use withError middleware only for public endpoints, custom authentication logic, or cron endpoints. For cron endpoints, MUST use hasCronSecret() or hasPostCronSecret() validation
Cron endpoints without proper authentication can be triggered by anyone. CRITICAL: All cron endpoints MUST validate cron secret using hasCronSecret(request) or hasPostCronSecret(request) and capture unauthorized attempts with captureException()
Always validate request bodies using Zod schemas to ensure type safety and prevent invalid data from reaching database operations
Maintain consistent error response format across all API routes to avoid information disclosure while providing meaningful error feedback

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{tsx,ts,css}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
**/{app,pages}/**/{route,+page}.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/{app,pages}/**/{route,+page}.{ts,tsx}: Use middleware wrappers (withError, withAuth, withEmailAccount, withEmailProvider) that automatically create loggers with request context in API routes
Enrich logger context within route handlers using logger.with() to add request-specific fields like messageId

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Follow NextJS app router structure with (app) directory

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/**/*.{ts,tsx,js,jsx,json,css}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Format code with Prettier

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/**/*.{example,ts,json}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
apps/web/app/api/**/*.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/app/api/**/*.ts: Create GET API routes wrapped with withAuth or withEmailAccount middleware for fetching data
Export response types from GET API routes using export type GetXResponse = Awaited<ReturnType<typeof getData>>

Files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
🧠 Learnings (3)
📚 Learning: 2025-11-25T14:39:23.326Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:23.326Z
Learning: Applies to app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account (reading/writing emails, rules, schedules, etc.) - provides `emailAccountId`, `userId`, and `email` in `request.auth`

Applied to files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
📚 Learning: 2025-11-25T14:39:04.892Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security-audit.mdc:0-0
Timestamp: 2025-11-25T14:39:04.892Z
Learning: Applies to apps/web/app/api/**/route.ts : All database queries must include user/account filtering with `emailAccountId` or `userId` in WHERE clauses to prevent IDOR vulnerabilities

Applied to files:

  • apps/web/app/api/google/linking/callback/route.ts
📚 Learning: 2025-11-25T14:39:27.909Z
Learnt from: CR
Repo: elie222/inbox-zero PR: 0
File: .cursor/rules/security.mdc:0-0
Timestamp: 2025-11-25T14:39:27.909Z
Learning: Applies to **/app/api/**/*.ts : Use `withEmailAccount` middleware for operations scoped to a specific email account, including reading/writing emails, rules, schedules, or any operation using `emailAccountId`

Applied to files:

  • apps/web/app/api/google/linking/callback/route.ts
  • apps/web/app/api/outlook/linking/callback/route.ts
🪛 LanguageTool
.claude/commands/create-pr.md

[uncategorized] ~61-~61: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ..." ``` Display the returned PR URL as a markdown link on its own line, formatted as: `[P...

(MARKDOWN_NNP)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test
🔇 Additional comments (9)
.claude/commands/create-pr.md (1)

61-62: Documentation additions are clear and improve user guidance.

The new instructions to display the PR URL as a clickable link and show the branch name created align well with the command workflow and provide helpful user feedback.

apps/web/app/api/google/linking/callback/route.ts (4)

182-183: LGTM! Necessary field addition for token updates.

The id field is correctly added to the select statement to enable token updates via the new helper function when handling duplicate accounts.


186-195: Excellent fix for the duplicate account token update issue.

This properly addresses the core problem described in the PR: when a duplicate account is detected during re-authentication, tokens are now updated instead of being ignored. The improved logging with accountId enhances observability for debugging re-authentication flows.


221-221: Good refactor to centralize token update logic.

Using the updateGoogleAccountTokens helper ensures consistent token handling across both the duplicate-account path and the update-tokens path.


288-315: Well-implemented token update helper that preserves refresh_token.

The conditional spread on lines 306-308 correctly preserves the existing refresh_token when the provider doesn't return one (which is typical for Google OAuth on subsequent re-authentications). This addresses the concerns raised in previous reviews about refresh tokens being overwritten with null.

The helper is appropriately:

  • Internal (not exported)
  • Colocated at the bottom of the file
  • Handles expiry_date to expires_at conversion for Google's OAuth response format
apps/web/app/api/outlook/linking/callback/route.ts (4)

234-234: LGTM! Necessary field addition for token updates.

Consistent with the Google file, the id field is added to support the token update helper when handling duplicate accounts.


238-247: Excellent fix for Microsoft re-authentication issue.

This addresses the specific failure mode mentioned in the PR description where Microsoft users couldn't re-authenticate after password changes. The token update now ensures refresh_token isn't left as NULL when duplicate accounts are detected.


273-276: Good refactor to centralize token update logic.

Consistent with the Google file, this uses the dedicated helper to ensure uniform token handling across different code paths.


341-381: Well-structured token helpers for Microsoft OAuth.

The implementation properly handles Microsoft OAuth token response variations:

  • parseMicrosoftExpiresAt handles both expires_at (Unix timestamp) and expires_in (relative seconds)
  • Conditional spread on lines 373-375 preserves existing refresh_token when provider doesn't return one
  • Good refactor to extract the expires_at calculation logic that was previously inline (lines 162-171)

The helpers are appropriately internal and colocated, following coding guidelines.

@elie222 elie222 merged commit 68d8c11 into main Jan 6, 2026
27 checks passed
@elie222 elie222 deleted the fix/oauth-token-update-on-duplicate branch January 6, 2026 23:15
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.

1 participant

Comments