Skip to content

Fix Social Auth Sign-Up Validation Failures#354

Merged
yash-pouranik merged 5 commits into
geturbackend:mainfrom
AYUSH-P-SINGH:Fix_Social_Auth
Jul 17, 2026
Merged

Fix Social Auth Sign-Up Validation Failures#354
yash-pouranik merged 5 commits into
geturbackend:mainfrom
AYUSH-P-SINGH:Fix_Social_Auth

Conversation

@AYUSH-P-SINGH

@AYUSH-P-SINGH AYUSH-P-SINGH commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Summary

FIXES #352

This PR fixes a bug where social authentication (Google/GitHub OAuth) failed with a 500 Internal Server Error when projects defined additional custom fields in the user schema with required: true.

Problem

During the OAuth callback flow (handleSocialAuthCallback), a new user was created using:

Model.create(newUserPayload)

The payload only contained OAuth-related information such as:

  • Email
  • Name
  • Username
  • Avatar
  • Generated password

If the application's user schema included any additional required fields (e.g. phone, department, role, etc.), Mongoose threw a ValidationError, causing the OAuth sign-up process to fail with a 500 error.

Solution

This PR introduces a validation-bypass fallback inside:

findOrCreateSocialUser()

Implementation flow:

  1. Attempt to create the user normally using:
Model.create(newUserPayload)
  1. If a Mongoose ValidationError occurs because of missing custom required fields:

    • Construct a new Mongoose document.
    • Save it using:
user.save({ validateBeforeSave: false })
  1. If the fallback save still fails due to database constraints (duplicate keys, invalid schema, etc.), the error is mapped to a clean 400 Bad Request response with a descriptive message.

This allows OAuth authentication to complete successfully while enabling applications to collect any missing required profile information later through an onboarding or profile-completion flow.


Changes Made

  • Added a validation-bypass fallback in findOrCreateSocialUser.
  • Preserved the default validation flow whenever possible.
  • Gracefully handled Mongoose ValidationError.
  • Improved error handling by returning meaningful client errors instead of an unhandled 500 response.
  • Added automated tests covering the fallback behavior.

Testing

Backend

  • ✅ Ran all backend tests successfully.
  • ✅ Added unit tests covering the validation-bypass scenario in:
apps/public-api/src/__tests__/userAuth.social.test.js

Frontend

  • ✅ Ran lint checks successfully with no warnings or errors.

Type of Change

  • ✅ 🐛 Bug fix (non-breaking change)

Checklist

  • ✅ Code follows the project's coding standards.
  • ✅ Self-reviewed the changes.
  • ✅ Added comments where necessary.
  • ✅ No new warnings or errors introduced.
  • ✅ Added tests for the new behavior.

Summary by CodeRabbit

  • Bug Fixes
    • Improved social sign-up flow to handle Mongoose ValidationError during user creation by retrying persistence with validation disabled.
    • Updated error handling to return clearer 409 responses for duplicate accounts and 500 responses for other completion failures.
    • Ensures the frontend callback redirect includes the newly created user identifier after successful retry.
  • Tests
    • Added Jest coverage for the validation-retry path and the resulting frontend redirect.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@AYUSH-P-SINGH, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 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

Run ID: 9556b48c-17d0-42bf-aed4-876065f3ecdf

📥 Commits

Reviewing files that changed from the base of the PR and between fa439a6 and 80b413b.

📒 Files selected for processing (2)
  • apps/public-api/src/__tests__/userAuth.social.test.js
  • apps/public-api/src/controllers/userAuth.controller.js
📝 Walkthrough

Walkthrough

Social OAuth user creation now retries Mongoose validation failures with validation disabled and translates creation failures into duplicate-user or signup errors. A Jest test verifies the fallback save and callback redirect.

Changes

Social authentication validation handling

Layer / File(s) Summary
Validation fallback and callback verification
apps/public-api/src/controllers/userAuth.controller.js, apps/public-api/src/__tests__/userAuth.social.test.js
Social signup retries ValidationError failures using validateBeforeSave: false, maps duplicate-key failures to status 409 and other creation failures to status 500, and tests the resulting redirect.

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

Suggested reviewers: yash-pouranik, nitin-kumar-yadav1307

Sequence Diagram(s)

sequenceDiagram
  participant SocialAuthCallback
  participant CompiledUserModel
  participant FrontendCallback
  SocialAuthCallback->>CompiledUserModel: create(newUserPayload)
  CompiledUserModel-->>SocialAuthCallback: ValidationError
  SocialAuthCallback->>CompiledUserModel: save({validateBeforeSave: false})
  CompiledUserModel-->>SocialAuthCallback: saved user
  SocialAuthCallback->>FrontendCallback: redirect with userId
Loading
🚥 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 states the main fix for social auth signup validation failures.
Linked Issues check ✅ Passed The controller now retries social signup after Mongoose validation errors and the new test covers the custom-required-field path.
Out of Scope Changes check ✅ Passed The changes stay focused on social auth signup handling and its corresponding test.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
apps/public-api/src/__tests__/userAuth.social.test.js (1)

693-749: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the fallback save failure path.

The test covers the happy path (save succeeds → redirect), but the error branch where doc.save also fails (controller lines 595-599) is untested. This is a critical path that returns error responses to the client. Consider adding a test where mockSave rejects (e.g., with an E11000 duplicate key error) and asserting the appropriate error response.

🤖 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 `@apps/public-api/src/__tests__/userAuth.social.test.js` around lines 693 -
749, Extend the test for handleSocialAuthCallback to cover the fallback save
failure path by making mockSave reject with an E11000 duplicate-key error after
MockModel.create throws ValidationError. Assert the controller returns the
expected client error response for this failure and does not redirect, while
preserving the existing setup and successful-save assertions in the current
test.
apps/public-api/src/controllers/userAuth.controller.js (1)

588-591: 🗄️ Data Integrity & Integration | 🔵 Trivial

validateBeforeSave: false bypasses all validation — users are saved with missing required fields.

Users persisted via this fallback will have undefined for any custom required fields (e.g., role, termsAccepted). Downstream code expecting these fields may fail at runtime. Consider setting default values for known custom required fields in newUserPayload before the fallback save, or redirecting users to a profile-completion step after social auth to fill in missing fields.

🤖 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 `@apps/public-api/src/controllers/userAuth.controller.js` around lines 588 -
591, Update the fallback save path in the user-auth controller around Model and
newUserPayload so required custom user fields receive valid defaults before
persistence, or route incomplete social-auth users through profile completion.
Ensure fields such as role and termsAccepted are populated before doc.save,
while preserving the existing fallback behavior for complete payloads.
🤖 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 `@apps/public-api/src/controllers/userAuth.controller.js`:
- Around line 595-599: Update the inner save-error handler around doc.save to
use saveErr rather than the outer err, distinguish validation failures from
other persistence errors, and avoid exposing raw Mongoose or MongoDB details.
Replace the raw Error/throw with the established AppError pattern, assigning the
appropriate client-safe message and status code for each error type.

---

Nitpick comments:
In `@apps/public-api/src/__tests__/userAuth.social.test.js`:
- Around line 693-749: Extend the test for handleSocialAuthCallback to cover the
fallback save failure path by making mockSave reject with an E11000
duplicate-key error after MockModel.create throws ValidationError. Assert the
controller returns the expected client error response for this failure and does
not redirect, while preserving the existing setup and successful-save assertions
in the current test.

In `@apps/public-api/src/controllers/userAuth.controller.js`:
- Around line 588-591: Update the fallback save path in the user-auth controller
around Model and newUserPayload so required custom user fields receive valid
defaults before persistence, or route incomplete social-auth users through
profile completion. Ensure fields such as role and termsAccepted are populated
before doc.save, while preserving the existing fallback behavior for complete
payloads.
🪄 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

Run ID: 215865d3-d950-4969-af67-85567cc83871

📥 Commits

Reviewing files that changed from the base of the PR and between 272bbe5 and b6323c5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • apps/public-api/src/__tests__/userAuth.social.test.js
  • apps/public-api/src/controllers/userAuth.controller.js

Comment thread apps/public-api/src/controllers/userAuth.controller.js
@yash-pouranik

Copy link
Copy Markdown
Member

Please fix coderabbits comment
@AYUSH-P-SINGH

@yash-pouranik

Copy link
Copy Markdown
Member

fix this before this Sunday
Else I will close the PR and unassign you from the issue?
@AYUSH-P-SINGH

Handle duplicate user error during social signup.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 `@apps/public-api/src/controllers/userAuth.controller.js`:
- Around line 606-608: Update the outer catch else branch in the relevant
user-auth controller flow to handle non-Mongoose-validation errors with the same
AppError mapping used by the inner catch block, rather than rethrowing raw err.
Preserve the existing validation-error handling while ensuring MongoDB errors
such as duplicate-key failures are converted into a safe client-facing AppError.
🪄 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

Run ID: 75a92eda-c125-4e3e-8203-d0597cac3eed

📥 Commits

Reviewing files that changed from the base of the PR and between b6323c5 and 61a8f87.

📒 Files selected for processing (1)
  • apps/public-api/src/controllers/userAuth.controller.js

Comment thread apps/public-api/src/controllers/userAuth.controller.js
@yash-pouranik

Copy link
Copy Markdown
Member

LGTM
@AYUSH-P-SINGH
Can u please check does this changes needs any changes in all three sdks (react, sdk, python)??

@yash-pouranik

Copy link
Copy Markdown
Member

LGTM
@AYUSH-P-SINGH
Can u please check does this changes needs any changes in all three sdks (react, sdk, python)??

@coderabbitai
please check

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== PR diff: changed paths and focused patch =='
git diff --name-status HEAD^ HEAD
git diff -- apps/public-api/src/controllers/userAuth.controller.js \
  apps/public-api/src/__tests__/userAuth.social.test.js

echo
echo '== Locate SDK/package directories and social-auth-related files =='
fd -HI -t d -E .git '(^|[-_])(react|sdk|python)([-_]|$)|sdk|react' . | head -200
fd -HI -t f -E .git . . | rg -i '(^|/)(react|sdk|python)(/|[-_.])|social.?auth|oauth|callback|userauth' | head -300

echo
echo '== Controller outline and social-auth/callback contract references =='
ast-grep outline apps/public-api/src/controllers/userAuth.controller.js --items all 2>/dev/null || true
rg -n -i -C 4 'findOrCreateSocialUser|social.?auth|oauth|callback|userId|frontend.*callback' \
  apps/public-api/src/controllers/userAuth.controller.js \
  -g '!**/node_modules/**' \
  -g '!**/dist/**' \
  -g '!**/build/**' || true

echo
echo '== Cross-repository/package references to affected public contract =='
rg -n -i -C 3 'social.?auth|oauth|auth/callback|callback.*userId|userId.*callback|google|github' \
  -g '!**/node_modules/**' \
  -g '!**/dist/**' \
  -g '!**/build/**' \
  . || true

Length of output: 190937


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '== Exact PR changes =='
git diff --unified=80 HEAD^ HEAD -- apps/public-api/src/controllers/userAuth.controller.js \
  apps/public-api/src/__tests__/userAuth.social.test.js

echo
echo '== Current social-auth controller flow (implementation and callback redirect) =='
rg -n -C 35 'async function findOrCreateSocialUser|const findOrCreateSocialUser|findOrCreateSocialUser|social.*callback|callback.*redirect|redirect\(' \
  apps/public-api/src/controllers/userAuth.controller.js

echo
echo '== React SDK callback consumer =='
sed -n '45,105p' sdks/urbackend-react/src/context.tsx

echo
echo '== JavaScript SDK social-auth methods =='
sed -n '465,545p' sdks/urbackend-sdk/src/modules/auth.ts

echo
echo '== Python SDK social-auth methods =='
sed -n '375,445p' sdks/urbackend-python/src/urbackend/auth.py

echo
echo '== Verify no SDK files are changed by this PR =='
git diff --name-only HEAD^ HEAD -- sdks/ || true

Length of output: 42780


@Yash-pouranik I checked all three SDKs. No SDK changes are required for this PR.

  • React SDK: continues to read the existing callback token and rtCode, then calls socialExchange.
  • JavaScript/TypeScript SDK: its socialStart() and socialExchange() endpoints and payloads are unchanged.
  • Python SDK: its social_start_url() and social_exchange() methods use the same unchanged contract.

This PR only changes server-side user creation/error handling after OAuth authentication. The public OAuth routes and callback contract remain unchanged: token, rtCode, provider, userId, projectId, isNewUser, and linkedByEmail.

No files under sdks/ are modified, so no SDK release or version bump is needed. 🐇

@yash-pouranik

Copy link
Copy Markdown
Member

So i feel its good to merge?
@coderabbitai

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@yash-pouranik Yes—based on the reviewed scope, this looks good to merge.

The fix is server-side only, includes coverage for the validation fallback, preserves the OAuth callback contract, and does not require changes or releases for the React, JavaScript/TypeScript, or Python SDKs. The reported backend tests and frontend lint checks are also passing. 🐇

@yash-pouranik
yash-pouranik merged commit 6967d01 into geturbackend:main Jul 17, 2026
8 checks passed
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.

[BUG] Social OAuth Sign-Up Fails When Users Schema Contains Custom Required Fields

2 participants