Skip to content

feat: add profile update functionality with Cloudinary integration an… - #5

Merged
hemjaygfx merged 3 commits into
mainfrom
update-profile
Jun 28, 2026
Merged

hemjaygfx merged 3 commits into
mainfrom
update-profile

Conversation

@hemjaygfx

@hemjaygfx hemjaygfx commented Jun 28, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added profile picture updates so users can upload and save a new avatar.
    • Added a protected account check endpoint to confirm the current signed-in user.
    • Enabled cookie-based session handling for authenticated requests.
  • Bug Fixes

    • Improved route protection so secured actions require a valid login session.
    • Added backend support for image hosting and profile image storage.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@hemjaygfx, we couldn't start this review because you've reached your PR review rate limit.

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 @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 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 configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ef11604a-64c1-491c-97e2-09534b2e27a7

📥 Commits

Reviewing files that changed from the base of the PR and between 7332599 and 7d1ab9c.

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

Walkthrough

Adds cookie-parser to Express, a protectRoute JWT middleware, Cloudinary SDK initialization with new env vars, an updateProfile controller that uploads a base64 image to Cloudinary and persists the URL, and two new protected auth routes (PUT /update-profile, GET /check). Also sets a GitHub Sponsors username.

Changes

Profile Update with JWT Auth and Cloudinary Upload

Layer / File(s) Summary
Cookie parser and env config
backend/src/server.js, backend/src/lib/env.js, backend/package.json
cookie-parser is imported and registered on Express; CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, and CLOUDINARY_API_SECRET are added to the ENV object; cloudinary ^2.5.1 added to dependencies.
Cloudinary SDK module
backend/src/lib/cloudinary.js
New module reads Cloudinary credentials from ENV, configures the v2 SDK, and exports the configured client.
JWT protectRoute middleware
backend/src/middleware/auth.middleware.js
New middleware reads req.cookies.jwt, verifies the token, loads the user (excluding password), sets req.user, and returns 401/500 on failure.
updateProfile controller and route wiring
backend/src/controllers/auth.controller.js, backend/src/routes/auth.route.js
Adds updateProfile that validates profilePic, uploads to Cloudinary with a deterministic public_id, persists secure_url, and returns updated user. Routes PUT /update-profile and GET /check are registered behind protectRoute.

GitHub Sponsors Config

Layer / File(s) Summary
Funding username
.github/FUNDING.yml
Sets the github sponsors entry to Ifeanyichukwu2277.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 Hop hop, a profile pic takes flight,
Up to the cloud on a Cloudinary kite,
JWT guards the warren's gate,
Cookies checked before it's too late,
The bunny updates, looking just right! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: profile update functionality with Cloudinary integration.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch update-profile

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: 2

🧹 Nitpick comments (2)
backend/src/routes/auth.route.js (1)

18-18: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Return a whitelisted user payload from /check.

protectRoute only excludes password; returning req.user directly can expose future internal user fields. Mirror the explicit response shape used by updateProfile.

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 win

Fail fast when Cloudinary credentials are missing.

Cloudinary’s Node SDK expects cloud_name, api_key, and api_secret to 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

📥 Commits

Reviewing files that changed from the base of the PR and between f78f74b and 7332599.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • .github/FUNDING.yml
  • backend/package.json
  • backend/src/controllers/auth.controller.js
  • backend/src/lib/cloudinary.js
  • backend/src/lib/env.js
  • backend/src/middleware/auth.middleware.js
  • backend/src/routes/auth.route.js
  • backend/src/server.js

Comment on lines +120 to +133
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'
});

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.

🔒 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 -S

Repository: 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 -S

Repository: 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.js

Repository: 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:


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.

@hemjaygfx
hemjaygfx merged commit 3eba0b2 into main Jun 28, 2026
1 check 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.

1 participant