对Feathers.js资源实施访问权限

时间:2017-11-02 22:03:09

标签: feathersjs

如何限制对通过Feathers.js公开的资源子集的访问权限?

例如,如何将CRUD操作限制为用户的tenantId或groupId?

到目前为止,我有点使用服务挂钩。下面的代码适用于“获取/查找”,但不适用于“放置/更新”。跟踪生成的mongo查询,在“更新”方案期间仅查询“_id”。似乎我的查询被忽略或覆盖。

// my-resource.hooks.js
module.exports = {
    before: {
        all: [
            function(hook) {
                const userGroupId = hook.params.userGroupId; 
                // NOTE: userGroupId gets extracted via an Express js hook from auth/header

                hook.params.query = {
                    ...hook.params.query,
                    userGroupId 
                }
                return hook;
            }
        ]
    }
}

更新

到目前为止,我已经扩展了feather-mongoose服务实现并更新了这段代码。似乎要做的伎俩,但我仍然想知道我是否遗漏了什么。

_get(id, params = {}) {
    params.query = params.query || {};

    const discriminator = (params.query || {})[this.discriminatorKey] || this.discriminatorKey;
    const model = this.discriminators[discriminator] || this.Model;
    let modelQuery = model
        .findOne({
            [this.id]: id,
            ...params.query
        });

1 个答案:

答案 0 :(得分:1)

为了知道是否允许用户修改单个资源,最好的方法是首先检索它,检查权限并在不允许的情况下抛出Feathers error

const errors = require('feathers-errors');

// my-resource.hooks.js
module.exports = {
  before: {
    all: [
      function(hook) {
        // NOTE: userGroupId gets extracted via an Express js hook from auth/header
        const userGroupId = hook.params.userGroupId;

        // If there is an id, get the entry first to check the permission
        if(hook.id !== undefined && hook.id !== null) {
          return hook.service.get(hook.id).then(entry => {
            if(entry.userGroupId !== userGroupId) {
              throw new errors.Forbidden('You are not allowed to access  this');
            }

            return hook;
          });
        }  

        // Otherwise just restrict the query
        hook.params.query = {
            ...hook.params.query,
            userGroupId 
        }

        return Promise.resolve(hook);
      }
    ]
  }
}