Marko vlaić Marko vlaić - 4 years ago 114
Node.js Question

Passportjs not saving user into session after login

I'm working on a simple social network and I want users to register and log in locally trough passport.js. I was following thistutorial and all code runs with no errors. However when I try to log in User passes the authentication but doesn't stay in session when I print

req.session
on index route. Here is my passport config file:

var LocalStrategy = require('passport-local').Strategy;
var User = require('../server/models/User.js');


module.exports = function(passport){
passport.serializeUser(function(user, done){
console.log('Serialized');
done(null, user._id);
});

passport.deserializeUser(function(id, done){
console.log('Deserialized');
User.findOne({id:id}, function(err, user){
done(err, user);
});
});

passport.use('local-login', new LocalStrategy({
usernameField:'email',
passwordField:'password',
passReqToCallback:true
},function(req, email, password, done){
console.log('Started');
User.findOne({email:email}, function(err, user){
console.log('Find query');
if(err){
console.log('Error occured');
console.error(err);
return done(err);
}
console.log('No error');
if(!user)return done(null, false, req.flash('loginMessage', 'No user with this email found'));
console.log('Got user', user);
if(!user.validatePassword(password, user.password)){
console.log('Not valid suka');
return done(null, false, req.flash('loginMessage', 'Wrong password!'));
}
console.log('Valid pass');
return done(null, user);
});
}));
}


This is my server.js file:

//Dependencies
const express = require('express');

const passport = require('passport');

const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const flash = require('connect-flash');

const path = require('path');

const morgan = require('morgan');

const mongoose = require('mongoose');

//Mongo setup
var mongoPath = 'mongodb://localhost:27017/party-net';

mongoose.connect(mongoPath, function(){
console.log('Party-net database connected');
});

//Passport
require('./config/passport.js')(passport);

//Application setup
var app = express();


//Static files
app.use('/views', express.static(path.join(__dirname, 'public', 'views')));
app.use('/scripts', express.static(path.join(__dirname, 'public', 'scripts')));
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));

//Middleware setup
app.use(morgan('dev'));

app.use(cookieParser());
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(session({secret:'muchsecretinfomustkipithir', saveUninitialized:true, resave:true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

//Routes
const index = require('./server/routes/index.js')(app, passport);
const api = require('./server/routes/api.js')(app, passport);

app.listen(8080, function(){
console.log('Server listening on port 8080');
});


Login route code:

app.post('/api/login', passport.authenticate('local-login', {
failureRedirect:'/'
}), (req, res) => {
console.log('Login route', req.isAuthenticated(), req.session);
//res.sendStatus(200);
res.redirect('/');
//res.redirect('/'+req.user.name+'/'+req.user.lastname);
});


And finally index route code:

app.get('/:firstname/:lastname', isLoggedIn , (req, res) => {
console.log('Requested', req.user, req.isAuthenticated());
res.send('Logged in successfully ' + req.params.firstname + ' ' + req.params.lastname);
});

Answer Source

Probably passport cannot deserialize user as you've used: User.findOne({id: id}, ... but serialized it by user._id so you should use:

User.findOne({ _id: id }, ...

or findById method:

User.findById(id, function(err, user) { ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download