Skip to content

Instantly share code, notes, and snippets.

@PatrickHeneise
Created March 20, 2012 06:38
Show Gist options
  • Save PatrickHeneise/2132062 to your computer and use it in GitHub Desktop.
Save PatrickHeneise/2132062 to your computer and use it in GitHub Desktop.
passport.js with flatiron.js, union and director
var flatiron = require('flatiron')
, connect = require('connect')
, path = require('path')
, fs = require('fs')
, plates = require('plates')
, director = require('director')
, util = require('util')
, keys = require('./auth_keys')
, passport = require('passport')
, TwitterStrategy = require('passport-twitter').Strategy
, union = require('union');
passport.use(new TwitterStrategy({
consumerKey: keys.twitter.consumerKey,
consumerSecret: keys.twitter.consumerSecret,
callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
console.log("strategy");
// asynchronous verification, for effect...
process.nextTick(function () {
console.log("strategy tick");
return done(null, profile);
});
}
));
passport.serializeUser(function(user, done) {
console.log("serialize");
done(null, user);
});
passport.deserializeUser(function(obj, done) {
console.log("deserialize");
done(null, obj);
});
var router = new director.http.Router();
var server = union.createServer({
before: [
connect.cookieParser("secret"),
connect.session(),
passport.initialize(),
passport.session(),
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
},
connect.static('public')
]
});
router.get('/auth/twitter',
passport.authenticate('twitter'),
function(){}
);
router.get('/auth/twitter/callback',
passport.authenticate('twitter', { failureRedirect: '/login' }),
function() {
this.res.writeHead(302, {
'Location': 'login.html'
});
this.res.end();
});
router.get(/logout/, function() {
// req.logout();
this.res.writeHead(302, {
'Location': '/'
});
this.res.end();
});
// GET /
// Main function
router.get('/', function () {
console.log("GET /");
var self = this;
// fs.get etc.
})
});
// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
server.listen(3000, function () {
console.log('Application is now started on port 3000');
});
@jaredhanson
Copy link

I'm having some luck getting the Twitter redirect and callback routes invoked, with Passport as middleware, by doing this:

router.get('/auth/twitter',
  function() {
    var self = this;
    function next() {
      // wrap union-style next
      console.log('next wrap')
      self.res.emit('next');
    }

    passport.authenticate('twitter')(this.req, this.res, next);
  }
);

router.get('/auth/twitter',
  function(){}
);

router.get('/auth/twitter/callback',
  function() {
    var self = this;
    function next() {
      // wrap union-style next
      console.log('next wrap callback')
      self.res.emit('next');
    }

    // This is failing with the following error:
    //   Cannot read property 'oauth_token_secret' of undefined
    // Maybe related to the session bug you mentioned.
    passport.authenticate('twitter')(this.req, this.res, next);
  }
);

router.get('/auth/twitter/callback', 
  function() {
    this.res.writeHead(302, {
      'Location': 'login.html'
  });
  this.res.end();
});

Looks like director doesn't support multiple functions on a route in the same way Express does, so I put the middleware in separate routing declarations. I also adapted the Passport authenticate call, so that it works with the way director dispatches req and res as properties of this, rather than function arguments. I'm sure that wrapper could be abstracted out and made reusable.

I still get a failure when attempting to access the session, so I'm hoping your investigation yields some insight on that problem.

Awesome that your pursuing this! Once its figured out, I'll add some example code so that others can get up and running quickly.

@PatrickHeneise
Copy link
Author

Thanks a lot!

I'm not sure if I should further pursue it. Even if I figure that out, there'll be the next problem right there tomorrow. I just set up the project in Express.js and within 10 minutes I'm at the same point which took me 5 evenings in flatiron. I think it just needs some more time.

@distracteddev
Copy link

Hey Jared,

I am picking up where Patrick left off. However, I am currently only using local authentication.

I've got it working, but I've had to make some hacky changes to flatiron and passport. I want to be able to do as you suggested and come up some example code that works with a vanilla passport/flatiron install but I need your help in moving my "hacky" work-arounds to stable solutions that can be contained within the passport module. Where can I reach you for some questions on this?

Thanks!

@jaredhanson
Copy link

Sounds great. Send me email to gmail user jaredhanson.

@steeleforge
Copy link

Anyone successfully use passport in flatiron?

@distracteddev
Copy link

Hey Steele, check out this branch of Passport:

https://github.com/jaredhanson/passport/tree/flatiron

I am currently using the two together, however, this is only for plain authentication. I have yet to try the oAuth, but I dont see any reason why it would not work.

However, just keep in mind that you will have to use a few tricks as Jared mentioned above to get it working. Here are the relevant snippets from my code:

// User is a flatiron/Resourceful model factory here. The set up of this is not shown below.
u = User.new(
    {
        "username": "test_user",
        "password": "secret",
        "email": "[email protected]"
    }
);

u.save();

function findByUsername(username, done) {
  User.find({"username":username}, function(err, user) {
    if (err) {
        return done(err, null);
    }
    else if (user) {
        return done(null, user[0]);
    }
    else {
        return done(null, null);
    }
  });
}

passport.use(new LocalStrategy(
  function(username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      // Find the user by username.  If there is no user with the given
      // username, or the password is not correct, set the user to `false` to
      // indicate failure and set a flash message.  Otherwise, return the
      // authenticated `user`.
      findByUsername(username, function(err, user) {
        if (err) { return done(err); }
        if (!user) { return done(null, false, { message: 'Unkown user ' + username }); }
        debugger;
        console.log(password);
        console.log(user.password);
        if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
        return done(null, user);
      })
    });
  }
));


passport.serializeUser(function(user, done) {
  done(null, user.username);
});

passport.deserializeUser(function(username, done) {
  findByUsername(username, function (err, user) {
    done(err, user);
  });
});

App.router.path('/', function() {
    this.post('/login',
        function() {
            self = this;
            function next() {
                console.log('next wrap');
                self.res.emit('next');
            }
            passport.authenticate('local', function(err, user) {
                console.log(user);
                if (err) { self.res.end("SERVER ERROR\n") }
                if (!user) { self.res.end("false") }
                else {
                    self.req.logIn(user, function(err) {
                        if (err) {throw err}
                        self.res.writeHead(200, {'Content-Type': 'text/html',
                            'Authentication': JSON.stringify(self.req._passport.session)});
                        self.res.end("true");
                    });

                }
            })(this.req, this.res, next);
        }
    );
});

@travist
Copy link

travist commented Aug 28, 2012

I believe I got this working with a simple package.

https://npmjs.org/package/flatiron-passport
https://github.com/travist/flatiron-passport

Please read the README.md on how to use. For the most part, it is a pretty simple wrapper around passport that makes it work within flatiron. I have only so far tested LocalStrategy, but it should work with others since I basically maintained the API between the two. Please test this and let me know if this works for you guys.

@robert52
Copy link

Hi,

I'm having some trouble the debugger says that "req" has no method "isAuthenticated". I'm checking if the user is authenticated in the before hook to not go all the way up to the app's router. What do you think that the problem might be.

app.use(flatiron.plugins.http, {
  before : [
    function(req, res) {
      req.originalUrl = req.url;
      res.emit('next');
    },
    connect.cookieParser(),
    connect.session({ secret : 'keyboard cat' }),
    passport.initialize(),
    passport.session(),
    function(req, res) {

      if (!/^\/dashboard$|dashboard\/.*$/.test(req.url)) {
        return res.emit('next');
      }

      if (req.isAuthenticated()) {
        return res.emit('next');
      }

      res.redirect('/');
    },
    ecstatic(path.join(__dirname, './public'), {
      autoIndex : false,
      cache : "0, no-cache, no-store, must-revalidate"
    }) //cache control was turned off
  ]
});

Robert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment