Skip to content

Add email validation#29

Open
numbpill3d wants to merge 2 commits intomainfrom
codex/add-regex-check-for-email-validation
Open

Add email validation#29
numbpill3d wants to merge 2 commits intomainfrom
codex/add-regex-check-for-email-validation

Conversation

@numbpill3d
Copy link
Copy Markdown
Collaborator

@numbpill3d numbpill3d commented Jun 8, 2025

Summary

  • validate email with regex in registration route
  • fix index route test mocks
  • add tests for invalid email registration

Testing

  • npm test --silent (fails: process.exit due to missing Supabase env vars)

https://chatgpt.com/codex/tasks/task_e_6845015110b8832f99dd0d3eaafb1b47

Summary by Sourcery

Add email format verification to the user registration flow and update tests to cover invalid emails and reflect changes in index route model mocks

New Features:

  • Validate user email format during registration

Tests:

  • Add unit test for invalid email registration
  • Update index route tests to include new model mocks, rename Item to ScrapyardItem, and add countDocuments and lastActive fields

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Jun 8, 2025

Reviewer's Guide

Implements regex-based email validation in the user registration route with accompanying tests and updates index route test mocks to reflect new model fields and rename changes.

Sequence diagram for email validation in registration

sequenceDiagram
    actor User
    participant RegistrationRoute as "POST /register"
    participant EmailValidationLogic as "Email Validation (Regex)"

    User->>RegistrationRoute: Submit registration form (email, username, etc.)
    activate RegistrationRoute
    RegistrationRoute->>EmailValidationLogic: Validate emailFormat(email)
    activate EmailValidationLogic
    alt Invalid Email Format
        EmailValidationLogic-->>RegistrationRoute: Invalid
        RegistrationRoute->>RegistrationRoute: errors.push({ msg: 'Invalid email address' })
    else Valid Email Format
        EmailValidationLogic-->>RegistrationRoute: Valid
    end
    deactivate EmailValidationLogic
    %% Other validations (username, customGlyph) are checked here
    alt Errors present (e.g., invalid email)
        RegistrationRoute-->>User: HTTP Response (e.g., 400 with errors)
    else No errors
        RegistrationRoute-->>User: HTTP Response (e.g., 201 Account Created)
    end
    deactivate RegistrationRoute
Loading

File-Level Changes

Change Details Files
Refine index route test mocks to include additional model fields and counts
  • Added lastActive property to mock user records
  • Introduced countDocuments and find mocks for User model
  • Renamed Item mock to ScrapyardItem and added its countDocuments mock
tests/server/routes/index.test.js
Add regex-based email format validation in registration route
  • Apply standard email regex to submitted email
  • Push an 'Invalid email address' error on failure
server/routes/users.js
Introduce tests for invalid email registration
  • Created POST /users/register invalid email test case
  • Verify error view and message for malformed email
tests/server/routes/users.test.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Comment on lines +68 to +69
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errors.push({ msg: 'Invalid email address' });
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.

The email validation regex used here is quite basic and may not accurately validate all valid email formats, potentially rejecting valid emails. Consider using a more robust regex pattern or a dedicated library for email validation to improve accuracy and user experience.

For example, using a library like validator:

const validator = require('validator');
if (email && !validator.isEmail(email)) {
    errors.push({ msg: 'Invalid email address' });
}

Comment on lines 73 to 74
if (customGlyph && customGlyph.length > 2) {
errors.push({ msg: 'Custom glyph must be at most 2 characters' });
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.

The validation for customGlyph only checks the length but does not sanitize or escape the input, which could lead to security vulnerabilities if harmful input is submitted. To enhance security, consider implementing input sanitization for customGlyph.

For example, using a library like sanitize-html:

const sanitizeHtml = require('sanitize-html');
customGlyph = sanitizeHtml(customGlyph);

Comment on lines +10 to +15
{ username: 'testuser1', displayName: 'Test User 1', lastActive: new Date() },
{ username: 'testuser2', displayName: 'Test User 2', lastActive: new Date() }
]),
countDocuments: jest.fn().mockResolvedValue(2),
find: jest.fn().mockResolvedValue([
{ username: 'testuser1', lastActive: new Date() }
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.

The use of new Date() within the mocked return values for findRecent and find methods introduces non-deterministic behavior in tests. Each invocation of new Date() generates a new timestamp, which can lead to inconsistent test results if the exact time of object creation becomes relevant in assertions or logic.

Recommendation:
To ensure consistent test outcomes, consider using a fixed timestamp or a mocking library like jest.useFakeTimers() to control time-related functions. This approach will make the tests deterministic and more reliable.

password2: 'password'
});

expect(response.status).toBe(200);
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.

The test expects a HTTP 200 status code even when the email provided is invalid. Typically, a 4xx status code (e.g., 400 Bad Request) should be used to indicate client-side input errors. Using HTTP 200 might be misleading as it indicates a successful request.

Recommendation: Modify the expected status code to reflect client errors appropriately, such as expecting a 400 status code for invalid inputs.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @numbpill3d - I've reviewed your changes - here's some feedback:

  • The email regex is very simplistic—consider using a well-tested validator library or a more RFC-compliant pattern to avoid edge cases.
  • Add tests for valid email inputs to ensure that legitimate addresses are accepted as well as invalid ones.
  • Extract the email validation logic into a reusable helper or middleware to keep the registration handler more focused.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟡 Testing: 1 issue found
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}

// Validate email format
if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
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.

suggestion: Consider using a dedicated email validation utility

Custom regex may miss edge cases. Using a library like validator.js ensures more reliable and comprehensive email validation.

Suggested implementation:

  // Validate email format
  const validator = require('validator');
  if (email && !validator.isEmail(email)) {
    errors.push({ msg: 'Invalid email address' });
  }

If validator is not already installed in your project, you will need to run:

npm install validator

Also, ensure that the require('validator') statement is only added once at the top of the file if not already present.

app.use((req, res, next) => {
req.flash = jest.fn();
next();
});
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.

suggestion (testing): Add a test case to ensure valid emails pass the format validation.

Including a test with a valid email, such as [email protected], will confirm that the validation allows correct formats and does not trigger errors for valid input.

Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@@ -64,6 +64,12 @@ router.post('/register', async (req, res) => {
errors.push({ msg: 'Username can only contain letters, numbers, underscores, and hyphens' });
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.

The regex used for username validation (/^[a-zA-Z0-9_-]+$/) is very restrictive, only allowing alphanumeric characters, underscores, and hyphens. This might be unnecessarily limiting for users who wish to use other characters in their usernames, such as periods or spaces. Consider relaxing this restriction if your application context allows for more diverse username characters.

For example, allowing periods and spaces:

if (username && !/^[a-zA-Z0-9_\-\.\s]+$/.test(username)) {
    errors.push({ msg: 'Username can only contain letters, numbers, underscores, hyphens, periods, and spaces' });
}

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.

1 participant