Skip to content

feat: add backend input validation using Zod for auth routes#279

Open
Likhi2005 wants to merge 2 commits into
GitMetricsLab:mainfrom
Likhi2005:fix/auth-zod-validation
Open

feat: add backend input validation using Zod for auth routes#279
Likhi2005 wants to merge 2 commits into
GitMetricsLab:mainfrom
Likhi2005:fix/auth-zod-validation

Conversation

@Likhi2005
Copy link
Copy Markdown

@Likhi2005 Likhi2005 commented May 16, 2026

Related Issue


Description

This PR adds backend input validation for authentication routes using Zod.

Previously, the application accepted invalid inputs such as malformed emails and weak passwords, which were directly stored in the database. This caused data inconsistency and potential security risks.

This update introduces schema-based validation to ensure all incoming authentication data is properly validated before processing.


Changes Made

  • Added Zod validation schemas for signup and login
  • Implemented reusable validation middleware
  • Added validation for username, email, and password fields
  • Enforced password strength requirements
  • Integrated validation into authentication routes
  • Standardized error response format for validation failures

How Has This Been Tested?

  • Tested signup with invalid email → request rejected
  • Tested weak password → validation error returned
  • Tested invalid username → rejected correctly
  • Tested valid credentials → successful signup/login
  • Verified no invalid data is stored in MongoDB

Screenshots (if applicable)

Invalid Email Test

invalid email

Weak Password Test

weak password


Type of Change

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

Summary by CodeRabbit

  • New Features

    • Signup and login endpoints now include enhanced validation for usernames, emails, and passwords with detailed error feedback.
  • Chores

    • Updated dependencies.

Review Change Stack

@netlify
Copy link
Copy Markdown

netlify Bot commented May 16, 2026

Deploy Preview for github-spy ready!

Name Link
🔨 Latest commit defd38d
🔍 Latest deploy log https://app.netlify.com/projects/github-spy/deploys/6a086063740377000854955b
😎 Deploy Preview https://deploy-preview-279--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 16, 2026

Warning

Rate limit exceeded

@Likhi2005 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 9 minutes and 8 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5988f90b-25c8-4670-8eff-2c4f81037d0d

📥 Commits

Reviewing files that changed from the base of the PR and between 7d07beb and defd38d.

📒 Files selected for processing (3)
  • backend/routes/auth.js
  • backend/validators/authValidator.js
  • backend/validators/validationRequest.js
📝 Walkthrough

Walkthrough

This PR implements schema-based request validation for authentication routes. It adds the Zod validation library, creates validation schemas for signup and login inputs, introduces a middleware factory that validates request bodies and attaches results to req.validated, and integrates validation into the signup and login routes to enforce email format, username constraints, and password complexity before processing.

Changes

Authentication Request Validation

Layer / File(s) Summary
Validation middleware and schemas
backend/package.json, backend/validators/validationRequest.js, backend/validators/authValidator.js
validateRequest(schema) middleware factory validates req.body using Zod's safeParse, returns structured 400 errors on failure, and stores parsed data on req.validated. signupSchema and loginSchema enforce email normalization, username/password length limits, and password complexity rules. Zod dependency added to package.json.
Route middleware integration
backend/routes/auth.js
/signup and /login routes now call validateRequest(signupSchema) and validateRequest(loginSchema) before processing, and destructure validated fields from req.validated instead of req.body.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A hop down validation lane,
Zod schemas guard against the vain,
No faker emails slip on through,
Just solid data, tried and true!
Strong passwords bloom, usernames align,
Backend checks make everything fine!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding backend input validation using Zod for auth routes, which matches the core focus of the changeset.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #274: implements Zod-based validation schemas, creates reusable validation middleware, validates email/username/password fields, enforces password strength, integrates validation into auth routes, and returns structured error responses.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing input validation for authentication routes as specified in issue #274. Backend dependency updates (Zod), validator schemas, middleware, and route integration are all within scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering all required template sections with clear details about the issue being addressed, changes made, testing performed, and relevant screenshots.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

Copy link
Copy Markdown

@github-actions github-actions Bot left a comment

Choose a reason for hiding this comment

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

🎉 Thank you @Likhi2005 for your contribution. Please make sure your PR follows https://github.com/GitMetricsLab/github_tracker/blob/main/CONTRIBUTING.md#-pull-request-guidelines

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.

Actionable comments posted: 5

🧹 Nitpick comments (1)
backend/validators/validationRequest.js (1)

1-1: ⚡ Quick win

Fix inconsistent spacing in function parameters.

The function signature has inconsistent spacing: (req,res, next) should be (req, res, next).

✨ Proposed fix
-const validateRequest = (schema) => (req,res, next) => {
+const validateRequest = (schema) => (req, res, next) => {
🤖 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/validators/validationRequest.js` at line 1, The validateRequest
middleware function signature has inconsistent spacing in its parameters; update
the parameter list in the arrow function for validateRequest from (req,res,
next) to use consistent spacing (req, res, next) so it matches the project's
style and other middleware declarations in validationRequest.js.
🤖 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 28: The login failure is caused because passport.authenticate('local')
reads credentials from req.body while your validateRequest middleware stores the
normalized input in req.validated; update the middleware (validationRequest.js /
validateRequest) to copy the validated data back onto req.body (i.e., set
req.body = req.validated or req.body = result.data after validation) so passport
sees the transformed email, or alternatively adjust the LocalStrategy to read
from req.validated or add a small middleware before
passport.authenticate('local') that copies req.validated into req.body.

In `@backend/validators/authValidator.js`:
- Around line 10-13: The email Zod chain applies .toLowerCase() and .trim()
after .email(), causing format validation to run on unnormalized input; in
authValidator.js update the email schema (the email property using z.string())
to perform .trim() and .toLowerCase() before calling .email(...) so the chain
becomes z.string().trim().toLowerCase().email("Invalid email address") to
normalize input prior to format validation.
- Around line 4-8: The username schema calls .trim() after length and regex
checks so inputs like " user " fail; move .trim() to the start of the chain on
the username z.string() schema so whitespace is removed before .min(), .max(),
and .regex validations (update the username validator definition accordingly to
call .trim() immediately after z.string()).
- Around line 26-29: The loginSchema applies .email() before normalization; move
the string transforms so .trim() and .toLowerCase() are called before .email()
on the email field (matching signupSchema) so validation runs against the
normalized value—update the email chain in loginSchema to call .trim() and
.toLowerCase() first, then .email().
- Around line 18-20: The password regex in authValidator.js (the .regex(...)
call) uses lookaheads correctly but the main pattern only matches a single
allowed character and lacks end anchoring, so update the main pattern to enforce
that the entire string consists only of the allowed character set and is at
least one character long by replacing the trailing token with an anchored
repetition of the allowed character class (i.e., ensure the pattern is wrapped
with ^ and $ and uses a quantifier like + on the [A-Za-z\d@$!%*?&] class) so
emojis or other disallowed characters cannot appear anywhere in the password
while keeping the existing lookaheads for required types.

---

Nitpick comments:
In `@backend/validators/validationRequest.js`:
- Line 1: The validateRequest middleware function signature has inconsistent
spacing in its parameters; update the parameter list in the arrow function for
validateRequest from (req,res, next) to use consistent spacing (req, res, next)
so it matches the project's style and other middleware declarations in
validationRequest.js.
🪄 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: 214fa33e-fb9d-4fa0-9b5b-cf265cec2b61

📥 Commits

Reviewing files that changed from the base of the PR and between 7a15543 and 7d07beb.

📒 Files selected for processing (4)
  • backend/package.json
  • backend/routes/auth.js
  • backend/validators/authValidator.js
  • backend/validators/validationRequest.js

Comment thread backend/routes/auth.js
Comment thread backend/validators/authValidator.js Outdated
Comment thread backend/validators/authValidator.js Outdated
Comment thread backend/validators/authValidator.js
Comment thread backend/validators/authValidator.js Outdated
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.

🐛 Bug Report: Missing Backend Validation for Authentication Fields

1 participant