Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Having some issues with node, express and passport playing nice.
var express = require('express');
var passport = require('passport');
var bcrypt = require('bcrypt');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./models').User;
var app = module.exports = express.createServer();
// Configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {layout: false});
app.use(express.session({secret: "awesome-o"}));
// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user._id) });
passport.deserializeUser(function(uid, cb){
console.log("Trying to deserialize user: "+uid);
User.findById(uid, function(err, user){
cb(err, user);
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
function(email, pass, done){
User.findOne({email: email}, function (err, user) {
// done takes error, user/false, and options hash
if (err)
return done(err);
if (!user)
return done(null, false, {message: "Couldn't find user"});
var crypted = bcrypt.hashSync(pass, user.salt);
if(user.hashpass != crypted)
return done(null, false, {message: "Bad password"});
// success!
return done(null, user);
passport.CreateSession = function (req, res, next) {
passport.authenticate('local', function(err, user, info){
if(err || !user)
return res.json({status: "Failure: "+err});
req.logIn(user, function (err){
return res.json({status: "Failure: "+err});
return res.json({status: "Authenticated"});
})(req, res, next);
passport.DestroySession = function (req, res) {
res.json({status: "Logged Out"});
passport.CheckSession = function (req, res, next) {
if(req.isAuthenticated()) { return next(); }
return res.json({status: "Failure: Authentication"});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.configure('production', function(){
// Routes'/session', passport.CreateSession);
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, function (req, res) { return {authenticated: "Yep, it's working"}});
//app.resource('images', require('./routes/images'));
//'/user', routes.images);
//app.get('/user/:id/images', routes.images);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment