Skip to content

Instantly share code, notes, and snippets.

@phpmaps
Last active August 11, 2021 16:08
Show Gist options
  • Select an option

  • Save phpmaps/9cdefd12f11086605cdeecfff1827055 to your computer and use it in GitHub Desktop.

Select an option

Save phpmaps/9cdefd12f11086605cdeecfff1827055 to your computer and use it in GitHub Desktop.
authenticate-middlewear.js
// Reusable middlewear which checks to see if a user can modify comments
const Campsite = require('./models/campsite');
exports.canModComments = async (req, res, next) => {
const campsite = await Campsite.findById(req.params.campsiteId);
if (campsite.comments.id(req.params.commentId).author.equals(req.user._id)) {
req.campsite = campsite; //Add more stuff to the req object
return next();
} else {
const err = new Error('You are not authorized to perform this operation!');
err.status = 403;
return next(err);
}
}
@phpmaps
Copy link
Author

phpmaps commented Aug 11, 2021

//Use the middlewear like this in the campsitesRouter

campsiteRouter.route('/:campsiteId/comments/:commentId')
    .delete(authenticate.verifyUser, authenticate.canModComments, (req, res, next) => {
        console.log(req.campsite); 
        //Note that the authenticate.canModComments middlewear added campsite on req object...
        //...now we can do away with findById campsite b/ that was already done in the middlewear... 
        //Not doing that ... but actually should remove the next findById for performance reasons.
        //The middlewear also does the perission check we need and can be used on PUT too...
        Campsite.findById(req.params.campsiteId)
            .then(campsite => {
                if (campsite && campsite.comments.id(req.params.commentId)) {
                    campsite.comments.id(req.params.commentId).remove();
                    campsite.save()
                        .then(campsite => {
                            res.statusCode = 200;
                            res.setHeader('Content-Type', 'application/json');
                            res.json(campsite);
                        })
                        .catch(err => next(err));
                } else if (!campsite) {
                    err = new Error(`Campsite ${req.params.campsiteId} not found`);
                    err.status = 404;
                    return next(err);
                } else {
                    err = new Error(`Comment ${req.params.commentId} not found`);
                    err.status = 404;
                    return next(err);
                }
            })
            .catch(err => next(err));
    })

@bcastillo32
Copy link

Thank you for this! super helpful and looks much cleaner than all those ifs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment