我已经通读了文档,但我似乎无法正确理解。
我正在尝试实现限制所有者和限制角色,以便具有管理员或超级管理员角色的用户可以访问此服务中的所有其他方法
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 ]
},
诀窍是不要寻找预先完成的钩子,因为它们非常有限,但不会做太多。在你自己的钩子中实现这样的自定义逻辑通常更有意义。
在您的情况下,我们首先要检查用户是否是管理员,如果不是,请将查询限制为用户 ID 或检查是否允许用户访问单个条目。这可以通过几行代码完成:
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 ]
},
这使得正在发生的事情相当清楚,并且您对每个细节(例如属性名称,数据的结构或检查顺序(具有完全的灵活性。