Search code examples
feathersjsfeathers-hook

Structure restrictToOwner & restrictToRoles in feathersjs


I've read through the documentation, but I can't seem to get it right.

I'm trying to implement a restrictToOwner and restrictToRoles such that users with admin or superadmin role can access every other method in this service

const restrict = [
‎  authenticate('jwt'),
‎  restrictToOwner({
    idField: '_id',
    ownerField: '_id'
  })
]
‎
const restrictUser = [
  authenticate('jwt'),
 restrictToRoles({
   roles: ['admin', 'super-admin'],
   fieldName: 'roles'
 })
]

before: {
  all: [],
  find: [ ...restrictUser ],
  get: [ ...restrict, ...restrictUser],
  create: [ hashPassword() ],
  update: [ ...restrict, ...restrictUser, hashPassword() ],
  patch: [ ...restrict, ...restrictUser, hashPassword() ],
  remove: [ ...restrict, ...restrictUser ]
},

Solution

  • The trick is to not look for pre-done hooks since they are very limited while not doing very much. It is usually makes much more sense to implement custom logic like this in your own hooks.

    In your case we first want to check if the user is an admin and if not, either restrict the query to the user id or check if the user is allowed to access the individual entry. This can be done in a few lines of code:

    const { Forbidden } = require('@feathersjs/errors');
    
    const restrictUser = async context => {
      const { user } = context.params;
    
      // For admin and superadmin allow everything
      if(user.roles.includes('admin') || user.roles.includes('superadmin')) {
        return context;
      }
    
      if(!context.id) {
        // When requesting multiple, restrict the query to the user
        context.params.query._id = user._id;
      } else {
        // When acessing a single item, check first if the user is an owner
        const item = await context.service.get(context.id);
    
        if(item._id !== user._id) {
          throw new Forbidden('You are not allowed to access this');
        }
      }
    
      return context;
    }
    
    before: {
      all: [],
      find: [ authenticate('jwt'), restrictUser ],
      get: [ authenticate('jwt'), restrictUser ],
      create: [ hashPassword() ],
      update: [ authenticate('jwt'), restrictUser, hashPassword() ],
      patch: [ authenticate('jwt'), restrictUser, hashPassword() ],
      remove: [ authenticate('jwt'), restrictUser ]
    },
    

    This makes it fairly clear what is happening and you have full flexibility over every detail (like property names, how your data is structured or in what order it is being checked).