Skip to content

Instantly share code, notes, and snippets.

@koolamusic
Created July 20, 2022 14:33
Show Gist options
  • Save koolamusic/fea74d0a627d6802eac4f6de8d14d55c to your computer and use it in GitHub Desktop.
Save koolamusic/fea74d0a627d6802eac4f6de8d14d55c to your computer and use it in GitHub Desktop.
CASL Authorization Layer sample with Mongoose [https://codesandbox.io/s/wxjrt?file=/src/modules/comments/service.js:0-1204] Reference
const { NotFound } = require('http-errors');
const { ForbiddenError } = require('@casl/ability');
const Comment = require('./model')();
async function findAll(req, res) {
const comments = await Comment.accessibleBy(req.ability);
res.send({ items: comments });
}
async function create(req, res) {
const comment = new Comment({
...req.body,
post: req.params.postId
});
if (req.user._id) {
comment.author = req.user._id;
}
ForbiddenError.from(req.ability).throwUnlessCan('create', comment);
await comment.save();
res.send({ item: comment });
}
async function update(req, res) {
const comment = await Comment.findById(req.params.id);
if (!comment) {
throw new NotFound('Comment not found');
}
comment.set(req.body);
ForbiddenError.from(req.ability).throwUnlessCan('update', comment);
await comment.save();
res.send({ item: comment });
}
async function destroy(req, res) {
const comment = await Comment.findById(req.params.id);
if (comment) {
ForbiddenError.from(req.ability).throwUnlessCan('delete', comment);
await comment.remove();
}
res.send({ item: comment });
}
module.exports = {
create,
update,
destroy,
findAll
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment