Skip to content

Instantly share code, notes, and snippets.

@claustres
Last active August 4, 2017 15:48
Show Gist options
  • Save claustres/4d2dff44a0110a552c44435a432f3de7 to your computer and use it in GitHub Desktop.
Save claustres/4d2dff44a0110a552c44435a432f3de7 to your computer and use it in GitHub Desktop.
Abilities hooks
...
function defineAbilitiesForSubject (subject) {
const { rules, can, cannot } = AbilityBuilder.extract()
// Run registered hooks
hooks.forEach(hook => hook(subject, can, cannot))
...
}
defineAbilitiesForSubject.registerHook = function (hook) {
if (!hooks.includes(hook)) {
hooks.push(hook)
}
}
defineAbilitiesForSubject.unregisterHook = function (hook) {
hooks = hooks.filter(registeredHook => registeredHook !== hook)
}
// Hook computing anonymous abilities for a given user
function defineAnonymousAbilitiesForSubject (subject, can, cannot) {
// Register
can('create', 'users')
}
...
// Register all default hooks here, others will be registered dynamically when setting up other modules
// Default rules for unauthenticated users
defineAbilitiesForSubject.registerHook(defineAnonymousAbilitiesForSubject)
// Other rules might be added/remove at other entry points of the app
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment