{"size": 789, "ext": "js", "max_stars_repo_path": "src/middlewares/role.middleware.js", "max_stars_repo_name": "nguyenhnghia/tdtubook-backend", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/middlewares/role.middleware.js", "max_issues_repo_name": "nguyenhnghia/tdtubook-backend", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/middlewares/role.middleware.js", "max_forks_repo_name": "nguyenhnghia/tdtubook-backend", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.4516129032, "max_line_length": 80, "alphanum_fraction": 0.6375158428}
/* eslint-disable arrow-body-style */

const ApiError = require("../utils/ApiError");

const permit = (...permittedRoles) => {
  // Return a middleware
  return (req, res, next) => {
    const { user } = req;

    const isOwnerPermitted = permittedRoles.includes("owner");

    if (isOwnerPermitted) {
      // If userId is match, then ownership is met
      if (user._id.toString() === req.params.userId) {
        return next();
      }
    }

    const isAllPermitted = permittedRoles.includes("all");
    const isUserPermitted = permittedRoles.includes(user.role);

    if (user && (isAllPermitted || isUserPermitted)) {
      return next(); // User role is allowed, so continue on the next middleware
    }

    throw new ApiError(403, "Forbidden");
  };
};

module.exports = permit;
