Skip to content

Comments

feat: single api for oauth connections#741

Merged
ahmetskilinc merged 4 commits intoMail-0:stagingfrom
BlankParticle:feat/single-point-of-oauth
Apr 21, 2025
Merged

feat: single api for oauth connections#741
ahmetskilinc merged 4 commits intoMail-0:stagingfrom
BlankParticle:feat/single-point-of-oauth

Conversation

@BlankParticle
Copy link
Contributor

@BlankParticle BlankParticle commented Apr 21, 2025

Description

Instead of having 2 endpoints, one for better auth and one custom, consolidate the oauth part into better auth and update relevant tables using hooks.
This fixes the following issues.

  1. Trying to add same connection twice now just updates the existing connection with new info if available.
  2. Only one auth callback is needed for app to function (better-auth one).
  3. No split code/state problem
  4. A user can now login with any one of his connected emails to login into zero.

Type of Change

Please delete options that are not relevant.

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature with breaking changes)
  • 📝 Documentation update
  • 🎨 UI/UX improvement
  • 🔒 Security enhancement
  • ⚡ Performance improvement

Areas Affected

Please check all that apply:

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Authentication/Authorization
  • Data Storage/Management
  • API Endpoints
  • Documentation
  • Testing Infrastructure
  • Development Workflow
  • Deployment/Infrastructure

Testing Done

Describe the tests you've done:

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • Cross-browser testing (if UI changes)
  • Mobile responsiveness verified (if UI changes)

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

Additional Notes

Add any other context about the pull request here.

Screenshots/Recordings

Add screenshots or recordings here if applicable.


By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • New Features

    • Improved account linking with trusted providers, including support for linking accounts with different emails.
    • Enhanced connection management, automatically updating connection details after account creation or update.
  • Refactor

    • Shifted email provider connection initiation from link-based navigation to a programmatic method for a smoother user experience.
    • Updated internal handling of email provider lists to ensure immutability and stricter type safety.
  • Chores

    • Upgraded the "better-auth" dependency to the latest version for improved authentication support.

@vercel
Copy link

vercel bot commented Apr 21, 2025

@BlankParticle is attempting to deploy a commit to the Zero Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 21, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change removes custom OAuth authentication API route handlers for mail provider connection initiation and callback, and migrates the connection flow to use a new programmatic approach. The email provider connection UI is updated to initiate linking via a client-side method instead of navigation. Authentication and connection logic is refactored into a new hook function, which is registered with the authentication library and runs after account creation or update. The email provider constants are made immutable, and the "better-auth" dependency is updated to a newer version.

Changes

File(s) Change Summary
apps/mail/app/api/v1/mail/auth/[providerId]/callback/route.ts,
.../init/route.ts
Deleted custom API route handlers for OAuth callback and authentication initiation.
apps/mail/components/connection/add.tsx Updated UI to use programmatic provider linking via authClient.linkSocial instead of anchor navigation; imported authClient.
apps/mail/lib/auth.ts Added connectionHandlerHook to handle connection logic after account events; registered it with betterAuth via databaseHooks. Extended options for account linking and trusted providers.
apps/mail/lib/constants.ts Made emailProviders export a readonly tuple using as const.
apps/mail/package.json Updated "better-auth" dependency from version "1.2.1" to "1.2.7".

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AddConnectionDialog
    participant authClient
    participant betterAuth
    participant Database

    User->>AddConnectionDialog: Clicks provider button
    AddConnectionDialog->>authClient: linkSocial(providerId)
    authClient->>betterAuth: Initiate OAuth flow
    betterAuth->>User: Redirect to provider for authentication
    User->>betterAuth: Completes authentication
    betterAuth->>connectionHandlerHook: After account create/update
    connectionHandlerHook->>Database: Insert/Update connection record
    betterAuth->>User: Redirect to mail page
Loading

Suggested reviewers

  • ahmetskilinc
  • needleXO

Poem

In the meadow of code, connections anew,
Old routes retire, as fresh flows debut.
With hooks and handlers, the linking is neat,
Immutable providers—oh, what a treat!
The bunny hops forward, dependencies in tow,
To a seamless new login, where happy users go.
🐇✨


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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 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 2c295d6 and 281e215.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • apps/mail/app/api/v1/mail/auth/[providerId]/callback/route.ts (0 hunks)
  • apps/mail/app/api/v1/mail/auth/[providerId]/init/route.ts (0 hunks)
  • apps/mail/components/connection/add.tsx (3 hunks)
  • apps/mail/lib/auth.ts (3 hunks)
  • apps/mail/lib/constants.ts (1 hunks)
  • apps/mail/package.json (1 hunks)
💤 Files with no reviewable changes (2)
  • apps/mail/app/api/v1/mail/auth/[providerId]/callback/route.ts
  • apps/mail/app/api/v1/mail/auth/[providerId]/init/route.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/mail/lib/auth.ts (4)
packages/db/src/schema.ts (2)
  • account (32-48)
  • connection (77-94)
apps/mail/types/index.ts (1)
  • Account (7-11)
apps/mail/app/api/driver/google.ts (1)
  • driver (127-877)
packages/db/src/index.ts (1)
  • db (17-17)
🔇 Additional comments (7)
apps/mail/package.json (1)

63-63: Dependency upgrade aligns with new features.

The upgraded "better-auth" version (1.2.1 → 1.2.7) supports the new account linking and hook features implemented in the auth.ts file.

apps/mail/lib/constants.ts (1)

100-106: Improved type safety with 'as const'.

The addition of as const assertion turns the array into a readonly tuple with literal types, providing stronger type checking and better IDE support for the provider IDs used throughout the authentication flow.

apps/mail/components/connection/add.tsx (2)

10-10: New dependency imported to support programmatic OAuth flow.

The import of authClient enables programmatic OAuth connection instead of navigation-based flows.


56-78: Transition from link-based to programmatic OAuth flow.

The implementation has been updated to replace anchor elements with div elements and use a programmatic approach for OAuth connection. This change:

  1. Eliminates the need for separate API routes for each provider
  2. Centralizes the OAuth flow to use the "better-auth" library directly
  3. Maintains the same user experience with animations and visual elements

Let's verify that all required error handling is in place:

#!/bin/bash
# Check for error handling in the authClient.linkSocial method
rg -A 5 "linkSocial" --type ts
apps/mail/lib/auth.ts (3)

4-4: Updated imports to support new authentication hooks.

The modified imports bring in necessary types and functions to support the new connection handling functionality, including:

  • Account type from better-auth
  • createDriver function to instantiate OAuth provider drivers
  • APIError for proper error handling

Also applies to: 9-9, 11-11


70-70: Enhanced database adapter configuration.

The database adapter configuration has been formatted more clearly, making it easier to read and maintain.


81-97: Robust account linking configuration.

The new configuration enables secure account linking with these key features:

  1. Allows users to link accounts with different email addresses, improving flexibility
  2. Restricts trusted providers to only 'google', enhancing security
  3. Registers the connection handler to run after account creation and update events

This configuration directly addresses the PR objectives of preventing duplicate connections and allowing login with any connected email address.

Let's verify that all files have been updated consistently with the new approach:

#!/bin/bash
# Check if any remaining OAuth route handlers might still exist
fd -t f -e ts "route.ts" --exec grep -l "mail/auth/\[providerId\]" {}

@ahmetskilinc
Copy link
Contributor

Hey @BlankParticle can you check the coderabbitai comments please?

@ahmetskilinc ahmetskilinc changed the base branch from main to staging April 21, 2025 11:46
@BlankParticle BlankParticle force-pushed the feat/single-point-of-oauth branch from 435c38f to 2763b45 Compare April 21, 2025 11:53
@BlankParticle
Copy link
Contributor Author

Hey @BlankParticle can you check the coderabbitai comments please?

I have added extra error handling for the userInfo, everything else can error out if neeed, that would be automatically handled by better-auth as a Internal Server Error. So that info doesn't need to propagate to users

Copy link
Contributor

@ahmetskilinc ahmetskilinc left a comment

Choose a reason for hiding this comment

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

@MrgSub approving this - tested locally.

@ahmetskilinc ahmetskilinc merged commit 37e5190 into Mail-0:staging Apr 21, 2025
2 of 3 checks passed
@BlankParticle BlankParticle deleted the feat/single-point-of-oauth branch April 21, 2025 12:14
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.

3 participants