Strapi Permissions
Highly customizable permission engine made for Strapi
Get Started
yarn add @strapi/permissions
const permissions = require('@strapi/permissions');
const engine = permissions.engine.new({ providers });
const ability = await engine.generateAbility([
{ action: 'read' },
{ action: 'delete', subject: 'foo' },
{ action: 'update', subject: 'bar', properties: { fields: ['foobar'] } },
{
action: 'create',
subject: 'foo',
properties: { fields: ['foobar'] },
conditions: ['isAuthor'],
},
]);
ability.can('read');
ability.can('publish');
ability.can('update', 'foo');
ability.can('update', 'bar');
- You need to give both an action and a condition provider as parameters when instantiating a new permission engine instance. They must be contained in a
providers
object property.
- You can also pass an
abilityBuilderFactory
to customize what kind of ability the generateAbility
method will return. By default it'll use a @casl/ability
builder.
You can also register to some hooks for each engine instance.
See lib/engine/hooks.js
-> createEngineHooks
for available hooks.
const permissions = require('@strapi/permissions');
const engine = permissions.engine
.new({ providers })
.on('before-format::validate.permission', ({ permission }) => {
if (permission.action === 'read') {
return false;
}
});
const ability = await engine.generateAbility([
{ action: 'read' },
{ action: 'delete', subject: 'foo' },
{ action: 'update', subject: 'bar', properties: { fields: ['foobar'] } },
{
action: 'create',
subject: 'foo',
properties: { fields: ['foobar'] },
conditions: ['isAuthor'],
},
]);
ability.can('read');
ability.can('publish');
ability.can('update', 'foo');
ability.can('update', 'bar');
The format.permission
hook can be used to modify the permission.
const permissions = require('@strapi/permissions');
const engine = permissions.engine
.new({ providers })
.on('before-format::validate.permission', ({ permission }) => {
if (permission.action === 'modify') {
return false;
}
})
.on('after-format::validate.permission', ({ permission }) => {
if (permission.action === 'update') {
return false;
}
})
.on('format.permission', ({ permission }) => {
if (permission.action === 'update') {
return {
...permission,
action: 'modify',
};
}
if (permission.action === 'delete') {
return {
...permission,
action: 'remove',
};
}
return permission;
});
const ability = await engine.generateAbility([{ action: 'update' }, { action: 'delete' }]);
ability.can('update');
ability.can('modify');
ability.can('delete');
ability.can('remove');