title: Passport.js local authentication with Express.js 4
body: <p>I´m trying to use Passport.js with Express.js 4.0 but nothing is happening. I´m following below tutorial and trying to adapt it to fit Express.js 4.0 new routing features.</p>
  
  <p><a href="http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local" rel="nofollow">http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local</a></p>
  
  <p>So far I just want to try to login and get the failure redirect view with the proper message, as stated in the LocalStrategy.</p>
  
  <p>This is what I´m doing in app.js:</p>
  
  <p><strong>1.- Pulling the required modules and creating the app variable</strong></p>
  
  <pre><code>...
  var session = require('express-session');
  var mongoose = require('mongoose');
  var passport = require('passport');
  var LocalStrategy = require('passport-local').Strategy;
  var flash = require('connect-flash');
  var bcrypt = require('bcrypt-nodejs');
  
  var app = express();
  </code></pre>
  
  <p><strong>2.- Connecting to MongoDB database and ensure a Users Model to store users</strong></p>
  
  <pre><code>require('./models/db')(mongoose, 'mongodb://localhost/cms');
  
  var User = require('./models/user')(mongoose);
  </code></pre>
  
  <p><strong>4.- Configure Passport</strong></p>
  
  <pre><code>require('./config/passport')(passport, User, LocalStrategy);
  </code></pre>
  
  <p><strong>5.- Making Sure to include all the required Middleware</strong></p>
  
  <pre><code>app.engine('.html', require('ejs').__express);
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'html');
  
  app.use(favicon());
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded());
  app.use(cookieParser());
  
  app.use(session({
    secret: 'keyboardcat'
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(flash());
  
  app.use(express.static(path.join(__dirname, 'public')));
  </code></pre>
  
  <p><strong>6.- Route Handling</strong></p>
  
  <pre><code>var router = express.Router();
  
  router.use(function (req, res, next) {
  
    if (req.method === 'POST' &amp;&amp; req.url === '/login') {
      // Log #1
      console.log(passport);
  
      passport.authenticate('login', { 
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: true 
      });
  
    } else {
  
      next();
  
    }
  });
  
  router.route('/')
        .get(function (req, res) {
          res.render('index');
        });
  
  router.route('/login')
        .post(function (req, res) {
          console.log('Post on /login');
        })
        .get(function (req, res) {
          res.render('login', {
            message: req.flash('loginMessage')
          });
        });
  
  app.use('/', router);
  
  ... (Rest of app.js such as error handlers)
  </code></pre>
  
  <p><strong>This is how the Configuration of the Passport Strategy is set in ./config/passport.js</strong></p>
  
  <pre><code>module.exports = function (passport, User, LocalStrategy) {
  
    passport.serializeUser(function (user, done) {
      done(null, user.id);
    });
  
    passport.deserializeUser(function(id, done) {
      User.findById(id, function (err, user) {
        done(err, user);
      });
    });
  
    passport.use('login', new LocalStrategy({
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true 
    }, function (email, password, done) {
  
        User.findOne({ email: email }, function (err, user) {
  
          if (err) { 
  
            return done(err);
  
          }
  
          if (!user) {
  
            return done(null, false, { message: 'Incorrect username.' });
  
          }
  
          if (!user.validPassword(password)) {
  
            return done(null, false, { message: 'Incorrect password.' });
  
          }
  
          return done(null, user);
  
        });
  
      }
  
    ));
  
  };
  </code></pre>
  
  <p><strong>The Login View looks like this</strong></p>
  
  <p>As we can see the input names are set properly like in the Strategy.</p>
  
  <pre><code>&lt;% include header.html %&gt;
  
  &lt;% if (message.length &gt; 0) { %&gt;
    &lt;div&gt;&lt;%= message %&gt;&lt;/div&gt;
  &lt;% } %&gt;
  
  &lt;form action="/login" method="post" enctype="multipart/form-data"&gt;
    &lt;input type="text" name="email"/&gt;
    &lt;input type="password" name="password"/&gt;
    &lt;input type="submit" value="Log In"/&gt;
  &lt;/form&gt;
  
  &lt;% include footer.html %&gt;
  </code></pre>
  
  <p>Since there´s no users yet I was expecting to be redirected to <strong>'/'</strong> with the <em>'Incorrect username.'</em> message when submitting the form but instead the browsers stays in a loading state and nothing happens.</p>
  
  <p><em>A few thoughts...</em></p>
  
  <p>Am I calling to:</p>
  
  <pre><code>passport.authenticate('login', { 
    successRedirect: '/',
    failureRedirect: '/login',
    failureFlash: true 
  });
  </code></pre>
  
  <p>Where it should be called? What I want it here is to call it as middleware when making a POST to the login route.</p>
  
  <p>The <strong>Log#1</strong> is actually showing the passport object.</p>
  
  <p>I have a few days with this and I can´t figure out what´s happening... I hope someone can spot something, Thanks Much!.</p>