Skip to content

fix(auth): specific error messages and strong password validation (#67)#77

Open
sricharan12-hub wants to merge 1 commit into
niharika-mente:mainfrom
sricharan12-hub:SriCharan12
Open

fix(auth): specific error messages and strong password validation (#67)#77
sricharan12-hub wants to merge 1 commit into
niharika-mente:mainfrom
sricharan12-hub:SriCharan12

Conversation

@sricharan12-hub

@sricharan12-hub sricharan12-hub commented Jun 27, 2026

Copy link
Copy Markdown

Description

Fixes #67

Improves the authentication system by providing clear, specific error messages and enforcing a strong password policy.

Changes

1. Specific error for unregistered email during login

  • Login now returns 404 with: "This email address is not registered. Please create an account first." when the email does not exist.
  • A wrong password now returns a distinct 401: "Invalid email or password. Please try again."

2. Specific error for duplicate email registration

  • Register checks for an existing user before creating and returns 409 with: "This email is already registered. Please sign in or use a different email address."
  • Added a code === 11000 fallback to handle the unique-index race condition gracefully.

3. Strong password validation

Enforced on both the backend validator and the signup form:

  • Minimum 8 characters
  • At least one uppercase letter (A–Z)
  • At least one lowercase letter (a–z)
  • At least one number (0–9)
  • At least one special character

Each rule reports its own clear validation message.

Additional fix

AuthContext previously swallowed API errors and returned false, so the specific catch handlers in Login.jsx / Signup.jsx never ran and users always saw a generic message. Errors now propagate, and both pages display the backend's specific message. Emails are also normalized to lowercase/trimmed for consistent lookups.

Testing

  • Backend files pass node --check.
  • Manually verified the error paths (unregistered email, wrong password, duplicate registration, weak passwords).

Summary by CodeRabbit

  • New Features
    • Password requirements are now stronger during sign-up, with clearer guidance shown on the form.
  • Bug Fixes
    • Email addresses are now handled consistently during sign-up and sign-in.
    • Duplicate account attempts now return a clearer “email already registered” response.
    • Login and registration errors now surface more relevant messages from the server when available.
  • Security
    • Password validation now requires 8+ characters plus uppercase, lowercase, a number, and a special character.

…harika-mente#67)

- Login: return 404 with a clear message when the email is not registered,
  and 401 specifically for an incorrect password
- Register: detect duplicate emails before creation and return 409 with a
  clear message; handle the unique-index race condition as a fallback
- Enforce a strong password policy (min 8 chars, upper, lower, number,
  special character) on both the backend validator and the signup form
- Stop AuthContext from swallowing API errors so pages can show the
  backend's specific error message
- Normalize emails to lowercase/trimmed for consistent lookups
@coderabbitai

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Password rules are tightened in both backend and signup UI, emails are normalized during auth, and login/register errors now prefer backend messages while the backend returns explicit duplicate, credential, and server responses.

Changes

Auth validation and error flow

Layer / File(s) Summary
Password policy and signup constraints
backend/src/Utils/Validetor.js, frontend/src/pages/Signup.jsx
Validate now requires 8+ characters with uppercase, lowercase, number, and special character, and the signup form mirrors that rule in client validation, minLength, and helper text.
Register normalization and duplicate handling
backend/src/controllers/userAuth.js
register trims and lowercases email before lookup and save, and duplicate-key write errors return a 409 response.
Login request handling
backend/src/controllers/userAuth.js
login now validates required fields, normalizes email before lookup, returns 404 or 401 for missing users and bad passwords, and sends a generic 500 on unexpected failures.
AuthContext request outcome
frontend/src/context/AuthContext.jsx
register and login return boolean success from the API response and let request errors propagate to the caller.
Login and signup error copy
frontend/src/pages/Login.jsx, frontend/src/pages/Signup.jsx
Both pages now prefer backend-provided error messages and fall back to generic messages instead of status-based branches.

Sequence Diagram(s)

sequenceDiagram
  participant Signup.jsx
  participant AuthContext
  participant userAuth.js
  participant MongoDB
  Signup.jsx->>AuthContext: register(email, password)
  AuthContext->>userAuth.js: POST /auth/register
  userAuth.js->>MongoDB: normalize email and check existing user
  MongoDB-->>userAuth.js: existing user or none
  userAuth.js->>MongoDB: save new user
  MongoDB-->>userAuth.js: success or duplicate key
  userAuth.js-->>AuthContext: 201, 409, or 400 response
  AuthContext-->>Signup.jsx: true / false or API error
Loading
sequenceDiagram
  participant Login.jsx
  participant AuthContext
  participant userAuth.js
  participant MongoDB
  Login.jsx->>AuthContext: login(email, password)
  AuthContext->>userAuth.js: POST /auth/login
  userAuth.js->>MongoDB: lookup normalized email
  MongoDB-->>userAuth.js: user record or none
  userAuth.js->>userAuth.js: compare password
  userAuth.js-->>AuthContext: 200, 404, 401, or 500 response
  AuthContext-->>Login.jsx: true / false or API error
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • Issue 67 — updates password rules and auth error handling across signup and login flows.

Poem

Hop hop, the bunny typed with care,
Stronger passwords now sniff the air.
Emails trimmed, errors speak true,
Then login hops cleanly through.

🚥 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 summarizes the main auth changes: specific error messages and stronger password validation.
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.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 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/userAuth.js`:
- Around line 52-63: The registration error handler in userAuth.js is logging
the full exception object, which can expose user identifiers on expected
duplicate-key failures. Update the catch block in the registration flow to
remove console.log("FULL ERROR:", err) and log only minimal safe fields from err
when needed, while keeping the existing duplicate-email handling in the same
catch path.
- Around line 16-20: The auth endpoints in userAuth should not reveal whether an
email is registered; unify the public failure responses for signup
duplicate-email handling and login 404/401 cases into one generic
message/status. Update the signup and login branches in the relevant controller
methods so anonymous callers always get the same generic auth failure response,
and move any account-specific guidance into separate out-of-band recovery flows.

In `@backend/src/Utils/Validetor.js`:
- Around line 11-15: The email validation in Validate currently checks the raw
input before normalization, so addresses with surrounding spaces or mixed case
can fail even though register later trims/lowercases them. Update Validate in
Validetor.js to normalize the email value before the emailRegex test, or ensure
userAuth.register passes a trimmed/lowercased email into Validate so the
validation matches the lookup behavior. Use the existing Validate and register
flow as the entry points to locate the fix.

In `@frontend/src/pages/Login.jsx`:
- Around line 42-47: The fallback in Login’s error handling is too
credential-specific for failures where Axios has no response. Update the error
path in Login.jsx so the backend-provided message is still used when available,
but the default message in the setError branch becomes a neutral retry message
for non-response failures. Keep the change localized to the Login component’s
error handling logic.
🪄 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: 1e13a99f-7077-4e00-8d12-a9c696bf2af6

📥 Commits

Reviewing files that changed from the base of the PR and between d3e42fd and ab6dccd.

📒 Files selected for processing (5)
  • backend/src/Utils/Validetor.js
  • backend/src/controllers/userAuth.js
  • frontend/src/context/AuthContext.jsx
  • frontend/src/pages/Login.jsx
  • frontend/src/pages/Signup.jsx

Comment on lines +16 to +20
return res.status(409).json({
success: false,
error:
"This email is already registered. Please sign in or use a different email address.",
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Use a generic public auth failure response.

The duplicate-email 409 on signup plus the 404/401 split on login lets anonymous callers verify which email addresses are registered. Keep one generic message/status for public auth failures, and move account-specific guidance to out-of-band flows.

Also applies to: 56-61, 87-100

🤖 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/userAuth.js` around lines 16 - 20, The auth endpoints
in userAuth should not reveal whether an email is registered; unify the public
failure responses for signup duplicate-email handling and login 404/401 cases
into one generic message/status. Update the signup and login branches in the
relevant controller methods so anonymous callers always get the same generic
auth failure response, and move any account-specific guidance into separate
out-of-band recovery flows.

Comment on lines 52 to +63
} catch (err) {
console.log("FULL ERROR:", err);

// Handle duplicate email (race condition / unique index violation)
if (err.code === 11000) {
return res.status(409).json({
success: false,
error:
"This email is already registered. Please sign in or use a different email address.",
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Avoid logging the full registration exception.

Duplicate-key errors commonly include the conflicting email in their payload/message, so console.log("FULL ERROR:", err) can leak user identifiers into server logs on a normal path. Log only the minimal fields you need.

🤖 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/userAuth.js` around lines 52 - 63, The registration
error handler in userAuth.js is logging the full exception object, which can
expose user identifiers on expected duplicate-key failures. Update the catch
block in the registration flow to remove console.log("FULL ERROR:", err) and log
only minimal safe fields from err when needed, while keeping the existing
duplicate-email handling in the same catch path.

Comment on lines +11 to 15
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error("Invalid email format");
}

Copy link
Copy Markdown

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

Normalize the email before this regex check.

register trims/lowercases the address later in backend/src/controllers/userAuth.js, but Validate(req.body) runs first, so " user@example.com " is still rejected here as invalid. Validate the trimmed value here, or normalize before calling Validate, so signup matches the new lookup behavior.

🤖 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/Utils/Validetor.js` around lines 11 - 15, The email validation in
Validate currently checks the raw input before normalization, so addresses with
surrounding spaces or mixed case can fail even though register later
trims/lowercases them. Update Validate in Validetor.js to normalize the email
value before the emailRegex test, or ensure userAuth.register passes a
trimmed/lowercased email into Validate so the validation matches the lookup
behavior. Use the existing Validate and register flow as the entry points to
locate the fix.

Comment on lines +42 to 47
// Prefer the specific message returned by the backend (e.g. unregistered
// email vs. wrong password); fall back to a generic message otherwise.
if (errorMsg) {
setError(errorMsg);
} else {
setError("Login failed. Please check your credentials.");

Copy link
Copy Markdown

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

Use a neutral fallback for non-response failures.

When Axios fails before a response exists, this path shows “Please check your credentials,” even for offline/CORS/timeout errors. A neutral fallback like “Login failed. Please try again.” is less misleading.

Suggested change
-        setError("Login failed. Please check your credentials.");
+        setError("Login failed. Please try again.");
📝 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
// Prefer the specific message returned by the backend (e.g. unregistered
// email vs. wrong password); fall back to a generic message otherwise.
if (errorMsg) {
setError(errorMsg);
} else {
setError("Login failed. Please check your credentials.");
// Prefer the specific message returned by the backend (e.g. unregistered
// email vs. wrong password); fall back to a generic message otherwise.
if (errorMsg) {
setError(errorMsg);
} else {
setError("Login failed. Please try again.");
🧰 Tools
🪛 ast-grep (0.44.0)

[warning] 44-44: Avoid using the initial state variable in setState
Context: setError(errorMsg)
Note: [CWE-710] Improper Adherence to Coding Standards. Security best practice.

(setstate-same-var)

🤖 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 `@frontend/src/pages/Login.jsx` around lines 42 - 47, The fallback in Login’s
error handling is too credential-specific for failures where Axios has no
response. Update the error path in Login.jsx so the backend-provided message is
still used when available, but the default message in the setError branch
becomes a neutral retry message for non-response failures. Keep the change
localized to the Login component’s error handling logic.

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.

Improve Authentication Error Handling and Password Validatio

1 participant