-
Notifications
You must be signed in to change notification settings - Fork 39
fix(auth): normalize JWT identity for Google-authenticated users #201
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
base: main
Are you sure you want to change the base?
Conversation
|
@Abhishek-Dige is attempting to deploy a commit to the mrimmortal09's projects Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThe changes modify NextAuth configuration to improve Google OAuth sign-in handling. Email is consistently lowercased; dbUser tracking propagates user data across conditional branches. Sign-in flow now distinguishes between new and existing users, with role propagation into session/JWT and custom pages (signIn, error routes) added to authOptions. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant GoogleOAuth as Google OAuth
participant NextAuth
participant Database
Client->>GoogleOAuth: Initiate sign-in
GoogleOAuth-->>Client: Return email & profile
Client->>NextAuth: Callback with credentials
rect rgb(200, 220, 240)
Note over NextAuth: Email normalization & lookup
NextAuth->>NextAuth: Lowercase email
NextAuth->>Database: Query user by email
Database-->>NextAuth: dbUser (existing) or null
end
alt Existing User (no googleId)
rect rgb(230, 200, 220)
Note over NextAuth: Update existing user
NextAuth->>Database: Update googleId
Database-->>NextAuth: Refresh dbUser with googleId
end
else New User
rect rgb(220, 230, 200)
Note over NextAuth: Create new user
NextAuth->>Database: Create user (verified=true,<br/>passwordSet=false, roles=[])
Database-->>NextAuth: Return new user record
NextAuth->>NextAuth: Set dbUser to new record
end
end
rect rgb(240, 240, 200)
Note over NextAuth: Populate session & JWT
NextAuth->>NextAuth: Set user.id & roles from dbUser
NextAuth->>NextAuth: Propagate roles into session
NextAuth->>NextAuth: Include roles in JWT token
end
alt Password not set
NextAuth-->>Client: Redirect to set-password
else Password exists
NextAuth-->>Client: Redirect to authenticated page
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
app/api/auth/[...nextauth]/options.ts (1)
121-133: Handle potential null fromfindOneAndUpdate.If
findOneAndUpdatereturnsnull(e.g., due to a race condition where the user was deleted between the find and update),dbUserbecomesnull, and the identity normalization at lines 148-151 would silently skip settinguser.id. This could cause the original OAuth provider ID to persist in the JWT.Consider preserving the original
existingUserreference as a fallback:🔎 Proposed fix
if (!existingUser.googleId && user.id) { - dbUser = await User.findOneAndUpdate( + const updatedUser = await User.findOneAndUpdate( { email: existingUser.email }, { $set: { googleId: user.id, image: user.image || undefined, emailVerified: true, }, }, { new: true, runValidators: true } ) + dbUser = updatedUser ?? existingUser }
🧹 Nitpick comments (1)
app/api/auth/[...nextauth]/options.ts (1)
147-157: Core fix correctly normalizes identity.This addresses the root cause from issue #182 by ensuring the JWT
subcontains the MongoDB_idrather than the Google OAuth provider ID. The conditional guards against nulldbUser.The
(user as any)type assertion is pragmatic given NextAuth's typing constraints. For improved type safety, consider extending NextAuth's types via module augmentation in anext-auth.d.tsfile.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
app/api/auth/[...nextauth]/options.ts
🧰 Additional context used
🧬 Code graph analysis (1)
app/api/auth/[...nextauth]/options.ts (1)
model/User.ts (1)
IUser(3-14)
🔇 Additional comments (5)
app/api/auth/[...nextauth]/options.ts (5)
91-94: LGTM!Custom pages configuration is properly added for sign-in and error routes.
111-119: LGTM!Email normalization to lowercase ensures consistent lookups regardless of case variations in the OAuth profile. The
dbUsercontainer cleanly tracks the database record across conditional branches.
134-145: LGTM!New user creation properly initializes all required fields including
passwordSet: falseand defaultroles: ['user']. TheisNewUserflag correctly tracks new registrations for the redirect logic.
183-191: LGTM!Session and JWT configuration uses sensible defaults with a 24-hour maximum age and 1-hour update interval.
162-180: Role propagation is correctly implemented.The
jwtcallback storesuser.rolesin the token (line 177), and thesessioncallback propagates it tosession.user.roles(line 168). This enables role-based access control throughout the application. NextAuth type augmentation is already in place intypes/next-auth.d.ts, properly extendingSession.userandUserwithidandrolesproperties, so TypeScript will correctly recognize these assignments.
Resolves #182.
Description
This PR fixes an authentication inconsistency for Google-authenticated users.
Previously, JWT
subwas populated with the OAuth provider user ID, while downstream authorization expects the internal MongoDB_id, causing upload failures.This change normalizes Google sign-in by mapping the authenticated user to the database record and injecting the MongoDB
_idinto the auth flow before JWT creation.Live Demo (if any)
Not applicable.
Note for Maintainer
Checkout
Summary by CodeRabbit
Release Notes
Bug Fixes
New Features
✏️ Tip: You can customize this high-level summary in your review settings.