title: Passport Local Strategy not saving user in cookie or session
body: <p>I'm attempting to use passport with express 4 and authenticate with a local strategy. I'm trying to get a simple setup working but I'm have issues.</p>
  
  <p>I'm try to authenticate with an authorization middleware function... deserializeUser is never called, req.user is undefined and the user data is missing from both the sessions and cookies.</p>
  
  <p>My server.js file:</p>
  
  <pre><code>var express = require('express');
  var app = express();
  var path = require('path')
  
  var port = process.env.PORT || 3000;
  var argv = require('minimist')(process.argv.slice(2));
  var dust = require('express-dustjs')
  
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var session = require('express-session');
  var passport = require('passport');
  var LocalStrategy = require('passport-local').Strategy;
  var methodOverride = require('method-override');
  
  var authService = require('./app/services/auth.js')
  var dbConfig = require('./app/config.js')['documentDB'];
  var authService = require('./app/services/auth.js');
  
  /*
   * DUST JS
   */
  
  // Dustjs settings 
  dust._.optimizers.format = function (ctx, node) {
    return node
  }
  
  // Define custom Dustjs helper 
  dust._.helpers.demo = function (chk, ctx, bodies, params) {
    return chk.w('demo')
  }
  
  // Use Dustjs as Express view engine 
  app.engine('dust', dust.engine({
    // Use dustjs-helpers 
    useHelpers: true
  }))
  
  /*
   * STATIC ASSETS
  */
  app.use('/', express.static(__dirname + '/public'));
  app.set('view engine', 'dust')
  app.set('views', path.resolve(__dirname, './app/views'))
  
  app.use(logger('dev'));
  
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  
  app.use(cookieParser('X+a1+TKXwd26mkiUUwqzqQ=='));
  app.use(session({ 
    secret: 'X+a1+TKXwd26mkiUUwqzqQ==',
    resave: true,
    saveUninitialized: true,
    cookie : { secure : true, maxAge : (4 * 60 * 60 * 1000) }
  }));
  
  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:8080");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-AUTHENTICATION, X-IP, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
  });
  
  // Configure Passport authenticated session persistence.
  //
  // In order to restore authentication state across HTTP requests, Passport needs
  // to serialize users into and deserialize users out of the session.  The
  // typical implementation of this is as simple as supplying the user ID when
  // serializing, and querying the user record by ID from the database when
  // deserializing.
  passport.serializeUser(function(user, cb) {
    console.log('serializeUser : ', user);
    cb(null, user.id);
  });
  
  passport.deserializeUser(function(id, cb) {
    console.log('-------------------------------');
    console.log('-------------------------------');
    console.log('deserializeUser : ', id);
    console.log('-------------------------------');
    console.log('-------------------------------');
    authService.getAccountByID(id, function (err, user) {
      if (err) { return cb(err); }
      cb(null, user);
    });
  });
  
  passport.use('local', new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
    }, function(username, password, callback) {
  
      authService.authenticate(username, password, function(err, user) {
  
        if (err) {
          console.log("ERR &gt;&gt; ", err);
          return callback(err, false, err);
        }    
  
        return callback(err, user);
  
      }); 
    })
  );
  
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(methodOverride());
  /*
   * ROUTES
  */
  
  app.use('/', require('./app/routes/index.js')(passport));
  app.use('/prototypes/', require('./app/routes/prototypes.js'));
  app.use('/auth', require('./app/routes/auth')(passport));
  
  /*
   * APP START
   */
  
  app.listen(port, function () {
    var msg = 'Express started &gt; ';
  
    console.log('Express started &gt;&gt; ');
    console.log('  env: ', process.env.NODE_ENV);
  
  }).on('error', function(err){
      console.log('ON ERROR &gt;&gt; ');
      console.log(err);
  });
  
  process.on('uncaughtException', function(err) {
      console.log('ON UNCAUGHT EXCEPTION &gt;&gt;');
      console.log(err);
  });
  </code></pre>
  
  <p>The middleware function and route.</p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  var controller = require('../controllers/index.js');
  
  module.exports = function(passport) {
  
    router.get('/', controller.index);
  
    router.get('/test', verifyAuth, function(req, res) {
      return res.status(200)
        .json({"req.isAuth" : req.isAuth});
    });
  
    return router;
  
  };
  
  function verifyAuth(req,res,next) {
  
    console.log('req.cookies : ', req.cookies);
  
    console.log('req.login', req.login);
    console.log('req.isAuthenticated : ', req.isAuthenticated);
    console.log('req.session', req.session);
    console.log('req.user : ', req.user);
  
    if ( !req.isAuthenticated() ) { 
       res.status( 400 );      // constant defined elsewhere, accessible here
       return res.end('Please Login'); // or a redirect in a traditional web app, 
    }                                   // as opposed to an SPA
    next();
  }
  </code></pre>
  
  <p>Here is the login route:</p>
  
  <pre><code>router.post('/login', function(req, res, next) {
  
      passport.authenticate('local',  function(err, user, info) {
        if (err || !user) {
          return res.send(500, info);
        }
  
        req.login(user, function(err) {
          if (err) {
            return next(err);
            console.log('ERROR &gt; ', error);
          }
  
          return res.json(200, user);
        });
      })(req, res, next);
  
  });
  </code></pre>