fix(auth): sanitize login response to exclude password hash#365
fix(auth): sanitize login response to exclude password hash#365adityack477 wants to merge 2 commits into
Conversation
✅ Deploy Preview for github-spy ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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. 📝 WalkthroughWalkthroughA security fix introduces ChangesUser Data Sanitization for Auth Responses
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~3 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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.
🎉 Thank you @adityack477 for your contribution. Please make sure your PR follows https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
backend/routes/auth.js (1)
34-36: 💤 Low valueGuard against
req.userbeing undefined.If
passport.authenticate('local')is ever configured (now or in the future) with{ failWithError: false }semantics that allow the handler to run without a user, callingreq.user.toSafeObject()will throw aTypeError. A small defensive check makes the handler more robust and avoids leaking a 500 on edge cases.♻️ Optional hardening
- + res.status(200).json({ message: 'Login successful', user: req.user.toSafeObject() }); + if (!req.user) { + return res.status(401).json({ message: 'Authentication failed' }); + } + res.status(200).json({ message: 'Login successful', user: req.user.toSafeObject() });🤖 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/routes/auth.js` around lines 34 - 36, The login route handler currently assumes req.user exists and calls req.user.toSafeObject(), which can throw if authentication passed control without a user; update the router.post("/login", validateRequest(loginSchema), passport.authenticate('local'), (req, res) => {...}) handler to defensively check for req.user before calling toSafeObject() — if req.user is missing, return a 401/appropriate error JSON (or an object with user: null) and otherwise call req.user.toSafeObject() and return the safe user in the 200 response.backend/models/User.js (1)
34-40: 💤 Low valueConsider using the
idvirtual (string) for consistency.
this._idis a MongooseObjectIdinstance. It serializes to a hex string viaJSON.stringify, but consumers reading the property programmatically (before serialization) get anObjectId, which can cause subtle bugs in strict comparisons. The Mongooseidvirtual returns the string form directly.♻️ Optional refactor
UserSchema.methods.toSafeObject = function () { return { - id: this._id, + id: this.id, username: this.username, email: this.email, }; };🤖 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/models/User.js` around lines 34 - 40, In UserSchema.methods.toSafeObject, replace use of the raw ObjectId this._id with the Mongoose string virtual this.id so the returned id is a JS string; update the toSafeObject method (referencing UserSchema and toSafeObject) to return id: this.id instead of id: this._id and keep username and email unchanged to avoid subtle type/comparison bugs.
🤖 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/routes/auth.js`:
- Line 35: The line currently has a stray '+' character before the response call
causing a unary plus to be applied to res.status(...).json(...); remove the
leading '+' so the statement is simply res.status(200).json({ message: 'Login
successful', user: req.user.toSafeObject() });, ensure req.user.toSafeObject()
remains unchanged, then run the linter/tests to confirm the unary plus is gone
and the response behaves normally.
---
Nitpick comments:
In `@backend/models/User.js`:
- Around line 34-40: In UserSchema.methods.toSafeObject, replace use of the raw
ObjectId this._id with the Mongoose string virtual this.id so the returned id is
a JS string; update the toSafeObject method (referencing UserSchema and
toSafeObject) to return id: this.id instead of id: this._id and keep username
and email unchanged to avoid subtle type/comparison bugs.
In `@backend/routes/auth.js`:
- Around line 34-36: The login route handler currently assumes req.user exists
and calls req.user.toSafeObject(), which can throw if authentication passed
control without a user; update the router.post("/login",
validateRequest(loginSchema), passport.authenticate('local'), (req, res) =>
{...}) handler to defensively check for req.user before calling toSafeObject() —
if req.user is missing, return a 401/appropriate error JSON (or an object with
user: null) and otherwise call req.user.toSafeObject() and return the safe user
in the 200 response.
🪄 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: 5fd9b437-9ec1-440c-9d24-ce72e5d49544
📒 Files selected for processing (2)
backend/models/User.jsbackend/routes/auth.js
|
@mehul-m-prajapati please review and /merge |
|
not required |
Related Issue
Description
Added toSafeObject() method on User model that returns only id,
username, and email. Use it in the /api/auth/login route instead
of sending the raw Mongoose user object which included the
bcrypt-hashed password field.
How Has This Been Tested?
Tested with
Screenshots (if applicable)
Type of Change
Summary by CodeRabbit