Skip to content

Fix session cookies with proper CORS and credentialed auth requests#254

Open
ChaitanyaChute wants to merge 4 commits into
GitMetricsLab:mainfrom
ChaitanyaChute:fix/cors
Open

Fix session cookies with proper CORS and credentialed auth requests#254
ChaitanyaChute wants to merge 4 commits into
GitMetricsLab:mainfrom
ChaitanyaChute:fix/cors

Conversation

@ChaitanyaChute
Copy link
Copy Markdown

@ChaitanyaChute ChaitanyaChute commented May 15, 2026

Related Issue


Description

  • Fix backend CORS configuration to allow credentialed requests from the frontend.
  • Ensure login/signup requests send cookies so session persists.

Type of Change

  • Bug fix
  • New feature
  • Code style update
  • Breaking change
  • Documentation update

Summary by CodeRabbit

  • Bug Fixes

    • Signup validation now detects and prevents duplicate usernames in addition to duplicate emails
    • Improved error handling for duplicate user detection with appropriate HTTP responses
    • CORS policy updated to use an explicit origin allowlist for enhanced security
  • Tests

    • Added test case to verify signup properly rejects attempts with existing usernames

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 15, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit 97c7321
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a06f7b234b3c10008523c39
😎 Deploy Preview https://deploy-preview-254--github-spy.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 15, 2026

📝 Walkthrough

Walkthrough

This PR fixes session cookie persistence by implementing credentialed authentication across the stack: the backend now uses an explicit CORS allowlist with credentials enabled, validates signup by both email and username with proper error handling, and the frontend's login and signup requests explicitly send credentials to maintain session state.

Changes

Session Authentication with Credentials and Credentials

Layer / File(s) Summary
Backend signup validation with username uniqueness and error handling
backend/routes/auth.js, spec/auth.routes.spec.cjs
Signup route checks for existing users by either email or username and handles Mongo duplicate-key errors (code 11000) by returning a 400 "User already exists" response. New test case verifies that signup rejects duplicate usernames with a 400 status and appropriate message.
Backend CORS allowlist with credentials
backend/server.js
CORS configuration replaced wildcard origin (cors('*')) with an explicit allowlist parsed from FRONTEND_URL environment variable (comma-separated, trimmed values), and credentials: true is now enabled to support cookie-based session handling.
Frontend API requests with withCredentials
src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx
Login and Signup handlers now explicitly include Axios request option { withCredentials: true } in their POST calls, ensuring session cookies are automatically sent to and received from the backend.
Frontend build stage with dev dependencies
Dockerfile.prod
Build stage now installs all dependencies (dev and production) via npm install instead of npm install --production, ensuring required dev tooling is available during the build process.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Frontend Client
  participant CORS as CORS Middleware
  participant SignupRoute as POST /api/auth/signup
  participant MongoDB as MongoDB

  Client->>CORS: POST signup with credentials
  activate CORS
  CORS->>CORS: Check origin against allowlist
  CORS->>CORS: Allow credentials: true
  CORS->>SignupRoute: Forward request
  deactivate CORS

  activate SignupRoute
  SignupRoute->>MongoDB: Query for email OR username
  activate MongooDB
  alt User found
    MongooDB-->>SignupRoute: Existing user
    SignupRoute-->>Client: 400 "User already exists"
  else User not found
    MongooDB-->>SignupRoute: No match
    SignupRoute->>MongooDB: Insert new user
    MongooDB-->>SignupRoute: Success
    SignupRoute-->>Client: 201 Created + set-cookie
  end
  deactivate MongooDB
  deactivate SignupRoute
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • GitMetricsLab/github_tracker#91: Both PRs modify the frontend production Docker build flow in Dockerfile.prod—specifically the dependency install step (prod-only vs installing all deps)—so the changes directly overlap in the same file/build stage.

Suggested reviewers

  • mehul-m-prajapati

Poem

🐰 A rabbit's hop toward trust and time,
With cookies set in perfect rhyme,
Credentials sent, origins clear,
Sessions now persist right here!
Username guard keeps duplicates out,
No more lost auth—that's what we're about! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Out of Scope Changes check ❓ Inconclusive Additional changes in backend/routes/auth.js (username duplicate check), Dockerfile.prod (dev dependencies), and spec/auth.routes.spec.cjs (new test) are related to auth robustness but extend beyond the core session-cookies issue. Clarify whether the username validation, Dockerfile changes, and new test case are necessary for the session cookie fix or represent scope creep.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: fixing session cookies by implementing proper CORS configuration and enabling credentialed auth requests.
Description check ✅ Passed The description covers the main objectives (CORS fix and credentialed requests) and specifies bug fix type, though testing details section is missing.
Linked Issues check ✅ Passed The PR addresses issue #249's requirements: CORS configured with explicit origin allowlist and credentials enabled [backend/server.js], and frontend requests now include withCredentials flag [src/pages/Login/Login.tsx, src/pages/Signup/Signup.tsx].
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 and usage tips.

@ChaitanyaChute ChaitanyaChute changed the title Fix/cors Fix session cookies with proper CORS and credentialed auth requests May 15, 2026
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/pages/Signup/Signup.tsx (1)

40-56: ⚡ Quick win

Consider removing the commented-out mock implementation.

The old mock code and TODO comments are no longer needed since the real backend integration is now working. Removing dead code improves maintainability.

🧹 Proposed cleanup
-    
-    // // Simulate API call (replace with your actual backend integration)
-    // try {
-    //   // Mock successful signup
-    //   setMessage("Account created successfully! Redirecting to login...");
-      
-    //   // In your actual implementation, integrate with your backend here:
-    //   // const response = await fetch(`${backendUrl}/api/auth/signup`, {
-    //   //   method: 'POST',
-    //   //   headers: { 'Content-Type': 'application/json' },
-    //   //   body: JSON.stringify(formData)
-    //   // });
-      
-    //   setTimeout(() => {
-    //     // Navigate to login page in your actual implementation
-    //     console.log("Redirecting to login page...");
-    //   }, 2000);
-      
     } catch (error) {
       setMessage("Something went wrong. Please try again.");
     }
🤖 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 `@src/pages/Signup/Signup.tsx` around lines 40 - 56, Remove the dead
commented-out mock signup flow in Signup.tsx: delete the block that simulates
the API call and the setTimeout/console.log redirect (the commented lines
referencing setMessage, formData, and the mock fetch), leaving only the real
backend integration in the signup handler (e.g., the actual fetch/POST logic and
subsequent setMessage/navigation). Ensure no leftover TODOs or commented code
related to the old mock remain.
🤖 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.

Nitpick comments:
In `@src/pages/Signup/Signup.tsx`:
- Around line 40-56: Remove the dead commented-out mock signup flow in
Signup.tsx: delete the block that simulates the API call and the
setTimeout/console.log redirect (the commented lines referencing setMessage,
formData, and the mock fetch), leaving only the real backend integration in the
signup handler (e.g., the actual fetch/POST logic and subsequent
setMessage/navigation). Ensure no leftover TODOs or commented code related to
the old mock remain.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f369502f-c36b-422e-a280-f53d5dc44797

📥 Commits

Reviewing files that changed from the base of the PR and between 56e17a3 and 97c7321.

📒 Files selected for processing (6)
  • Dockerfile.prod
  • backend/routes/auth.js
  • backend/server.js
  • spec/auth.routes.spec.cjs
  • src/pages/Login/Login.tsx
  • src/pages/Signup/Signup.tsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug Report: Session cookies are not persisted due to incorrect CORS setup and missing credentials in frontend requests

1 participant