Repository navigation
feat: add profile update functionality with Cloudinary integration an… - #5
Conversation
|
Warning Review limit reached
More reviews will be available in 53 minutes and 59 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the 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 credits. 🚦 How do rate 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 see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAdds cookie-parser to Express, a ChangesProfile Update with JWT Auth and Cloudinary Upload
GitHub Sponsors Config
Sequence Diagram(s)sequenceDiagram
participant Client
participant protectRoute
participant updateProfile
participant Cloudinary
participant MongoDB
Client->>protectRoute: PUT /update-profile (jwt cookie + profilePic)
protectRoute->>MongoDB: User.findById(decoded.userId)
MongoDB-->>protectRoute: user doc (no password)
protectRoute->>updateProfile: next() with req.user set
updateProfile->>Cloudinary: uploader.upload(profilePic, {folder, public_id, overwrite})
Cloudinary-->>updateProfile: secure_url
updateProfile->>MongoDB: User.findByIdAndUpdate(userId, {profilePic: secure_url})
MongoDB-->>updateProfile: updated user
updateProfile-->>Client: 200 updated user
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ 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.
Actionable comments posted: 2
🧹 Nitpick comments (2)
backend/src/routes/auth.route.js (1)
18-18: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winReturn a whitelisted user payload from
/check.
protectRouteonly excludespassword; returningreq.userdirectly can expose future internal user fields. Mirror the explicit response shape used byupdateProfile.Proposed fix
-router.get('/check', protectRoute, (req, res) => res.status(200).json(req.user)); +router.get('/check', protectRoute, (req, res) => { + const { _id, username, fullName, email, profilePic } = req.user; + res.status(200).json({ _id, username, fullName, email, profilePic }); +});🤖 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/routes/auth.route.js` at line 18, The /check handler currently returns req.user directly, which can expose internal user fields beyond password; update the router.get('/check', protectRoute, ...) response to use the same explicit whitelisted payload shape as updateProfile. Locate the response construction in the auth route and return only the allowed user properties instead of the full req.user object.backend/src/lib/cloudinary.js (1)
4-8: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winFail fast when Cloudinary credentials are missing.
Cloudinary’s Node SDK expects
cloud_name,api_key, andapi_secretto be configured for SDK uploads; validating them here prevents profile updates from failing later with opaque upload errors. (cloudinary.com)Proposed fix
+const cloudinaryConfig = { + cloud_name: ENV.CLOUDINARY_CLOUD_NAME, + api_key: ENV.CLOUDINARY_API_KEY, + api_secret: ENV.CLOUDINARY_API_SECRET, +}; + +const missingCloudinaryConfig = Object.entries(cloudinaryConfig) + .filter(([, value]) => !value) + .map(([key]) => key); + +if (missingCloudinaryConfig.length > 0) { + throw new Error(`Missing Cloudinary configuration: ${missingCloudinaryConfig.join(', ')}`); +} + cloudinary.config({ - cloud_name: ENV.CLOUDINARY_CLOUD_NAME, - api_key: ENV.CLOUDINARY_API_KEY, - api_secret: ENV.CLOUDINARY_API_SECRET, + ...cloudinaryConfig, });🤖 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/lib/cloudinary.js` around lines 4 - 8, The Cloudinary setup in cloudinary.config currently assumes ENV.CLOUDINARY_CLOUD_NAME, ENV.CLOUDINARY_API_KEY, and ENV.CLOUDINARY_API_SECRET are always present, which can defer failures until upload time. Add a guard in the Cloudinary initialization path to validate these three values before calling cloudinary.config, and throw or fail immediately with a clear error if any are missing. Use the cloudinary.config call and the ENV credential fields as the key locations to update.
🤖 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 120-133: The profile picture upload flow in auth.controller.js
only checks that profilePic is truthy before calling cloudinary.uploader.upload,
so tighten validation in this handler first. In the profile update path where
req.body.profilePic is read, enforce the expected image payload format and a
maximum size before upload, and make sure the express.json body limit matches
that cap if base64 data URIs are supported. Use the existing profilePic
validation and uploadResponse flow to reject invalid or oversized inputs before
reaching Cloudinary.
In `@backend/src/middleware/auth.middleware.js`:
- Around line 11-27: In protectRoute, JWT verification failures from
jwt.verify() are being treated as server errors instead of unauthorized access.
Update the try/catch flow so auth-related verification errors (expired,
malformed, bad signature, invalid token) return a 401 response, while only
unexpected failures fall through to a 500. Keep the check around decoded/user
lookup in protectRoute and preserve the existing unauthorized responses for
invalid tokens and missing users.
---
Nitpick comments:
In `@backend/src/lib/cloudinary.js`:
- Around line 4-8: The Cloudinary setup in cloudinary.config currently assumes
ENV.CLOUDINARY_CLOUD_NAME, ENV.CLOUDINARY_API_KEY, and ENV.CLOUDINARY_API_SECRET
are always present, which can defer failures until upload time. Add a guard in
the Cloudinary initialization path to validate these three values before calling
cloudinary.config, and throw or fail immediately with a clear error if any are
missing. Use the cloudinary.config call and the ENV credential fields as the key
locations to update.
In `@backend/src/routes/auth.route.js`:
- Line 18: The /check handler currently returns req.user directly, which can
expose internal user fields beyond password; update the router.get('/check',
protectRoute, ...) response to use the same explicit whitelisted payload shape
as updateProfile. Locate the response construction in the auth route and return
only the allowed user properties instead of the full req.user object.
🪄 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: 2c772b1c-2ad0-4e75-88f8-7502454757ee
⛔ Files ignored due to path filters (1)
backend/package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (8)
.github/FUNDING.ymlbackend/package.jsonbackend/src/controllers/auth.controller.jsbackend/src/lib/cloudinary.jsbackend/src/lib/env.jsbackend/src/middleware/auth.middleware.jsbackend/src/routes/auth.route.jsbackend/src/server.js
| const { profilePic } = req.body; | ||
| if (!profilePic) { | ||
| return res.status(400).json({ message: 'Profile picture is required' }); | ||
| } | ||
|
|
||
| const userId = req.user._id; | ||
|
|
||
| // Upload the new profile picture to Cloudinary | ||
| const uploadResponse = await cloudinary.uploader.upload(profilePic, { | ||
| folder: 'profile_pics', | ||
| public_id: `user_${userId}`, | ||
| overwrite: true, | ||
| resource_type: 'image' | ||
| }); |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== files =="
git ls-files backend/src/controllers/auth.controller.js backend/src/server.js backend/src/app.js backend/src | sed -n '1,120p'
echo
echo "== controller slice =="
nl -ba backend/src/controllers/auth.controller.js | sed -n '100,170p'
echo
echo "== server/app slice =="
for f in backend/src/server.js backend/src/app.js; do
if [ -f "$f" ]; then
echo "--- $f ---"
nl -ba "$f" | sed -n '1,200p'
fi
done
echo
echo "== search for profilePic validation / express.json limit =="
rg -n "profilePic|express\.json|bodyParser|limit:" backend/src -SRepository: hemjaygfx/NexTalk
Length of output: 637
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== controller slice =="
awk 'NR>=100 && NR<=170 {printf "%d:%s\n", NR, $0}' backend/src/controllers/auth.controller.js
echo
echo "== server slice =="
awk 'NR>=1 && NR<=120 {printf "%d:%s\n", NR, $0}' backend/src/server.js
echo
echo "== related references =="
rg -n "profilePic|express\.json|bodyParser|upload\\(" backend/src -SRepository: hemjaygfx/NexTalk
Length of output: 4181
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== profilePic references =="
rg -n "profilePic" backend/src -S
echo
echo "== user model slice =="
awk 'NR>=1 && NR<=120 {printf "%d:%s\n", NR, $0}' backend/src/models/user.model.jsRepository: hemjaygfx/NexTalk
Length of output: 1632
🌐 Web query:
Cloudinary uploader.upload input sources remote URL base64 data URI documentation
💡 Result:
Cloudinary supports multiple input sources for file uploads, including local paths, remote URLs, and Base64 data URIs [1][2][3]. Remote URLs When providing a remote HTTP or HTTPS URL, Cloudinary fetches the file directly from that location and uploads it to your account [1][4]. This is an efficient method for migrating existing assets [1]. Base64 Data URIs You can upload files by providing their Base64-encoded data URI [1][5]. - Limit: The maximum file size for Base64 data URI uploads is 60 MB [5][6]. For larger files, use a remote URL or standard file stream/path upload methods [5]. - Implementation via SDKs: Most Cloudinary SDKs accept the Data URI string directly as the file argument in their upload methods (e.g., cloudinary.uploader.upload("data:image/png;base64,...")) [1][5]. - Implementation via REST API: If you are making direct HTTP requests without an SDK, the Data URI must be URL-encoded before being sent in the request body (e.g., application/x-www-form-urlencoded) to ensure reserved characters do not break the payload [1][5]. General Upload Best Practices - The file source is specified via the mandatory file parameter in the Upload API [1][4][7]. - When performing direct REST API calls, ensure your credentials (API Key/Secret) are handled securely [4][8]. For client-side uploads, it is recommended to use unsigned uploads with an upload preset to avoid exposing your API Secret [7][8]. [1][5][8]
Citations:
- 1: https://cloudinary.com/documentation/upload_parameters
- 2: https://cloudinary.com/documentation/node_image_and_video_upload
- 3: https://cloudinary.com/documentation/rails_image_and_video_upload
- 4: https://cloudinary.com/documentation/upload%5Fimages
- 5: https://support.cloudinary.com/hc/en-us/articles/203125741-Uploading-assets-using-a-base64-DATA-URI
- 6: https://cloudinary.com/documentation/jquery_image_and_video_upload
- 7: https://cloudinary.com/documentation/upload_images
- 8: https://cloudinary.com/documentation/client_side_uploading
Validate profilePic before uploading.
This handler accepts any truthy body string, and Cloudinary will also accept URLs or base64 data URIs as upload sources. Enforce the expected image format and a size cap here, and align express.json() with that limit if base64 uploads are intended.
🤖 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 120 - 133, The
profile picture upload flow in auth.controller.js only checks that profilePic is
truthy before calling cloudinary.uploader.upload, so tighten validation in this
handler first. In the profile update path where req.body.profilePic is read,
enforce the expected image payload format and a maximum size before upload, and
make sure the express.json body limit matches that cap if base64 data URIs are
supported. Use the existing profilePic validation and uploadResponse flow to
reject invalid or oversized inputs before reaching Cloudinary.
… protectRoute middleware
Summary by CodeRabbit
New Features
Bug Fixes