node.jstwitter-oauthpassport.jslocomotivejs

Best way to setup locomotivejs with passport-twitter?


I'm trying to configure passport-twitter in my locomotive project.

The problem is that nothing happens after hitting the /auth/twitter url.

Edit: I hit the controller but twitter seems to not be invoked.

What I did was set a match to /auth/twitter at routes.js and mapped this to an auth_controller.js

Something like the code below:

I really don't know if that's the right way to use it with locomotive, any help will be very appreciated.

Cheers, Fabio


Solution

  • Passport needs to be configured first. An example on how to do that can be found here. In the case of LocomotiveJS, the obvious place of putting that configuration would be an initializer:

    // config/initializers/10_passport_twitter.js <-- you can pick filename yourself
    module.exports = function(done) {    
      // At least the following calls are needed:
      passport.use(new TwitterStrategy(...));
      passport.serializeUser(...);
      passport.deserializeUser(...);
    };
    

    Next, configure sessions and initialize Passport:

    // config/environments/all.js
    module.exports = {
      ...
      // Enable session support.
      this.use(connect.cookieParser());
      this.use(connect.session({ secret: YOUR_SECRET }));
      // Alternative for the previous line: use express.cookieSession() to enable client-side sessions
      /*
        this.use(express.cookieSession({
         secret  : YOUR_SECRET,
         cookie  : {
           maxAge  : 3600 * 6 * 1000 // expiry in ms (6 hours)
         }
        }));
      */
    
      // Initialize Passport.
      this.use(passport.initialize());
      this.use(passport.session());
      ...
    };
    

    Next, configure routes:

    // config/routes.js
    this.match('auth/twitter/', 'auth#twitter');
    this.match('auth/twitter/callback/', 'auth#callback');
    

    Because passport.authenticate is middleware, it's easier to use a before hook in your controller:

    // app/controllers/auth_controller.js
    ...
    AuthController.twitter = function() {
      // does nothing, only a placeholder for the following hook.
    };
    AuthController.before('twitter', passport.authenticate('twitter'));
    
    AuthController.callback = function() {
      // This will only be called when authentication succeeded.
      this.redirect('/list');
    }
    AuthController.before('callback', passport.authenticate('twitter', { failureRedirect: '/auth/twitter' })};
    

    Disclaimer: I haven't tested the code above, I'm basing it on my own code which I recently used in a project, and which uses passport-local instead of passport-twitter. However, the basics are pretty much similar, apart from the callback-URL which isn't needed for passport-local.