如何将params传递给路由处理程序pre-hapi.js

时间:2015-07-20 13:04:52

标签: routing hapijs

我正在使用路由处理程序。我想从路由器传递权限,所以我的想法是检查登录用户是否具有权限?当我直接传递parm时会抛出错误。

路由

 server.route({ 
     method: 'GET', 
     path: '/getUser', 
     config: {
         handler: User.getUser, 
         pre: [
              { method: Activity.checkVal(1) }
         ]
     }
 });

功能调用

exports.checkVal = function(parm, request, reply) {
    Jwt.verify(request.headers.authorization.split(' ')[1],  Config.key.privateKey, function(err, decoded) {    
        var permissions = permissionsSet();
        if(permissions.indexOf(request.pre.val) > -1)
            return reply().continue();
        else
            reply(Boom.forbidden( "You don't have permission." ));
    });

}

错误

  

错误:无效的routeConfig选项(getUser)

无论如何都要将参数传递给路线?

2 个答案:

答案 0 :(得分:2)

使用路由"权限级别"在配置对象上解决了我的问题。

var checkVal = function (request, reply) {

     var permissionLevel = request.route.settings.app.permissionLevel;

     ... // decide whether to allow
};

server.route({
  config: {
      app: {
        permissionLevel: 1  // "permission level" for this route
    },
    pre: [
        checkVal   
    ]
  },
  method: 'GET',
  path: '/',
  handler: function (request, reply) {

    ... // do whatever
  }
});

以下是参考https://github.com/hapijs/hapi/issues/2652#event-360912937

的链接

答案 1 :(得分:0)

您可以通过为request.pre对象提供pre属性来为assign对象指定属性:

 server.route({ 
      method: 'GET', 
      path: '/getUser', 
      config: {
          handler: User.getUser, 
          pre: [
               { method: Activity.checkVal(1), assign: 'someVar' }
          ]
      }
  });

然后在你的路线处理程序中:

 User.getUser = function (request, reply) {
      console.log(request.pre.someVar);
 }

(假设您的Activity.checkVal(1)返回一个通常为request, reply签名的函数)

关注您的修改:

我建议你想创建一个闭包;像这样的东西:

exports.checkVal = function(parm) {

    return function preHandler(request, reply) {

        Jwt.verify(request.headers.authorization.split(' ')[parm], Config.key.privateKey, function(err, decoded) {    
            var permissions = permissionsSet();
            if(permissions.indexOf(request.pre.val) > -1)
                return reply().continue();
            else
                reply(Boom.forbidden( "You don't have permission." ));
        });
    }
}