Skip to content

feat(auth): add centralized request validation and input sanitization for authentication endpoints#61

Open
om-dev007 wants to merge 1 commit into
rishabhx29:mainfrom
om-dev007:fix/issue-55-add-validation-and-input-sanitization
Open

feat(auth): add centralized request validation and input sanitization for authentication endpoints#61
om-dev007 wants to merge 1 commit into
rishabhx29:mainfrom
om-dev007:fix/issue-55-add-validation-and-input-sanitization

Conversation

@om-dev007

@om-dev007 om-dev007 commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Description

This PR adds centralized request validation and input sanitization for authentication endpoints using express-validator.

Changes Made

  • Added reusable validation middleware for authentication routes.
  • Validated required fields for registration and login requests.
  • Enforced proper email format validation.
  • Added minimum password length validation.
  • Trimmed leading and trailing whitespace from user inputs.
  • Normalized email addresses before processing.
  • Introduced a centralized validation error handler to return consistent error responses.
  • Removed redundant validation logic from the authentication controller, making it cleaner and easier to maintain.

Benefits

  • Prevents malformed or invalid input from reaching the controller.
  • Improves data integrity and consistency.
  • Provides clear and consistent validation error messages.
  • Makes validation logic reusable across authentication endpoints.
  • Simplifies controller logic and improves maintainability.

Closes #55

Summary by CodeRabbit

  • New Features

    • Added stricter form validation for sign-up and login requests, including checks for required fields, email format, and password length.
  • Bug Fixes

    • Requests with missing or invalid account details now return clear validation errors instead of continuing with account creation or login attempts.
    • Improved consistency of error responses when input does not meet requirements.

@vercel

vercel Bot commented Jun 29, 2026

Copy link
Copy Markdown

@om-dev007 is attempting to deploy a commit to the rishabhjtripathi2903-3434's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds express-validator as a dependency and a new validationMiddleware.ts module exporting registerValidation, loginValidation, and validateRequest. These are wired into the POST / and POST /login auth routes before their controller handlers. The inline "all fields required" check is removed from registerUser.

Auth Request Validation

Layer / File(s) Summary
Validation rules and validateRequest middleware
backend/src/middleware/validationMiddleware.ts
Defines registerValidation (name 2–50 chars, valid email, password ≥ 8 chars) and loginValidation rule arrays, plus validateRequest middleware that returns HTTP 400 with { success: false, errors: [{ field, message }] } on failure or calls next().
Route wiring, controller cleanup, and dependency
backend/src/routes/authRoutes.ts, backend/src/controllers/authController.ts, backend/package.json
Auth routes now include the validation middleware before registerUser and loginUser. The redundant inline field presence check is removed from registerUser. express-validator ^7.3.2 is added to dependencies.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hoppity-hop, the fields are now checked,
No empty emails shall pass unchecked!
With trimmed little strings and a password of eight,
The middleware bunny guards every gate.
Invalid inputs? A 400 they'll meet —
The warren is safe and the data is neat! 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: centralized validation and sanitization for auth endpoints.
Linked Issues check ✅ Passed The PR implements reusable auth validation, sanitization, and consistent error handling as requested in #55.
Out of Scope Changes check ✅ Passed The changes stay within the auth validation scope and do not introduce unrelated functionality.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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.

@om-dev007

Copy link
Copy Markdown
Contributor Author

@Rishabhworkspace please review this pr

@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

🤖 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/middleware/validationMiddleware.ts`:
- Around line 8-28: The validation chains in validationMiddleware should stop
after the first failure so a single bad field does not emit multiple errors. Add
.bail() in each body('name'), body('email'), and body('password') chain after
the required check and before the type/length checks, and apply the same pattern
to the other validation block referenced by this review so the centralized error
payload stays one-error-per-field.
- Around line 43-46: The password validator in validationMiddleware only checks
for non-empty input, so short passwords still reach loginUser and the downstream
Prisma/bcrypt flow. Update the existing password rule used by the auth login
validation to enforce the same minimum length floor as registration, while
keeping the current empty check and message behavior. Use the body('password')
validator chain in validationMiddleware to add the length constraint so invalid
short passwords are rejected before controller/database work.
🪄 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 Plus

Run ID: 036e1ffe-e8dc-499f-ae7e-c02f18198e8f

📥 Commits

Reviewing files that changed from the base of the PR and between 8e41fd8 and bbcacf3.

⛔ Files ignored due to path filters (1)
  • backend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • backend/package.json
  • backend/src/controllers/authController.ts
  • backend/src/middleware/validationMiddleware.ts
  • backend/src/routes/authRoutes.ts
💤 Files with no reviewable changes (1)
  • backend/src/controllers/authController.ts

Comment on lines +8 to +28
body('name')
.trim()
.notEmpty()
.withMessage('Name is required')
.isLength({ min: 2, max: 50 })
.withMessage('Name must be between 2 and 50 characters'),

body('email')
.trim()
.notEmpty()
.withMessage('Email is required')
.isEmail()
.withMessage('Please provide a valid email address')
.normalizeEmail(),

body('password')
.trim()
.notEmpty()
.withMessage('Password is required')
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters long'),

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Stop each validation chain after the first failure.

Without .bail(), whitespace-only name, email, or password values can produce multiple errors for the same field (required plus invalid/too short). That makes the centralized error payload less consistent than intended.

Suggested fix
 export const registerValidation = [
     body('name')
         .trim()
         .notEmpty()
         .withMessage('Name is required')
+        .bail()
         .isLength({ min: 2, max: 50 })
         .withMessage('Name must be between 2 and 50 characters'),

     body('email')
         .trim()
         .notEmpty()
         .withMessage('Email is required')
+        .bail()
         .isEmail()
         .withMessage('Please provide a valid email address')
         .normalizeEmail(),

     body('password')
         .trim()
         .notEmpty()
         .withMessage('Password is required')
+        .bail()
         .isLength({ min: 8 })
         .withMessage('Password must be at least 8 characters long'),
 ];

 export const loginValidation = [
     body('email')
         .trim()
         .notEmpty()
         .withMessage('Email is required')
+        .bail()
         .isEmail()
         .withMessage('Please provide a valid email address')
         .normalizeEmail(),

     body('password')
         .trim()
         .notEmpty()
         .withMessage('Password is required')
 ];

Also applies to: 35-46

🤖 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/middleware/validationMiddleware.ts` around lines 8 - 28, The
validation chains in validationMiddleware should stop after the first failure so
a single bad field does not emit multiple errors. Add .bail() in each
body('name'), body('email'), and body('password') chain after the required check
and before the type/length checks, and apply the same pattern to the other
validation block referenced by this review so the centralized error payload
stays one-error-per-field.

Comment on lines +43 to +46
body('password')
.trim()
.notEmpty()
.withMessage('Password is required'),

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Enforce the password length floor on login too.

Line 43-46 only reject empty passwords, so short values still reach loginUser and trigger the Prisma lookup / bcrypt compare path. That misses the stated auth-endpoint contract of keeping low-quality input out of the controller/database.

Suggested fix
 export const loginValidation = [
     body('email')
         .trim()
         .notEmpty()
         .withMessage('Email is required')
         .isEmail()
         .withMessage('Please provide a valid email address')
         .normalizeEmail(),

     body('password')
         .trim()
         .notEmpty()
-        .withMessage('Password is required'),
+        .withMessage('Password is required')
+        .bail()
+        .isLength({ min: 8 })
+        .withMessage('Password must be at least 8 characters long'),
 ];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
body('password')
.trim()
.notEmpty()
.withMessage('Password is required'),
body('password')
.trim()
.notEmpty()
.withMessage('Password is required')
.bail()
.isLength({ min: 8 })
.withMessage('Password must be at least 8 characters long'),
🤖 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/middleware/validationMiddleware.ts` around lines 43 - 46, The
password validator in validationMiddleware only checks for non-empty input, so
short passwords still reach loginUser and the downstream Prisma/bcrypt flow.
Update the existing password rule used by the auth login validation to enforce
the same minimum length floor as registration, while keeping the current empty
check and message behavior. Use the body('password') validator chain in
validationMiddleware to add the length constraint so invalid short passwords are
rejected before controller/database work.

@vercel

vercel Bot commented Jul 4, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
algo-forge-2-0 Ready Ready Preview, Comment Jul 4, 2026 9:11am

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.

Add Request Validation and Input Sanitization for Authentication Endpoints

2 participants