Check action permissions.
This module requires at least Node v8.3.0.
yarn add moleculer-middleware-permissions
// moleculer.config.js
const PermissionGuard = require('moleculer-middleware-permissions');
const guard = new PermissionGuard({options});
module.exports = {
...
middlewares: [
guard.middleware(),
],
};
// service.js
module.exports = {
name: 'awesome.service',
actions: {
hello: {
// The user must have both 'hello:read' AND 'hello:name'
// You can override this behaviour by passing your 'checkFunction'
permissions: ['hello.read', '$owner', (ctx) => ctx.call('acl.canSayHello')],
handler (ctx) {
const {name} = ctx.params;
return `Hello ${name}`;
}
},
me: {
// Will check for these permissions: ['awesome.service.me']
permissions: true,
handler (ctx) {
return `Hello me`;
}
}
}
};
checkFunction(current, requested)
: A function that returntrue
if the request has enough permissions. Else, the return value will be send in the rejectedPermissionError
.getPermissionsFromAction(action)
: Called to return an array of permissions from an action.getUserPermissions(ctx)
: Function called to retrieve user's permissions. By default will returnmeta.user.permissions
.
The simplest way to add permissions is to use a list of strings, representing each a permissions, like this:
members.read
: Can list/get/find membersmembers.write
: Can update/remove/create members
It will be checked before any functions and if it allows to access, function will not be checked!
If you want the owner of the entity to be able to update it but not other ones, you can use this
special permissions. It will try to call the method isEntityOwner(ctx)
of your service.
Returning a truthy value will act as allowed.
This method can be async.
You can also provide functions to check if the user is allowed to access an action. It will be called only if strings aren't allowed first. Only one function needs to return a truthy value to be allowed!
This method can be async.
You can override this behaviour by overriding the
check
method the class.
The v2 was inspired by @icebob's kantab project.
MIT