Skip to content

Instantly share code, notes, and snippets.

@stalniy
Last active July 24, 2017 20:02
Show Gist options
  • Save stalniy/60e3a2ad5ca4bfeb5fd81726bc59dd1d to your computer and use it in GitHub Desktop.
Save stalniy/60e3a2ad5ca4bfeb5fd81726bc59dd1d to your computer and use it in GitHub Desktop.
CASL in expressjs app
const { AbilityBuilder, Ability } = require('casl')
function defineAbilitiesFor(user) {
const { rules, can } = AbilityBuilder.extract()
can('read', ['Post', 'Comment'])
can('create', 'User')
if (user) {
can('manage', ['Post', 'Comment'], { author: user._id })
can(['read', 'update'], 'User', { _id: user._id })
}
return new Ability(rules)
}
const ANONYMOUS_ABILITY = defineAbilitiesFor(null)
module.exports = function createAbilities(req, res, next) {
req.ability = req.user.email ? defineAbilitiesFor(req.user) : ANONYMOUS_ABILITY
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment