Last active
July 24, 2017 20:02
-
-
Save stalniy/60e3a2ad5ca4bfeb5fd81726bc59dd1d to your computer and use it in GitHub Desktop.
CASL in expressjs app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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