Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Banner validation (Backend) #497

Merged
merged 9 commits into from
Jan 17, 2025

Conversation

eulerbutcooler
Copy link
Contributor

Banner backend validations.

This PR addresses the issue #388

I've used express validator for the backend validation checks.

Added Changes:

  • Added all the validation logic for banners in **banner.
  • Reused validation logic for /add_banner and /edit_banner
  • Reused id check from param in both /delete_banner and /get_banner/:id
  • Added url check for /get_banner_by_url
  • Added checks for url that are triggered only when the close action button is set to 'open url' or 'open url in a new tab'
  • Consistent background and font color checks allowing only hex color codes
  • Added/Updated error messages expected in /e2e/banner.test.mjs and unit/controllers/banner.test.js

Removed code:

  • Validation checks from banner.controller.js
  • Validation checks from Banner.js

I've left the validatePosition, validatePositionWrapper, etc as they might still be used by some other service.

Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Walkthrough

The pull request introduces significant changes to the validation and error handling mechanisms across various banner-related components in both the backend and frontend. Key modifications include the removal of validation checks from controller methods and model definitions, the addition of new validation middleware in routes, and enhancements to error reporting in frontend services. These changes streamline the handling of banner data while maintaining core functionalities.

Changes

File Change Summary
backend/src/controllers/banner.controller.js Simplified validation logic, removed input checks from methods such as addBanner, deleteBanner, and editBanner.
backend/src/models/Banner.js Removed field-level validation functions for multiple fields including closeButtonAction, url, and fontColor.
backend/src/routes/banner.routes.js Added new validation middleware for POST, DELETE, and GET routes, enhancing error handling processes.
backend/src/service/banner.service.js Modified error handling in methods to omit error parameters in catch blocks, simplifying error management.
backend/src/utils/banner.helper.js Introduced new validation rules and constants for banner-related data, enforcing checks for various fields.
frontend/src/utils/guideHelper.js Enhanced error message reporting to emit multiple errors instead of just the first one.
frontend/src/services/bannerServices.js Updated error logging in catch blocks to provide more detailed error messages from API responses.
frontend/src/scenes/banner/CreateBannerPage.jsx Removed a comment line within the useEffect hook, cleaning up the code without altering functionality.
backend/src/test/e2e/auth.test.mjs Changed double quotes to single quotes for string literals throughout the test file for consistency.
backend/src/test/e2e/banner.test.mjs Standardized string literals to single quotes and restructured test descriptions for uniformity.
backend/src/test/mocks/banner.mock.js Updated string literals to single quotes and changed actionUrl property to a relative path string.
backend/src/test/unit/controllers/banner.test.js Converted double quotes to single quotes in test descriptions and assertions for consistency.

Suggested Reviewers

  • erenfn

Possibly Related PRs

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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 (7)
frontend/src/utils/guideHelper.js (1)

5-7: Yo dawg, let's make this error handling more robust!

The iteration through errors is straight fire, but we can make it even better with modern JavaScript. Plus, we need to check if that errors array exists, or we might catch a TypeError!

Here's a cleaner way to do it:

-      for (let i = 0; i < error.response.data.errors.length; i++){
-        toastEmitter.emit(TOAST_EMITTER_KEY, 'An error occurred: ' + error.response.data.errors[i])
-      }
+      const errors = error.response.data.errors || [];
+      errors.forEach(errorMsg => 
+        toastEmitter.emit(TOAST_EMITTER_KEY, `An error occurred: ${errorMsg}`)
+      );
backend/src/models/Banner.js (1)

5-40: Yo, we need some database-level validation up in here!

While moving validations to the route level is dope, we should consider adding some database-level constraints for the following fields to prevent invalid data from sneaking in:

  • closeButtonAction: Add CHECK constraint for valid actions
  • position: Add CHECK constraint for valid positions
  • fontColor, backgroundColor: Add CHECK constraints for hex color format

Consider adding migrations to implement these constraints. Want me to help draft those SQL constraints?

backend/src/routes/banner.routes.js (1)

12-46: Let's organize these routes like mom organizes her kitchen!

The routes could be grouped better for maintainability. Consider organizing them by authentication requirements.

Group them like this:

  1. Authenticated routes with banner permissions
  2. Authenticated routes without special permissions
  3. Public routes

Want me to show you how to restructure this?

backend/src/service/banner.service.js (2)

45-53: Yo dawg, let's make that error handling more lit! 🔥

The error handling in getBannerById could drop more knowledge about what went wrong. Consider passing the original error message to help with debugging.

   } catch {
-    throw new Error('Error retrieving banner by ID');
+    throw new Error(`Error retrieving banner by ID: ${error.message}`);
   }

55-74: These error messages be looking like twins, fam! 👯‍♂️

The error messages in getBannerByUrl and getIncompleteBannersByUrl are identical despite performing different operations. Let's make them unique and include the URL for better debugging.

   } catch {
-    throw new Error('Error retrieving banner by URL');
+    throw new Error(`Error retrieving banner for URL: ${url}`);
   }
   } catch {
-    throw new Error('Error retrieving banner by URL');
+    throw new Error(`Error retrieving incomplete banners for URL: ${url}`);
   }
backend/src/utils/banner.helper.js (1)

2-2: These hex colors need some swagger check! 🎨

The hex color validation could be improved:

  1. Export the pattern for reuse
  2. Consider enforcing 6-digit format for consistency
-const hexColorPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
+const HEX_COLOR_PATTERN = /^#[A-Fa-f0-9]{6}$/;

 module.exports = {
+  HEX_COLOR_PATTERN,
   // ... other exports
 };

Also applies to: 45-49

backend/src/controllers/banner.controller.js (1)

14-14: That console log be looking kinda sus! 📝

The informal error logging message "here is the error yar" should be standardized for better log searching and professionalism.

-      console.log('here is the error yar', err.message);
+      console.error('Error creating banner:', err.message);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9380551 and eb131e5.

📒 Files selected for processing (13)
  • backend/src/controllers/banner.controller.js (1 hunks)
  • backend/src/models/Banner.js (1 hunks)
  • backend/src/routes/banner.routes.js (1 hunks)
  • backend/src/service/banner.service.js (1 hunks)
  • backend/src/test/e2e/auth.test.mjs (2 hunks)
  • backend/src/test/e2e/banner.test.mjs (1 hunks)
  • backend/src/test/mocks/banner.mock.js (3 hunks)
  • backend/src/test/unit/controllers/banner.test.js (2 hunks)
  • backend/src/utils/auth.helper.js (1 hunks)
  • backend/src/utils/banner.helper.js (2 hunks)
  • frontend/src/scenes/banner/CreateBannerPage.jsx (0 hunks)
  • frontend/src/services/bannerServices.js (1 hunks)
  • frontend/src/utils/guideHelper.js (1 hunks)
💤 Files with no reviewable changes (1)
  • frontend/src/scenes/banner/CreateBannerPage.jsx
✅ Files skipped from review due to trivial changes (4)
  • backend/src/test/e2e/auth.test.mjs
  • backend/src/test/unit/controllers/banner.test.js
  • backend/src/test/mocks/banner.mock.js
  • backend/src/test/e2e/banner.test.mjs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)

Copy link
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: 0

🧹 Nitpick comments (1)
backend/src/routes/banner.routes.js (1)

1-51: Consider grouping these routes like mom's recipe categories!

For better maintainability, consider grouping the routes by access level or functionality:

  1. Public routes
  2. Authenticated routes
  3. Admin routes

Example structure:

// Public routes
router.get('/get_banner_by_url', ...);

// Authenticated routes
router.get('/banners', ...);
router.get('/all_banners', ...);

// Admin routes (with accessGuard)
router.post('/add_banner', ...);
router.delete('/delete_banner/:id', ...);
router.put('/edit_banner/:id', ...);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb131e5 and 4c7285f.

📒 Files selected for processing (2)
  • backend/src/routes/banner.routes.js (1 hunks)
  • backend/src/utils/auth.helper.js (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/utils/auth.helper.js
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (4)
backend/src/routes/banner.routes.js (4)

1-15: Yo, these imports are cleaner than mom's kitchen!

The organization of dependencies is on point, with clear separation of core Express components, controllers, middleware, and validation utilities.


16-39: These protected routes are more secure than mom's secret recipe vault!

Solid implementation with:

  • JWT authentication
  • Access control guards
  • Validation middleware in the correct order

49-49: Validation's looking fresh like mom's homemade bread!

Nice job adding the getBannerByUrlValidation and handleValidationErrors middleware to the /get_banner_by_url endpoint. This addresses the security concern raised in the previous review.


40-41: ⚠️ Potential issue

Yo! These routes are missing validation like mom's spaghetti missing sauce!

The /all_banners and /banners endpoints lack validation middleware, which could make them vulnerable to potential attacks.

Add validation middleware:

-router.get('/all_banners', authenticateJWT, bannerController.getAllBanners);
-router.get('/banners', authenticateJWT, bannerController.getBanners);
+router.get(
+  '/all_banners',
+  authenticateJWT,
+  handleValidationErrors,
+  bannerController.getAllBanners
+);
+router.get(
+  '/banners',
+  authenticateJWT,
+  handleValidationErrors,
+  bannerController.getBanners
+);

Likely invalid or redundant comment.

@eulerbutcooler
Copy link
Contributor Author

@erenfn Let me know if i need to make any changes here

Copy link
Collaborator

@erenfn erenfn left a comment

Choose a reason for hiding this comment

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

Missing repetition type returns:

{
    "errors": [
        "Invalid value",
        "Invalid repetition"
    ]
}

However, missing position returns

{
    "errors": [
        "Position is required"
    ]
}

In repetitionType, can we remove "Invalid value", and change Invalid repetition to "Repetition type is required"?

@eulerbutcooler
Copy link
Contributor Author

eulerbutcooler commented Jan 17, 2025

@erenfn fixed the error message as requested
i noticed there are no tests for repetition type. Do you want me to add those?

Copy link
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: 0

🧹 Nitpick comments (4)
backend/src/utils/banner.helper.js (4)

2-2: Yo dawg, let's make that regex more self-explanatory! 🎨

Consider renaming hexColorPattern to something more descriptive like VALID_HEX_COLOR_REGEX to better communicate its purpose and validation rules.

-const hexColorPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
+const VALID_HEX_COLOR_REGEX = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;

11-16: Mom's spaghetti time! Let's make these actions more maintainable! 🍝

Extract the allowed actions into a constant to make updates easier and prevent typos.

+const VALID_CLOSE_BUTTON_ACTIONS = ['no action', 'open url', 'open url in a new tab'];
+
 body('closeButtonAction')
   .notEmpty()
   .withMessage('Close Button Action is required')
   .bail()
-  .isIn(['no action', 'open url', 'open url in a new tab'])
+  .isIn(VALID_CLOSE_BUTTON_ACTIONS)
   .withMessage('Invalid close button action'),

17-36: Knees weak, arms heavy... this URL validation needs some cleanup! 💪

The nested custom validations make the code harder to follow. Consider splitting this into separate middleware functions.

+const validateUrlWithAction = (value, { req }) => {
+  if (!value && ['open url', 'open url in a new tab'].includes(req.body.closeButtonAction)) {
+    throw new Error('URL is required when close button action is set to open URL');
+  }
+  return true;
+};
+
+const validateUrlProtocol = (value) => {
+  if (!value) return true;
+  try {
+    const url = new URL(value);
+    if (!['http:', 'https:'].includes(url.protocol)) {
+      throw new Error('URL must use HTTP or HTTPS protocol');
+    }
+    return true;
+  } catch {
+    throw new Error('URL must use HTTP or HTTPS protocol');
+  }
+};
+
 body('url')
   .optional()
-  .custom((value, { req }) => {
-    if (!value && ['open url', 'open url in a new tab'].includes(req.body.closeButtonAction)) {
-      return false;
-    }
-    return true;
-  })
-  .withMessage('URL is required when close button action is set to open URL')
+  .custom(validateUrlWithAction)
   .bail()
-  .custom((value) => {
-    if (!value) return true;
-    try {
-      const url = new URL(value);
-      return ['http:', 'https:'].includes(url.protocol);
-    } catch {
-      return false;
-    }
-  })
-  .withMessage('URL must use HTTP or HTTPS protocol'),
+  .custom(validateUrlProtocol),

52-53: These validations looking slim like mom's spaghetti! 🍜

Consider adding more robust checks:

  1. For ID: Add a minimum value check
  2. For URL: Add length limits and character restrictions
-const deleteOrGetBannerByIdValidation = [param('id').notEmpty().trim().isInt().withMessage('Invalid id')];
+const deleteOrGetBannerByIdValidation = [
+  param('id')
+    .notEmpty()
+    .trim()
+    .isInt({ min: 1 })
+    .withMessage('ID must be a positive integer')
+];

-const getBannerByUrlValidation = [body('url').notEmpty().isString().withMessage('URL is missing or invalid')];
+const getBannerByUrlValidation = [
+  body('url')
+    .notEmpty()
+    .isString()
+    .isLength({ max: 2048 })
+    .matches(/^[a-zA-Z0-9-_/.]+$/)
+    .withMessage('URL must be valid and not exceed 2048 characters')
+];
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c7285f and de3e4f4.

📒 Files selected for processing (1)
  • backend/src/utils/banner.helper.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (1)
backend/src/utils/banner.helper.js (1)

Line range hint 65-87: Let's verify these helper functions ain't collecting dust! 🕵️

These URL validation helpers might be used elsewhere, but let's verify their usage to ensure we're not keeping dead code.

Also, consider adding JSDoc comments to document these utility functions:

+/**
+ * Validates a URL string to ensure it uses HTTP/HTTPS protocol
+ * @param {string} value - The URL to validate
+ * @param {string} fieldName - Name of the field for error messages
+ * @throws {Error} If URL is invalid or doesn't use HTTP/HTTPS
+ */
 const validateUrl = (value, fieldName) => {
✅ Verification successful

Yo, these validation functions are straight fire! 🔥

Both validateUrl and validateRelativeUrl are actively used across frontend and backend components. They're not just collecting dust - they're doing the heavy lifting in popup controllers and models, eh!

The JSDoc suggestion is still solid though - would make these utility functions even more legit.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of validateUrl and validateRelativeUrl functions
echo "Searching for validateUrl usage..."
rg "validateUrl\(" --type js

echo "Searching for validateRelativeUrl usage..."
rg "validateRelativeUrl\(" --type js

Length of output: 829

@erenfn
Copy link
Collaborator

erenfn commented Jan 17, 2025

@erenfn fixed the error message as requested i noticed there are no tests for repetition type. Do you want me to add those?

Sure. That would be great. Also can you change the validation of repetitionType to this?

  body('repetitionType')
    .custom((value) => {
      if (!value) {
        throw new Error('Repetition type is required');
      }
      if (!['show only once', 'show every visit'].includes(value)) {
        throw new Error('Invalid repetition type');
      }
      return true;
    }),

@eulerbutcooler
Copy link
Contributor Author

@erenfn fixed the error message as requested i noticed there are no tests for repetition type. Do you want me to add those?

Sure. That would be great. Also can you change the validation of repetitionType to this?

  body('repetitionType')
    .custom((value) => {
      if (!value) {
        throw new Error('Repetition type is required');
      }
      if (!['show only once', 'show every visit'].includes(value)) {
        throw new Error('Invalid repetition type');
      }
      return true;
    }),

Added the tests for both add_banner and edit_banner and also implemented the repetitionType validation as requested

Copy link
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: 0

🔭 Outside diff range comments (1)
backend/src/utils/banner.helper.js (1)

Line range hint 74-95: URL validation functions looking like copy-pasta! 🍝

The URL validation functions have similar patterns and could be consolidated into a single function with options:

const validateUrlWithOptions = (value, options = {}) => {
  const { fieldName = 'URL', allowRelative = false, requireProtocol = false } = options;
  if (!value) return;
  
  try {
    const url = new URL(value);
    if (requireProtocol && !['http:', 'https:'].includes(url.protocol)) {
      throw new Error('URL must use HTTP or HTTPS protocol');
    }
  } catch (error) {
    if (allowRelative && value.startsWith('/')) {
      return;
    }
    throw new Error(`Invalid ${fieldName}: ${error.message}`);
  }
};
🧹 Nitpick comments (5)
backend/src/utils/banner.helper.js (5)

1-2: Yo dawg, let's make that hex color regex more readable! 🎨

Add a descriptive comment explaining the hex color pattern:

 const { body, param } = require('express-validator');
+// Validates 6-digit (#RRGGBB) or 3-digit (#RGB) hex color codes
 const hexColorPattern = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;

19-36: Mom's spaghetti moment: URL validation's getting heavy! 🍝

The URL validation logic is complex and could be simplified using express-validator's built-in URL validator:

-    .custom((value) => {
-      if (!value) return true;
-      try {
-        const url = new URL(value);
-        return ['http:', 'https:'].includes(url.protocol);
-      } catch {
-        return false;
-      }
-    })
+    .if(value => value)
+    .isURL({ protocols: ['http', 'https'] })

44-52: Repetition type validation needs some cleanup on aisle 3! 🧹

Convert the custom validation to use express-validator's built-in validators for cleaner code:

-  body('repetitionType').custom((value) => {
-    if (!value) {
-      throw new Error('Repetition type is required');
-    }
-    if (!['show only once', 'show every visit'].includes(value)) {
-      throw new Error('Invalid repetition type');
-    }
-    return true;
-  }),
+  body('repetitionType')
+    .notEmpty()
+    .withMessage('Repetition type is required')
+    .bail()
+    .isIn(['show only once', 'show every visit'])
+    .withMessage('Invalid repetition type'),

60-61: These error messages be looking kinda basic, yo! 📝

Enhance error messages to be more specific and helpful:

-const deleteOrGetBannerByIdValidation = [param('id').notEmpty().trim().isInt().withMessage('Invalid id')];
+const deleteOrGetBannerByIdValidation = [
+  param('id')
+    .notEmpty()
+    .withMessage('Banner ID is required')
+    .trim()
+    .isInt()
+    .withMessage('Banner ID must be a valid integer')
+];

63-71: Performance check: toLowerCase() result getting ghosted! 👻

The toLowerCase() result should be stored to avoid potential multiple calls:

 const validatePosition = (value) => {
   const validPositions = ['top', 'bottom'];
-  return validPositions.includes(value.toLowerCase());
+  const normalizedValue = value.toLowerCase();
+  return validPositions.includes(normalizedValue);
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between de3e4f4 and c162d1c.

⛔ Files ignored due to path filters (1)
  • frontend/dist/index.html is excluded by !**/dist/**
📒 Files selected for processing (2)
  • backend/src/test/e2e/banner.test.mjs (1 hunks)
  • backend/src/utils/banner.helper.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/test/e2e/banner.test.mjs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)

@erenfn erenfn self-requested a review January 17, 2025 10:40
Copy link
Collaborator

@erenfn erenfn left a comment

Choose a reason for hiding this comment

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

Looks good!

@erenfn erenfn merged commit fbcd7c2 into bluewave-labs:develop Jan 17, 2025
2 checks passed
This was referenced Feb 19, 2025
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.

2 participants