0

我在数据库中有两个用户,他们有相同的电子邮件和密码,但角色不同。它看起来像:

  email        pass   roles
+------------+------+-------
 1@gmail.com   123    user
 1@gmail.com   123    admin

当用户尝试登录时,我发送带有参数的请求

{
    email:"1@1.ru"
    password:"123"
    roles:"user"
    strategy:"local"
}

问题是:我如何通过角色识别用户(当我使用参数角色从前端请求发送时:“用户”用户必须通过角色“用户”登录,当角色:“管理员” - 由管理员)

这是我的来自 auth 的钩子

app.service('authentication').hooks({
before: {
  create: [
    authentication.hooks.authenticate(['local', 'jwt'])
  ],
  remove: [
    authentication.hooks.authenticate('jwt')
  ]
},
4

1 回答 1

2

用户(或其他经过身份验证的)实体应该是唯一可识别的,因此为一个用户存储角色列表更有意义,如下所示:

  email        pass   roles
+------------+------+-------
 1@gmail.com   123    user,admin

然后可以使用该用户登录并在挂钩中检查角色列表是否包含您需要的内容:

const { Forbidden } = require('feathers-errors');

function hasRole(name) {
  return function(context) {
    const { user = {} } = context.params;

    if(!user.roles || !user.roles.split(',').includes(name)) {
      throw new Forbidden('You are not allowed to access this');
    }
  }
}

app.service('myservice').hooks({
  before: {
    get: [ hasRole('user') ],
    find: [ hasRole('user') ],
    create: [ hasRole('admin') ],
    patch: [ hasRole('admin') ],
    update: [ hasRole('admin') ],
    remove: [ hasRole('admin') ]
  }
})
于 2017-11-29T17:14:49.220 回答