Reputation: 972
What am I doing wrong? It always redirect to failure page but I cant debug.
// passport
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('./models/user.js').Model;
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
console.log('entrou');
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);
});
}
));
// login
app.get('/login', user.login);
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
})
);
Upvotes: 2
Views: 3383
Reputation: 120
I had some issues too with passport.js not authenticating. So here it is how it works for me:
/**
* Local authentication strategy
*
*/
passport.use('local', new LocalStrategy(function(username, password, done) {
//async code waits until next()
process.nextTick(function() {
//searches the database for the user
//that matches the username|e-mail and password provided
models.User.checkCredentials(username, password, function(err, user) {
if (err) {
return done(err);
}
//user is not found
if (!user) {
return done(null, false, {message: 'Unknown user ' + username});
}
return done(null, user);
});
});
}));
Log in a user
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
// if user is not found due to wrong username or password
if (!user) {
return res.render('login', {
//you can send a message to your view
message: 'Invalid username or password'
});
}
//passport.js has a logIn user method
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/');
});
})(req, res, next);
});
Upvotes: 2