Anusha Nilapu
Anusha Nilapu

Reputation: 1303

How to pass params into route handler pre - hapi.js

I am using route handler pre. I want to pass permission from router so my idea is check whether that logged in user has the permission or not? When I pass parm directly it throws an error.

Routing

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

Function Call

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

Error: Invalid routeConfig options (getUser)

Is there anyway to pass paramters into route?

Upvotes: 3

Views: 4295

Answers (2)

Anusha Nilapu
Anusha Nilapu

Reputation: 1303

Using route's "permission level" on the config object fixed my problem.

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

Here is the link for reference https://github.com/hapijs/hapi/issues/2652#event-360912937

Upvotes: 2

Clarkie
Clarkie

Reputation: 7550

You can assign properties to the request.pre object by giving the pre object an assign property:

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

Then in your route handler:

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

(That's assuming your Activity.checkVal(1) returns a function with the usual request, reply signature)

Following your edit:

I'd suggest you want to create a closure; something like this:

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

Upvotes: 0

Related Questions