Search code examples
node.jsmodulepassport.jshapi.js

Modularization in a nodejs/hapi app with passport


I'm using Hapi as an api framework on top of node.js. I'm also using passport for session management and authentication.

I'm struggling to find a way to separate out the logic of these different components. For now I have a separate file for most of my request handlers- I'd like to get all the handling logic out of the main app file. Whats holding me back are the dependencies on passport that some of the handlers have.

The problematic init code:

//init server
var server = new Hapi.Server(config.hostname, config.port);
server.pack.allow({ ext: true }).require(plugins, function (err) { 

    if (err) {
        throw err;
    }
});

//setup auth
var Passport = server.plugins.travelogue.passport;
Passport.use(new LocalStrategy( handlers.authUser ) );

While most of the routes are defined in a separate file (something like { method: 'POST', path: '/logout', handler: handlers.logout}) The problem is there are a couple routes that depend of Passport and I'm not sure how I would get access to the Passport variable in the handlers file.

Example route depending on passport:

{ method: 'POST', path: '/login', config: {
            handler: function (request, reply) {
                Passport.authenticate('local')(request, function (err) {
                    console.log("successful authentication?");
                    if (err && err.isBoom) {}
                    reply({message: "logged in"});
                }); }}}

I guess the real question is what is the best way to get a reference to the passport variable in a different file?

Thanks a lot.

Update: This is pre v8 api code, the way to register has been changed.


Solution

  • I recently dealt with this same issue. Turns out the request object that is passed into each handler has a reference to the passport plugin. I can't remember exactly what it is for Passport, but it's something like this:

    // ...
    handler: function(request, reply) {
      var passport = request.server.plugins.passport;
    }
    

    Take some time to explore the request object, I've found many of answers attached to that object. For example, if someone is logged in correctly with Travelogue and Passport, you can find their user profile on request.user.