Skip to content

Conversation

anshifmonz
Copy link

Description

Currently, all three authentication-related endpoints (/api/users, /api/users/login, and /api/user) accept any string for the email field and only check existence against the database. This fix adds early-format email validation to all three endpoints.

Since we already enforce a correct email format at registration, it’s redundant (and wasteful) to hit the database every time with an obviously malformed value. This change:

  • Adds early-format validation to the three endpoints
  • Short-circuits invalid requests with a 422 response before any DB lookup
  • Improves performance by avoiding unnecessary database calls
  • Standardizes error messaging for all auth routes

What’s Changed

  1. /api/users (register) endpoint

    • Added email format check using email-validator
    • Returns 422 Unprocessable Entity +
      {
        "errors": {
          "email": ["is invalid"]
        }
      }
      if validation fails
  2. /api/users/login (login) endpoint

    • Moved DB lookup logic after the new format validation
    • Early exit with 422 Unprocessable Entity + same errors payload if email is malformed
  3. /api/user (update user) endpoint

    • Added format check for any incoming email in the update payload
    • Early exit with 422 Unprocessable Entity + same errors payload if malformed
  4. Dependency updates

    • Installed email-validator via npm install email-validator
    • Updated package.json & package-lock.json

How to Test

  • Register

    curl -X POST http://localhost:3000/api/users \
      -H "Content-Type: application/json" \
      -d '{"user": {"email": "bad-email", "username": "user", "password": "passwd"}}'
    # 422, {"errors":{"email":["is invalid"]}}
    
  • LogIn

    curl -X POST http://localhost:3000/api/users/login \
      -H "Content-Type: application/json" \
      -d '{"user": {"email": "bad-email", "password": "passwd"}}'
    # 422, {"errors":{"email":["is invalid"]}}
  • Update User

    curl -X PUT http://localhost:3000/api/user \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer <YOUR_JWT_TOKEN>" \
      -d '{"user": {"email": "bad-email"}}'
    # 422, {"errors":{"email":["is invalid"]}}

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