I'm working on an application using Node.js with the Express framework, using Passport for user authentication and MongoDB for storage. I'm having trouble figuring out why no matter which user tries to log in, the server decides that the logged-in user is the first user in the database, i.e. the first user who signed up.
When the server receives a post request to /login, it runs passport.authenticate to authenticate the user's credentials. From logging out to the console, it's clear that the proper user credentials are passed through, and even the session ID is correct, but wherever req.user is set, it is being set to the wrong user.
Here is a log in the console of what's happening to give you some idea:
get /user
--req.user is { salt: '$2a$10$NgPcBpvUqGq32IoWvsChd.',
hash: '$2a$10$NgPcBpvUqGq32IoWvsChd.SYva2e/aaPsfUcdN65aRm/D1oYJB3Ty',
username: 'daniel',
email: 'dan@dan.com',
_id: 515decd49fc3204ca1000001,
__v: 0,
songs: [] }
--req.session is { cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: { user: '515decdc9fc3204ca1000002' },
flash: {} }
As you can see, the user id is correct in req.sessions but incorrect in req.user.
The full code is available here: https://github.com/patrickmestabrook/song-swap
I would guess it is something to do with the serialize/deserialize process. Have you tried using _id.toString() in the serializeUser method?
Have you verified that the correct user is being returned inside models.js?
schemas.User.static('authenticate', function( username, password, done) {
console.log('schemas.User.static.authenticate');
console.log('-username is ' + username);
console.log('-password is ' + password);
this.findOne({ username: username }, function( err, user ) {
console.log('this.findOne inside authenticate, callback');
console.log('user.username is ' + user.username);
if ( err ) return done( err );
if ( !user ) return done( null, false );
user.verifyPassword( password, function( err, passwordCorrect) {
if ( err ) return done( err );
if ( !passwordCorrect ) { return done( null, false ); }
// return done( null, user );
done ( null, user );
})
})
})
Also check that the correct username and password are being passed to the authenticate method
passport.use(new LocalStrategy(function( username, password, done ) {
console.log('username: ' + username)
console.log('password: ' + password)
models.User.authenticate( username, password, function( err, user) {
// right now, this reports the WRONG USER DAMMIT
console.log('models.User.authenticate callback');
console.log('--username is ' + user.username);
// return done( err, user );
done( err, user);
});
}));