I am upgrading the express 4 and my passport is failing every time now. It is not even logging to the console in passport.use(new LocalStrategy.
It redirects the /failure every time without hitting any breakpoints
// Use the LocalStrategy within Passport.
// Strategies in passport require a `verify` function, which accept
// credentials (in this case, a username and password), and invoke a callback
// with a user object. In the real world, this would query a database;
// however, in this example we are using a baked-in set of users.
passport.use(new LocalStrategy(
function(username, password, done) {
console.log("LocalStrategy working...");
// 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, password, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user ' + username
});
} else {
return done(null, user);
}
})
});
}
));
app.use(cookieParser('keyboard cat'));
app.use(session({
secret: 'keyboard cat',
saveUninitialized: true,
resave: true
}));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
app.post('/login', passport.authenticate('local', {
failureRedirect: '/failure',
failureFlash: false
}),
function(req, res) {
res.cookie('userdata', req.user);
switch (req.user.role) {
case 'candidate':
res.redirect('/app/candidates');
break;
case 'employer':
res.redirect('/app/employers');
break;
case 'provider':
res.redirect('/app/providers');
break;
case 'admin':
res.redirect('/app/admin');
break;
default:
break;
}
});
Assuming you have all relevant code included the reason for the failure is likely missing body parser. The authentication strategy will try to find the username and password fields from req.body
and req.query
, and if there is no body parser used req.body
will be empty. The strategy will then fail straight away as it would have nothing to pass to your verify callback.
You need to make the Express application use relevant body parser, for example:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Have you included LocalStrategy?
var LocalStrategy = require('passport-local').Strategy;
app.use(express.cookieParser()); // read cookies
app.use(express.bodyParser()); // get information from html forms