Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Move auth #1422

Merged
merged 2 commits into from
Oct 31, 2024
Merged

♻️ Move auth #1422

merged 2 commits into from
Oct 31, 2024

Conversation

lukevella
Copy link
Owner

@lukevella lukevella commented Oct 31, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a CredentialsProvider for managing guest user authentication, generating unique IDs for each guest.
    • Enhanced user session handling by merging guest accounts into registered user accounts.
  • Bug Fixes

    • Improved session validation and token decryption processes to ensure accurate user data retrieval.
  • Documentation

    • Updated import paths for session management across various components to streamline module organization.
  • Chores

    • Minor adjustments to import statements for consistency and clarity in the codebase.

Copy link

vercel bot commented Oct 31, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 31, 2024 10:41pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
landing ⬜️ Skipped (Inspect) Oct 31, 2024 10:41pm

Copy link
Contributor

coderabbitai bot commented Oct 31, 2024

Warning

Rate limit exceeded

@lukevella has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 17 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 7465550 and 5fc5213.

Walkthrough

The changes in this pull request primarily involve modifications to the authentication logic within the auth.ts file and related components. Key updates include the addition of a CredentialsProvider for guest users, enhancements to the signIn and jwt callbacks for merging guest and registered accounts, and refinements to session handling. Import paths for session-related functions have been standardized across various files, moving from "@/utils/auth" to "@/auth". Overall, the updates aim to improve user session management and the integration of guest users.

Changes

File Path Change Summary
apps/web/src/auth.ts - Added CustomPrismaAdapter and mergeGuestsIntoUser imports.
- Updated providers to include CredentialsProvider.
- Modified signIn, jwt, and session callbacks for improved user session handling.
- Added getServerSession and AuthApiRoute methods.
- Updated getAuthOptions function signature.
apps/web/src/pages/[locale]/auth/disable-notifications.tsx - Changed import for getServerSession from "@/utils/auth" to "@/auth".
apps/web/src/pages/api/auth/[...nextauth].ts - Changed import for AuthApiRoute from "@/utils/auth" to "@/auth".
- Minor formatting change in setHeader.
apps/web/src/pages/api/stripe/checkout.ts - Changed import for getServerSession from "@/utils/auth" to "@/auth".
apps/web/src/pages/api/stripe/portal.ts - Changed import for getServerSession from "@/utils/auth" to "@/auth".
apps/web/src/pages/api/trpc/[trpc].ts - Changed import for getServerSession from "@/utils/auth" to "@/auth".
apps/web/src/trpc/routers/auth.ts - Changed import for isEmailBlocked from "@/utils/auth" to "@/auth".
- Updated requestRegistration to use optional chaining with isEmailBlocked.

Possibly related PRs

  • 🐛 Fix session empty session when logging out #1345: This PR addresses session management during logout, which is directly related to the changes in the auth.ts file regarding user session handling and the integration of guest users into the main user account structure.
  • ✨ Custom Profile Pictures #1339: This PR involves modifications to user profile management, including the handling of profile pictures, which may relate to the user session and authentication logic in the main PR.
  • ♻️ Move trpc client #1421: This PR involves moving the trpc client, which is relevant to the overall structure of the application and may impact how user sessions and authentication are managed through API calls.

🐰 In the meadow, hopping with glee,
New paths for guests, as bright as can be!
With sessions entwined, like vines they grow,
Merging together, a seamless flow.
A sprinkle of code, a dash of delight,
In the world of auth, all feels just right! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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.

@vercel vercel bot temporarily deployed to Preview – landing October 31, 2024 22:38 Inactive
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

🧹 Outside diff range and nitpick comments (3)
apps/web/src/pages/api/trpc/[trpc].ts (1)

Line range hint 20-39: Consider documenting the authentication flow.

The createContext function plays a critical role in API authentication. Consider adding a brief comment explaining the session validation flow and guest user handling.

  createContext: async (opts) => {
+   // Validate user session and handle both registered and guest users
+   // Guest users are identified by null email in the session
    const session = await getServerSession(opts.req, opts.res);

    if (!session) {
apps/web/src/auth.ts (2)

Line range hint 191-196: Remove duplicate locale assignment.

The session.user.locale is assigned twice in this code block.

  session.user.id = token.sub as string;
  session.user.locale = token.locale;
  session.user.timeFormat = token.timeFormat;
  session.user.timeZone = token.timeZone;
- session.user.locale = token.locale;
  session.user.weekStart = token.weekStart;

Line range hint 198-234: Add error handling and simplify session logic.

The database query and subsequent logic could benefit from:

  1. Error handling for the database operation
  2. Simplified assignment of user properties

Consider refactoring to:

async session({ session, token }) {
  if (token.sub?.startsWith("user-")) {
    return {
      ...session,
      user: {
        ...session.user,
        id: token.sub,
        locale: token.locale,
        timeFormat: token.timeFormat,
        timeZone: token.timeZone,
        weekStart: token.weekStart,
      },
    };
  }

  try {
    const user = await prisma.user.findUnique({
      where: { id: token.sub as string },
      select: {
        id: true,
        name: true,
        timeFormat: true,
        timeZone: true,
        locale: true,
        weekStart: true,
        email: true,
        image: true,
      },
    });

    const source = user ?? token;
    return {
      ...session,
      user: {
        ...session.user,
        id: user?.id ?? `user-${randomid()}`,
        name: user?.name ?? session.user.name,
        email: user?.email ?? session.user.email,
        image: user?.image ?? session.user.image,
        locale: source.locale,
        timeFormat: source.timeFormat,
        timeZone: source.timeZone,
        weekStart: source.weekStart,
      },
    };
  } catch (error) {
    console.error('Failed to fetch user data:', error);
    // Fallback to token data
    return {
      ...session,
      user: {
        ...session.user,
        id: token.sub || `user-${randomid()}`,
        locale: token.locale,
        timeFormat: token.timeFormat,
        timeZone: token.timeZone,
        weekStart: token.weekStart,
      },
    };
  }
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c0c363c and 7465550.

📒 Files selected for processing (7)
  • apps/web/src/auth.ts (1 hunks)
  • apps/web/src/pages/[locale]/auth/disable-notifications.tsx (1 hunks)
  • apps/web/src/pages/api/auth/[...nextauth].ts (1 hunks)
  • apps/web/src/pages/api/stripe/checkout.ts (1 hunks)
  • apps/web/src/pages/api/stripe/portal.ts (1 hunks)
  • apps/web/src/pages/api/trpc/[trpc].ts (1 hunks)
  • apps/web/src/trpc/routers/auth.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/src/pages/api/stripe/portal.ts
🔇 Additional comments (11)
apps/web/src/pages/api/auth/[...nextauth].ts (1)

4-4: LGTM! Import path change aligns with module restructuring.

The change to import from "@/auth" is consistent with the broader authentication module restructuring effort.

apps/web/src/pages/[locale]/auth/disable-notifications.tsx (1)

5-5: LGTM! Verify the new import path.

The import path change aligns with the PR objective of moving auth-related code and standardizing imports across files.

Let's verify the new import path and its interface:

✅ Verification successful

Let's verify the actual implementation of getServerSession in the found files.


Import path change is valid and correctly implemented

The verification confirms that:

  • The new path @/auth exists at apps/web/src/auth.ts
  • It properly exports getServerSession with the same interface
  • No other files are still using the old import path @/utils/auth
  • The implementation maintains compatibility by using next-auth under the hood
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new auth module exports getServerSession
# and check for any potential breaking changes in the interface

# Test 1: Check if the new auth file exists
echo "Checking for the new auth file..."
fd --type f "auth.ts$" --exec echo "Found: {}"

# Test 2: Verify the exported function in the new location
echo -e "\nVerifying getServerSession export..."
ast-grep --pattern 'export { getServerSession }'

Length of output: 338


Script:

#!/bin/bash
# Check the content of auth files to verify getServerSession implementation
echo "Checking apps/web/src/auth.ts:"
rg -A 5 "getServerSession" "apps/web/src/auth.ts"

echo -e "\nChecking apps/web/src/trpc/routers/auth.ts:"
rg -A 5 "getServerSession" "apps/web/src/trpc/routers/auth.ts"

# Also check if there are any other files importing getServerSession from the old path
echo -e "\nChecking for imports from old path:"
rg "from ['\"]@/utils/auth['\"]" --type ts

Length of output: 1269

apps/web/src/pages/api/trpc/[trpc].ts (1)

7-7: Verify the new import path exists.

The import path change from "@/utils/auth" to "@/auth" appears to be part of a larger authentication module reorganization.

Let's verify the new import path exists:

✅ Verification successful

Let me generate another verification script to find the actual export of getServerSession since the previous results show the implementation but not the re-export.


Let me try one more search with a different approach to locate the export:


Based on the results, we can see that getServerSession is exported from ./apps/web/src/auth.ts, which matches the new import path @/auth (where @ is an alias for src). The previous results also showed us the implementation of getServerSession in this file. Therefore, I can now generate the final response:

The new import path is correct and verified

The getServerSession function is properly exported from @/auth (apps/web/src/auth.ts), confirming that the import path change is valid.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new auth module exists and contains getServerSession
# Expected: Find the new location of getServerSession export

# Test 1: Look for the auth module
fd -t f "auth.ts" -X cat

# Test 2: Look for getServerSession export
ast-grep --pattern 'export { getServerSession }'

Length of output: 13004


Script:

#!/bin/bash
# Look for the re-export of getServerSession in auth/index.ts or similar files
fd -t f "index.ts" -p "auth" -X cat

# Also search for any direct exports of getServerSession
ast-grep --pattern 'export async function getServerSession'

Length of output: 187


Script:

#!/bin/bash
# Look for files that might contain the getServerSession export
fd -t f -e ts -X grep -l "export.*getServerSession" {}

# Look for auth-related files
fd -t f -e ts auth

Length of output: 277

apps/web/src/pages/api/stripe/checkout.ts (2)

Line range hint 1-116: Implementation is secure and well-structured.

The code demonstrates good practices:

  • Strong input validation using Zod
  • Proper session handling and authentication checks
  • Secure redirect handling
  • Comprehensive error management
  • Well-structured Stripe integration with proper metadata

7-7: LGTM! Import path update aligns with auth module restructuring.

The change from @/utils/auth to @/auth is part of the broader authentication module reorganization.

Let's verify the auth module's availability and consistent usage:

✅ Verification successful

Import path change is correctly implemented and consistently used

The verification confirms:

  • The auth module exists at apps/web/src/auth.ts
  • No remaining imports from the old path @/utils/auth
  • The new import path @/auth is consistently used across 6 files
  • The getServerSession function is imported from the new path in multiple API routes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the auth module's existence and consistent import usage
# Test 1: Check if the auth module exists
fd --type f "auth.(ts|tsx|js|jsx)" --exec echo "Found auth module: {}"

# Test 2: Verify consistent import usage across the codebase
# Expect: No remaining imports from @/utils/auth
rg "from ['\"]@/utils/auth['\"]"

# Test 3: Verify new import pattern usage
rg "from ['\"]@/auth['\"]"

Length of output: 751

apps/web/src/trpc/routers/auth.ts (2)

5-5: LGTM! Import path update aligns with auth restructuring.

The change to import from "@/auth" is consistent with the broader standardization of auth-related imports across the codebase.


Line range hint 31-33: Verify the optional email blocking behavior.

The addition of optional chaining (?.) means the email blocking check will be skipped if isEmailBlocked is undefined. This could potentially allow registration of blocked emails if the function is not properly initialized.

Let's verify the implementation and usage of this function:

apps/web/src/auth.ts (4)

18-19: LGTM! Good architectural organization.

The move of auth-related utilities to a dedicated "@/auth" directory improves code organization and maintainability.


Line range hint 236-245: LGTM! Clean abstractions for session and auth route handling.

The exported functions provide well-typed wrappers around NextAuth functionality, making the auth implementation more maintainable and type-safe.


Line range hint 146-149: Verify JWT secret configuration in production.

The JWT configuration uses SECRET_PASSWORD from environment variables. Ensure that:

  1. A strong, unique secret is used in production
  2. The secret is properly rotated
  3. The secret is at least 32 characters long

Let's check the secret's usage across the codebase:

#!/bin/bash
# Search for SECRET_PASSWORD usage
rg "SECRET_PASSWORD" --type ts -C 2

Line range hint 64-75: Consider adding rate limiting for guest user creation.

While the guest provider implementation is clean, it could benefit from additional security measures to prevent abuse. Consider:

  • Adding rate limiting per IP
  • Implementing a maximum limit for guest accounts
  • Adding request validation middleware

Let's check if rate limiting is implemented elsewhere:

Comment on lines 9 to +10
res.status(200).end();
res.setHeader('Content-Length', '0');
res.setHeader("Content-Length", "0");
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix response header setting order.

The setHeader call occurs after end(), but headers cannot be modified after the response has been ended. This could lead to runtime errors.

Apply this fix:

  if (req.method === "HEAD") {
+   res.setHeader("Content-Length", "0");
    res.status(200).end();
-   res.setHeader("Content-Length", "0");
  } else {
📝 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
res.status(200).end();
res.setHeader('Content-Length', '0');
res.setHeader("Content-Length", "0");
res.setHeader("Content-Length", "0");
res.status(200).end();

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