Skip to content

fix: fetch full user object from MongoDB in protect middleware to populate username#210

Merged
Userunknown84 merged 1 commit into
Userunknown84:mainfrom
vedant-kawale-27:main
Jun 22, 2026
Merged

fix: fetch full user object from MongoDB in protect middleware to populate username#210
Userunknown84 merged 1 commit into
Userunknown84:mainfrom
vedant-kawale-27:main

Conversation

@vedant-kawale-27

Copy link
Copy Markdown
Contributor

Summary

Fixes an issue where requests forwarded to the Flask ML API contained X-User-Username: undefined in the headers.

The protect middleware was previously assigning the decoded JWT payload { id: userId } directly to req.user without querying the database. Consequently, references to req.user.username returned undefined. This PR modifies the middleware to retrieve the complete user document from MongoDB.

Changes

  • Import User Model: Added the MongoDB User model import in backend/middleware/authMiddleware.js.
  • Async Middleware: Modified the protect middleware to be async.
  • Retrieve User Document: Implemented User.findById(decoded.id).select('-password') to retrieve the user's complete data from MongoDB.
  • Verify User Existence: Returns a 401 User not found. response if the user no longer exists in the database.
  • Populate req.user: Assigned the retrieved user document to req.user so req.user.username and other properties are correctly populated.

Verification

  • Ran the integration test suite locally to verify there were no regressions in endpoints utilizing protect:
    .\venv\Scripts\python.exe -m pytest backend/tests/
    
    

closes #174

Copilot AI review requested due to automatic review settings June 22, 2026 17:22
@vercel

vercel Bot commented Jun 22, 2026

Copy link
Copy Markdown

@vedant-kawale-27 is attempting to deploy a commit to the Aditya Sharma's projects Team on Vercel.

A member of the Team first needs to authorize it.

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@Userunknown84 Userunknown84 merged commit a7fc394 into Userunknown84:main Jun 22, 2026
4 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JWT Token Payload is missing the username field, causing undefined headers

3 participants