Skip to content

feat(auth): add Google OAuth authentication#124

Open
TejasNere99 wants to merge 5 commits into
CodePlaygroundHub:mainfrom
TejasNere99:feat/google-oauth-authentication
Open

feat(auth): add Google OAuth authentication#124
TejasNere99 wants to merge 5 commits into
CodePlaygroundHub:mainfrom
TejasNere99:feat/google-oauth-authentication

Conversation

@TejasNere99

@TejasNere99 TejasNere99 commented Jul 19, 2026

Copy link
Copy Markdown

Summary

fixes : #122
This PR adds Google OAuth authentication to the application, allowing users to securely sign in or sign up using their Google account.

The authentication pages were updated to include the Google Sign-In option while preserving the existing authentication flow.


Changes Made

Backend

  • Added Google OAuth token verification using google-auth-library.
  • Added a new /auth/google endpoint.
  • Supports both:
    • Existing users signing in with Google.
    • New users creating an account using Google.
  • Automatically links an existing local account with a Google account using the same email.
  • Added support for provider and googleId in the User model.

Frontend

  • Integrated Google Sign-In using @react-oauth/google.
  • Added Google authentication to both Login and Signup pages.
  • Reused the existing authentication flow for a seamless user experience.
  • Added loading states and error handling.
  • Updated the authentication page layout to accommodate the Google Sign-In button without affecting the existing flow.

Testing

  • Email login
  • Email signup
  • Google login
  • Google signup
  • Existing user with Google account
  • New user account creation
  • No existing authentication flow was broken

Screenshots

image image Screenshot 2026-07-19 160143

Summary by CodeRabbit

  • New Features
    • Added Google sign-in and sign-up alongside email/password login.
    • Added a Google auth flow that validates Google ID tokens, restricts to verified Google emails, and returns an app JWT.
    • Supports creating new Google accounts or linking Google identity to existing accounts.
  • UI Improvements
    • Updated login and registration screens with Google buttons, “OR” divider, loading spinners, and toast-based error handling.
  • Backend Updates
    • Expanded user profile to store OAuth provider info and Google identity, and relaxed password requirement for non-local accounts.
  • Configuration / Setup
    • Added Google OAuth client ID to frontend and backend environment examples.

@vercel

vercel Bot commented Jul 19, 2026

Copy link
Copy Markdown

@TejasNere99 is attempting to deploy a commit to the Akash Santra 's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@TejasNere99, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 42 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d2d48010-e96d-481c-8ce5-fd5b06c24912

📥 Commits

Reviewing files that changed from the base of the PR and between 787f322 and 5770cdb.

📒 Files selected for processing (1)
  • backend/src/controllers/auth.controller.js
📝 Walkthrough

Walkthrough

Google OAuth sign-in and sign-up are implemented across the backend and frontend, including token verification, provider-aware user records, account creation/linking, frontend OAuth controls, and authenticated session handling.

Changes

Google OAuth authentication

Layer / File(s) Summary
OAuth configuration and user schema
backend/.env.example, backend/package.json, backend/src/models/user.model.js, frontend/.env.example, frontend/package.json
Adds Google client configuration and authentication dependencies, while allowing provider users without passwords and storing provider metadata.
Google authentication endpoint
backend/src/controllers/auth.controller.js, backend/src/routes/auth.route.js
Verifies Google ID tokens, links or creates users, returns JWT user data, and exposes POST /google.
Frontend Google sign-in and sign-up
frontend/src/main.jsx, frontend/src/store/useAuthStore.js, frontend/src/pages/LoginPage.jsx, frontend/src/pages/SignUpPage.jsx
Configures the Google provider, adds Google login controls and loading states, and persists successful authentication.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Frontend
  participant GoogleOAuth
  participant Backend
  participant UserModel
  Frontend->>GoogleOAuth: Obtain Google ID token
  Frontend->>Backend: POST /auth/google with token
  Backend->>GoogleOAuth: Verify ID token
  GoogleOAuth-->>Backend: Verified email and profile
  Backend->>UserModel: Find, link, or create user
  UserModel-->>Backend: User record
  Backend-->>Frontend: JWT and user profile
Loading

Possibly related issues

Suggested labels: enhancement

Suggested reviewers: akash504-ai, nihar-ux18

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding Google OAuth authentication for sign-in and sign-up.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/src/models/user.model.js (1)

35-39: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard password login for Google accounts
googleAuth can create users without a local password, but login still calls bcrypt.compare(password, user.password) unconditionally. For those accounts this returns a 500 instead of a clear “use Google Sign-In” response. Add an early !user.password check in login.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/models/user.model.js` around lines 35 - 39, Update the login
method to check for a missing user.password before calling bcrypt.compare, and
return a clear response directing Google-linked accounts to use Google Sign-In.
Preserve the existing password comparison flow for users with local passwords.
🧹 Nitpick comments (2)
backend/src/models/user.model.js (1)

136-146: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Consider a unique/sparse index on googleId.

googleId has no index constraints. Adding unique: true, sparse: true guards against two user documents ever sharing the same Google account identifier, which is otherwise only implicitly prevented by the email-based lookup in the controller.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/models/user.model.js` around lines 136 - 146, Update the googleId
field in the user model schema to enforce a unique sparse index by adding the
corresponding schema options. Preserve the existing String type and null default
so users without Google accounts remain allowed while duplicate non-null Google
identifiers are rejected.
backend/src/controllers/auth.controller.js (1)

1066-1072: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Token-verification failures return 500 instead of 401.

Any failure inside the try block — including verifyIdToken rejecting an invalid/expired/tampered token — falls through to a generic 500 "Internal Server Error". Distinguishing token-verification errors (401) from true server errors would give the frontend a more accurate signal and avoid masking client-side issues as backend failures.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/controllers/auth.controller.js` around lines 1066 - 1072, Update
the Google authentication error handling around the controller’s verifyIdToken
flow to detect invalid, expired, or tampered token-verification failures and
return HTTP 401 instead of the generic 500 response. Preserve the existing 500
response for unrelated server errors and keep the current error logging context.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/src/controllers/auth.controller.js`:
- Around line 1028-1052: Update the existing-user branch after User.findOne to
reject banned users and prevent Google linking or authentication for users whose
isVerified flag is false. Apply these checks before assigning googleId, saving
the user, or issuing the JWT, while preserving Google linking for verified,
non-banned users and the existing new-user creation flow.
- Around line 1-11: Add a startup validation immediately after the
`googleClient` initialization to require `process.env.GOOGLE_CLIENT_ID`,
matching the existing `JWT_SECRET` guard’s fail-fast behavior and error-handling
style. Ensure application startup stops when the value is missing, before any
token verification can occur.

---

Outside diff comments:
In `@backend/src/models/user.model.js`:
- Around line 35-39: Update the login method to check for a missing
user.password before calling bcrypt.compare, and return a clear response
directing Google-linked accounts to use Google Sign-In. Preserve the existing
password comparison flow for users with local passwords.

---

Nitpick comments:
In `@backend/src/controllers/auth.controller.js`:
- Around line 1066-1072: Update the Google authentication error handling around
the controller’s verifyIdToken flow to detect invalid, expired, or tampered
token-verification failures and return HTTP 401 instead of the generic 500
response. Preserve the existing 500 response for unrelated server errors and
keep the current error logging context.

In `@backend/src/models/user.model.js`:
- Around line 136-146: Update the googleId field in the user model schema to
enforce a unique sparse index by adding the corresponding schema options.
Preserve the existing String type and null default so users without Google
accounts remain allowed while duplicate non-null Google identifiers are
rejected.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bbfcb0a6-fe39-40dd-86ff-ccde88070166

📥 Commits

Reviewing files that changed from the base of the PR and between 64c82d1 and d6e6327.

⛔ Files ignored due to path filters (2)
  • backend/package-lock.json is excluded by !**/package-lock.json
  • frontend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (11)
  • backend/.env.example
  • backend/package.json
  • backend/src/controllers/auth.controller.js
  • backend/src/models/user.model.js
  • backend/src/routes/auth.route.js
  • frontend/.env.example
  • frontend/package.json
  • frontend/src/main.jsx
  • frontend/src/pages/LoginPage.jsx
  • frontend/src/pages/SignUpPage.jsx
  • frontend/src/store/useAuthStore.js

Comment thread backend/src/controllers/auth.controller.js Outdated
Comment thread backend/src/controllers/auth.controller.js
@Akash504-ai

Copy link
Copy Markdown
Member

Thanks for the contribution! The implementation looks good overall. Before I review it further, please address the security issues highlighted by CodeRabbit, especially the isVerified/isBanned checks and the missing GOOGLE_CLIENT_ID validation. Once those are fixed, I'll take another look.

TejasNere99 and others added 3 commits July 20, 2026 19:39
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Refactor Google OAuth client initialization to handle undefined GOOGLE_CLIENT_ID gracefully.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/src/controllers/auth.controller.js`:
- Around line 1048-1055: Update the Google-user lookup in the relevant auth
controller flow to explicitly select the password field before setting it
undefined, ensuring Mongoose persists its removal. In the local login handler,
guard against users without a password and return the existing
invalid-credentials response before calling bcrypt.compare.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 824774c6-ec82-48ee-addb-f9b992714725

📥 Commits

Reviewing files that changed from the base of the PR and between 5e481f3 and 787f322.

📒 Files selected for processing (1)
  • backend/src/controllers/auth.controller.js

Comment thread backend/src/controllers/auth.controller.js
Add validation for missing password in authentication.
@TejasNere99

Copy link
Copy Markdown
Author

Hi @Akash504-ai,

I've addressed all the CodeRabbit review comments and pushed the required changes. The CI checks are now passing successfully.

Could you please review the PR when you have a chance? If there's anything else that needs to be improved, I'd be happy to make the necessary changes.

Thank you!

@Akash504-ai

Copy link
Copy Markdown
Member

Thanks for the updates! Looks good so far.
I'll start reviewing and merging PRs from the 25th. If I find anything during the review, I'll let you know. Thanks for the contribution!

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.

[FEATURE]: Add Google OAuth Authentication for Sign In & Sign Up

2 participants