Structure restrictToOwner & restrictToRoles in feathersjs

戏子无情 提交于 2019-12-13 03:26:13

问题


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 ]
},

回答1:


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).



来源:https://stackoverflow.com/questions/48595255/structure-restricttoowner-restricttoroles-in-feathersjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!