2015-07-20 52 views
1

我正在使用路由處理程序pre。我想通過路由器的權限,所以我的想法是檢查登錄的用戶是否有權限?當我直接傳遞parm時會引發錯誤。如何將params傳遞到路由處理程序pre - hapi.js

路由

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.")); 
    }); 

}

錯誤

Error: Invalid routeConfig options (getUser)

無論如何要傳遞參數進入路線嗎?

+0

你能提供有關你想達到什麼樣的多一點背景?也許還有一些代碼。 Activity.checkVal是一個返回函數的函數嗎? –

回答

1

在配置對象上使用路由的「權限級別」解決了我的問題。

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

0

您可以通過給pre對象的assign屬性分配屬性的request.pre對象:

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.")); 
     }); 
    } 
} 
+0

是的,但我必須將參數傳遞給pre函數。 –

+0

我已經嘗試過分配,但它期望函數(請求,回覆)而不是任何參數,它顯示:無效的routeConfig選項 –

+0

然後'Activity.checkVal(1)'需要返回具有正確簽名的函數。我認爲我們需要看到更多的代碼。 – Clarkie

相關問題