I am using node.js, express and passport and am having a continuous redirect to the login page. The strange thing is that the application is validating the user/passport, but then it renders the login page again.
How can I get this to render the index page upon authentication? Is there something wrong with the session, such that it doesn't carry the authentication over from login to index?
var mongoose = require('mongoose/');
mongoose.connect('mongodb://localhost/testdb');
passport = require('passport')
LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
var Schema = mongoose.Schema;
var UserDetail = new Schema({
username: String,
password: String
}, {
collection: 'userInfo'
});
var UserDetails = mongoose.model('userInfo', UserDetail);
passport.use(new LocalStrategy(function(username, password, done) {
process.nextTick(function() {
UserDetails.findOne({
'username': username,
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
console.log("no such user...")
return done(null, false);
}
if (user.password != password) {
console.log("password doesn't match..")
return done(null, false);
}
console.log('found user')
return done(null, user);
});
});
}));
router.get('/', passport.authenticate('local', { failureRedirect: '/login' }), function(req, res) {
res.render('index', { title: 'theTitle' });
});
router.post('/login', passport.authenticate('local', {
failureRedirect: '/login'}),
function(req, res) {
console.log('success, redirecting to index page...')
res.redirect('/');
}
);
This is in my login.js file:
router.get('/', function(req, res) {
res.render('login', { title: 'login' });
});
It follows the following path:
GET / 302 17.735 ms - 68
GET /login 304 241.586 ms - -
GET /javascripts/jquery.min.js 200 25.971 ms - 84245
found user // this is being logged to the console
success, redirecting to index page... //also being logged to the console
POST /login 302 31.477 ms - 58
GET / 302 0.847 ms - 68
GET /login 200 21.153 ms - 1012
GET /javascripts/jquery-ui.min.js 200 51.780 ms - 239564
解决方案
I don't know Passport very well but it appears to me that passport.authenticate is failing on GET requests whilst passing on POST requests. Check to ensure you are passing the correct arguments in the GET request.