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

added find by url endpoints for models #357

Merged
merged 9 commits into from
Dec 6, 2024
Merged

Conversation

erenfn
Copy link
Collaborator

@erenfn erenfn commented Dec 4, 2024

  • Added find by url endpoints for models
  • Added accessGuard for link endpoints

@erenfn erenfn requested a review from swoopertr December 4, 2024 19:59
Copy link
Contributor

coderabbitai bot commented Dec 4, 2024

Warning

Rate limit exceeded

@swoopertr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 26 minutes and 58 seconds before requesting another review.

⌛ 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 69afe07 and 507b966.

Walkthrough

This pull request introduces several changes to the backend codebase, primarily focusing on enhancing the routing structure and permissions for various controllers and services. New methods are added to multiple controllers to retrieve resources based on a URL, along with corresponding routes in the routing files. Additionally, new permissions for links and tours are introduced in the configuration, affecting role-based access control. The changes also include updates to middleware usage for improved security and access management across the application.

Changes

File Path Change Summary
backend/config/settings.js Added permissions links and tours to the permissions object for userRole.ADMIN.
backend/index.js Introduced guideRoutes, updated database sync behavior to force: false, and commented out fileSizeValidator. Removed unused import for Team.
backend/src/controllers/banner.controller.js Added method getBannerByUrl for retrieving a banner by URL, with validation and error handling adjustments.
backend/src/controllers/guide.controller.js Added GuideController class with method getGuidesByUrl to retrieve guides by URL, including validation and concurrent service calls.
backend/src/controllers/hint.controller.js Added method getHintByUrl for retrieving a hint by URL, with validation and error handling.
backend/src/controllers/link.controller.js Added method getLinkByUrl for retrieving a link by URL, with validation and error handling.
backend/src/controllers/popup.controller.js Added method getPopupByUrl for retrieving a popup by URL, with validation and error handling.
backend/src/controllers/tour.controller.js Added method getTourByUrl for retrieving a tour by URL, with validation and error handling.
backend/src/routes/banner.routes.js Added route /get_banner_by_url to retrieve a banner by URL.
backend/src/routes/guide.routes.js Introduced new router with route /get_guides_by_url to retrieve guides by URL.
backend/src/routes/hint.routes.js Added commented-out route /get_hint_by_url for hint retrieval by URL.
backend/src/routes/link.routes.js Added route /get_link_by_url and updated existing routes to include authenticateJWT and accessGuard middleware for permission checks.
backend/src/routes/popup.routes.js Added route /get_popup_by_url for retrieving popups by URL.
backend/src/routes/tour.routes.js Updated routes to include accessGuard for permission checks on tour-related operations.
backend/src/service/banner.service.js Added method getBannerByUrl to retrieve banners by URL.
backend/src/service/hint.service.js Added method getHintByUrl to retrieve hints by URL.
backend/src/service/link.service.js Added method getLinkByUrl to retrieve links by URL.
backend/src/service/popup.service.js Added method getPopupByUrl to retrieve popups by URL.
backend/src/service/tour.service.js Added method getTourByUrl to retrieve tours by URL.
backend/.env Added a newline at the end of the file; no other changes made to environment variables.

Possibly related PRs

  • Settings and Teams feature #211: The changes in this PR involve adding new permissions to the team.permissions object, which is directly related to the modifications made in the main PR that introduced new permissions (links and tours) to the same object.
  • PR for Issue#303 #327: This PR adds a new permission setOrg to the permissions object, which is related to the changes in the main PR that also involve modifying permissions.
  • PR for Issue#301 #337: This PR also adds new permissions (popups, hints, and banners) to the team.permissions object, which aligns with the changes in the main PR regarding the enhancement of role-based access control.
  • Popup log fixed #355: The renaming of the popup log to guide log and the introduction of new endpoints for guide logs are relevant to the changes in the main PR that involve permissions and user roles.

Suggested labels

backend


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 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: 19

🧹 Outside diff range and nitpick comments (3)
backend/src/service/hint.service.js (1)

Line range hint 58-79: There's code duplication on his sweater already! 🍝

I notice similar URL-based retrieval patterns across all three services. Consider the following architectural improvements:

  1. Create a shared URL validation utility
  2. Implement rate limiting for URL-based queries
  3. Consider implementing a base service class with common URL retrieval logic
  4. Add request IP logging for security monitoring

Example shared utility:

// utils/urlValidator.js
const validateAndSanitizeUrl = (url) => {
  if (!url || typeof url !== 'string') {
    throw new Error('Invalid URL provided');
  }
  // Add URL sanitization logic
  return url.trim().toLowerCase();
};

module.exports = { validateAndSanitizeUrl };
backend/index.js (2)

Line range hint 34-43: Yo! CRITICAL SECURITY ISSUE: Database sync with force:true will drop all tables! 🚨

The force: true option in sequelize.sync() will drop and recreate all tables on every server restart. This is extremely dangerous in production!

- .sync({ force: true })
+ .sync()

Also, the database connection error handling needs improvement:

 sequelize
   .authenticate()
   .then(() => console.log('Database connected...'))
-  .catch((err) => console.log('Error: ' + err));
+  .catch((err) => {
+    console.error('Unable to connect to the database:', err);
+    process.exit(1);  // Fail fast if DB connection fails
+  });

Line range hint 29-30: Heads up! Security concern with commented out file size validator 🛡️

The file size validator middleware is commented out, which could expose the server to large file upload attacks.

- // app.use(fileSizeValidator);
+ app.use(fileSizeValidator);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d46ed29 and 51a1146.

📒 Files selected for processing (19)
  • backend/config/settings.js (1 hunks)
  • backend/index.js (3 hunks)
  • backend/src/controllers/banner.controller.js (7 hunks)
  • backend/src/controllers/guide.controller.js (1 hunks)
  • backend/src/controllers/hint.controller.js (1 hunks)
  • backend/src/controllers/link.controller.js (2 hunks)
  • backend/src/controllers/popup.controller.js (1 hunks)
  • backend/src/controllers/tour.controller.js (1 hunks)
  • backend/src/routes/banner.routes.js (1 hunks)
  • backend/src/routes/guide.routes.js (1 hunks)
  • backend/src/routes/hint.routes.js (1 hunks)
  • backend/src/routes/link.routes.js (1 hunks)
  • backend/src/routes/popup.routes.js (1 hunks)
  • backend/src/routes/tour.routes.js (1 hunks)
  • backend/src/service/banner.service.js (1 hunks)
  • backend/src/service/hint.service.js (1 hunks)
  • backend/src/service/link.service.js (1 hunks)
  • backend/src/service/popup.service.js (1 hunks)
  • backend/src/service/tour.service.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/src/routes/hint.routes.js
🔇 Additional comments (7)
backend/config/settings.js (1)

26-27: Yo, these permission changes look tight! 🔒

The addition of links and tours permissions for admin role follows the existing pattern and maintains proper access control.

Let's make sure these permissions are used consistently:

✅ Verification successful

Yo dawg, these permission checks are straight fire! 🔥

The permissions are properly locked down in both route files:

  • links permission guards all write operations (POST/PUT/DELETE) in link.routes.js
  • tours permission guards all write operations (POST/PUT/DELETE) in tour.routes.js
  • Read operations are only behind JWT auth, which is the right move

The implementation is consistent with the permission settings, no spaghetti code here!

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of these permissions in middleware
rg -l "teamPermissions\.(links|tours)" 

Length of output: 108


Script:

#!/bin/bash
# Let's check how these permissions are actually used in the route files
rg "teamPermissions\.(links|tours)" -A 3 backend/src/routes/tour.routes.js backend/src/routes/link.routes.js

Length of output: 1795

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

10-12: These security upgrades are fire! 🔥

Solid addition of access guards to all modify operations (add/edit/delete). This aligns perfectly with the principle of least privilege.

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

16-16: Yo dawg, we need to talk about security! 🍝

The new /get_popup_by_url endpoint is wide open like mom's spaghetti - no authentication required! While this might be intentional for public access, we should verify if this aligns with the business requirements. If not, consider adding authentication middleware like the other routes.

backend/src/routes/link.routes.js (2)

10-15: Access guards looking tight! 💪

The write operations (add/edit/delete) are properly secured with both authentication and access guards. That's the way to keep it clean!


16-16: Same security vibe check as popup routes 🤔

Like the popup routes, this endpoint is also publicly accessible. Let's make sure this is intentional and consistent across all URL-based endpoints.

✅ Verification successful

The previous pattern didn't work well with ast-grep, so I'm using ripgrep to get a broader view of the routing patterns and authentication setup. This will help us verify if the endpoint's public accessibility is intentional and consistent with other similar endpoints.


Public URL-based endpoints are consistent with the application's design pattern

Looking at the codebase, I can see that all URL-based endpoints (get_*_by_url) are intentionally public:

  • /get_popup_by_url
  • /get_banner_by_url
  • /get_link_by_url
  • /get_guides_by_url

This appears to be a deliberate architectural decision where these specific endpoints need to be publicly accessible, while other operations (add, edit, delete) are properly secured with authenticateJWT and accessGuard middleware.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential sensitive data exposure in URL-based endpoints
ast-grep --pattern 'router.get("/get_$_by_url"'

Length of output: 49


Script:

#!/bin/bash
# Let's check all router endpoints to understand the security pattern
rg "router\.(get|post|put|delete)" -A 2

# Also check for any authentication middleware usage
rg "auth.*middleware" 

Length of output: 9013

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

166-182: Same issues as in LinkController, fam!

This method has the same problems as getLinkByUrl:

  1. Missing response in error handling
  2. URL validation needs to check for empty strings after trim
  3. No 404 handling when banner not found

Please apply the same fixes as suggested in the LinkController review.

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

192-208: Same issues as other controllers, plus we need to talk architecture!

This method has the same problems as getLinkByUrl and getBannerByUrl.

Please apply the same fixes as suggested in the LinkController review.

Since we're implementing the same URL-based retrieval pattern across multiple controllers, consider:

  1. Creating a base controller class with common URL validation and error handling
  2. Using a middleware for URL validation
  3. Creating a common response formatter

Example base controller:

class BaseController {
  validateUrl(url, res) {
    if (!url || typeof url !== 'string' || !url.trim()) {
      res.status(400).json({ errors: [{ msg: "URL is missing or invalid" }] });
      return false;
    }
    return true;
  }

  handleNotFound(entity, res) {
    if (!entity) {
      res.status(404).json({ errors: [{ msg: "Resource not found" }] });
      return true;
    }
    return false;
  }
}

backend/src/routes/guide.routes.js Show resolved Hide resolved
backend/src/routes/tour.routes.js Show resolved Hide resolved
backend/src/controllers/guide.controller.js Show resolved Hide resolved
backend/src/controllers/guide.controller.js Show resolved Hide resolved
backend/src/controllers/guide.controller.js Show resolved Hide resolved
backend/src/controllers/hint.controller.js Show resolved Hide resolved
backend/src/controllers/hint.controller.js Show resolved Hide resolved
backend/src/controllers/link.controller.js Show resolved Hide resolved
backend/src/controllers/link.controller.js Show resolved Hide resolved
backend/src/controllers/link.controller.js Show resolved Hide resolved
@erenfn
Copy link
Collaborator Author

erenfn commented Dec 5, 2024

@coderabbitai resolve

@swoopertr
Copy link
Contributor

adding popup doesnt work.

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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c16f660 and 2587ed4.

📒 Files selected for processing (2)
  • backend/Dockerfile (1 hunks)
  • frontend/Dockerfile (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/Dockerfile


WORKDIR /app

COPY package*.json ./

RUN npm install
RUN rm -rf package-lock.json && npm install
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Mom's spaghetti alert: Removing package-lock.json is risky business!

Removing package-lock.json before npm install:

  • Breaks dependency version locking
  • Can lead to inconsistent builds across environments
  • May introduce unexpected package version updates

Remove this practice and instead use:

-RUN rm -rf package-lock.json && npm install
+RUN npm ci

The npm ci command is designed for CI/CD environments and:

  • Uses package-lock.json strictly
  • Provides faster, reliable installations
  • Ensures consistent dependencies across builds
📝 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
RUN rm -rf package-lock.json && npm install
RUN npm ci

@@ -2,9 +1,11 @@
FROM node:22-alpine3.20
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Yo dawg, we need to reconsider that base image choice!

The node:22 version is still in development and not stable yet. Consider using the latest LTS version (like node:20-alpine3.20) to avoid potential stability issues.

Apply this diff for a more stable base:

-FROM node:22-alpine3.20
+FROM node:20-alpine3.20
📝 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
FROM node:22-alpine3.20
FROM node:20-alpine3.20


WORKDIR /app

COPY package*.json ./

RUN npm install
RUN rm -rf package-lock.json && npm install
RUN npm install formik
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Yo, drop that spaghetti code: Remove redundant formik install!

Mom's spaghetti confirms that formik (v2.4.6) is already cookin' in the package.json dependencies. This explicit installation in the Dockerfile is as redundant as bringing extra pasta to an Italian restaurant!

  • Remove this line from frontend/Dockerfile:
-RUN npm install formik
🔗 Analysis chain

Knees weak, arms heavy: Redundant formik installation detected!

If formik is listed in package.json (which it should be), this explicit installation is redundant and could potentially cause version conflicts.

Remove this line if formik is already in package.json:

-RUN npm install formik

Let's check if formik is already in package.json:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if formik is already listed in package.json
cat package.json | jq '.dependencies.formik, .devDependencies.formik'

Length of output: 116


Script:

#!/bin/bash
# Let's find the package.json file first
fd package.json

# Then check its content for formik
fd package.json --exec cat {} \; | grep -i formik

Length of output: 139

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