javascriptrestpermissionsfeathersjsfeathers-authentication

User's permissions in feathers.js API


I'm trying to create some REST API with user roles like admin, superadmin etc. I was trying to achieve this by using feathers-permissions module, but there are none working examples and the internet. Have you ever dealt with such task? What I do now is: feathers generate app and then feathers generate authentication. What should I do next?


Solution

  • The secret to implementing permissions and roles in Feathers is that Hooks really provide everything you need with all the flexibility you might want. There isn't really a a need to spend time looking for a separate module and learning it's API.

    Store the permissions (which are normally just strings) in an array on the user (or a separate permissions service based on the users ID) and then in a before hook check if the user is allowed to perform the operation the hook is registered as (here the permission is called messages::create), and if not throw a Feathers error:

    const { Forbidden } = require('feathers-errors');
    
    app.service('messages').hooks({
      before: {
        create: [ context => {
          // `params.provider` is set for any external access
          // usually we don't need to check permissions for internal calls
          const isExternal = !!context.params.provider;
    
          if(isExternal && !context.params.user.permissions.includes('messages::create')) {
            throw new Forbidden('You are not allowed to access this');
          }
        }]
      }
    });
    

    This pattern can also be implemented with any existing permissions module for Node. feathers-permissions is a simple module that allows to do this more easily.

    For more information also see the blog posts about Access Control Strategies in FeathersJS and Easy API Authorization with CASL and Feathers.