Skip to content

Instantly share code, notes, and snippets.

@marshallswain
Created April 17, 2017 12:40
Show Gist options
  • Save marshallswain/024400078aa8022f75c34d413129f94d to your computer and use it in GitHub Desktop.
Save marshallswain/024400078aa8022f75c34d413129f94d to your computer and use it in GitHub Desktop.
FeathersJS: Better permissions

Better Permissions Control

We have introduced 3 new hooks and 2 new middleware as part of feathers-permissions that give you much more flexibility and control over access permissions than was previously possible. Permissions are stored in the database on the entity record that needs to have access permissions checked (typically a user). They look like this:

[
    '*', // all services, all methods, all docs
    'users:*', // all methods on users service
    'users:remove:*', // can remove any user
    '*:remove', // can remove on any service
    'users:remove:1234', // can only remove user with id 1234
    'users:*:1234' // can call any service method for user with id 1234
]

you use your hooks like this:

const permissions = require('feathers-permissions');
userService.hooks({
    before: {
        all: [
            permissions.hooks.checkPermissions({service: 'users', on: 'user', field: 'permissions'}),
            permissions.hooks.isPermitted()
        ]
    }
});
userService.hooks({
    after: {
        create: [
            permissions.hooks.setPermissions({permissions: ['users:*:[id]'], field: 'permissions'})
        ]
    }
});

and the middleware like this:

const permissions = require('feathers-permissions');
const requiredPermissions = ['users:*', 'admin']; // whatever permissions you want
app.get(
    '/protected',
    permissions.express.checkPermissions({
        on: 'user',
        field: 'permissions',
        permissions: requiredPermissions
    }),
    permissions.express.isPermitted,
    (req, res, next) => {
    // Do your thing
    }
);

By default this new hook and new middleware assume you are storing your permissions on a permissions field either as an array of strings or a string with comma separated permissions. As always, you can customize the field you are storing your permissions under so you can still use the old role based system by doing this:

const auth = require('feathers-authentication').hooks;
userService.before({
    all: [
        auth.isAuthenticated(),
        auth.checkPermissions({roles: ['admin'], on: 'user', field: 'role'})
    ]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment