{"size": 814, "ext": "js", "max_stars_repo_path": "middleware/checkCampgroundOwenership.js", "max_stars_repo_name": "Hsins-Lab/Yelp-Camp", "max_stars_repo_stars_event_min_datetime": "2021-03-02T10:59:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-02T10:59:29.000Z", "max_issues_repo_path": "middleware/checkCampgroundOwenership.js", "max_issues_repo_name": "ShuvradipChakraborty/udemy_Yelp-Camp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "middleware/checkCampgroundOwenership.js", "max_forks_repo_name": "ShuvradipChakraborty/udemy_Yelp-Camp", "max_forks_repo_forks_event_min_datetime": "2020-03-16T21:23:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-11T02:41:50.000Z"}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": 2, "avg_line_length": 28.0689655172, "max_line_length": 69, "alphanum_fraction": 0.5651105651}
const Campground = require('../models/campground');

const checkCampgroundOwenership = (req, res, next) => {
  if (req.isAuthenticated()) {
    Campground.findById(req.params.id, (err, foundCampground) => {
      if (err || !foundCampground) {
        req.flash('error', 'Campground not found');
        res.redirect('back');
      } else {
        // does the user own the campground
        if (
          foundCampground.author.id.equals(req.user._id) ||
          req.user.isAdmin
        ) {
          next();
        } else {
          req.flash('error', "You don't have permission to do that");
          res.redirect('back');
        }
      }
    });
  } else {
    req.flash('error', 'You need to be logged in to do that');
    res.redirect('/login');
  }
};

module.exports = checkCampgroundOwenership;
