Arnaud Rinquin Arnaud Rinquin - 4 months ago 85
Node.js Question

Node.js + express.js + passport.js : stay authenticated between server restart

I use passport.js to handle auth on my nodejs + express.js application. I setup a LocalStrategy to take users from mongodb

My problems is that users have to re-authenticate when I restart my node server. This is a problem as I am actively developing it and don't wan't to login at every restart... (+ I use node supervisor)

Here is my app setup :

app.configure(function(){
app.use('/static', express.static(__dirname + '/static'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret:'something'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});


And session serializing setup :

passport.serializeUser(function(user, done) {
done(null, user.email);
});

passport.deserializeUser(function(email, done) {
User.findOne({email:email}, function(err, user) {
done(err, user);
});
});


I tried the solution given on a blog (removed the link as it does not exist any more) using connect-mongodb without success

app.use(express.session({
secret:'something else',
cookie: {maxAge: 60000 * 60 * 24 * 30}, // 30 days
store: MongoDBStore({
db: mongoose.connection.db
})
}));


EDIT additional problem : only one connection should be made (use of one connexion limited mongohq free service)

EDIT 2 solution (as an edition as I my reputation is to low to answer my question by now

Here is the solution I finally found, using mongoose initiated connection

app.use(express.session({
secret:'awesome unicorns',
maxAge: new Date(Date.now() + 3600000),
store: new MongoStore(
{db:mongoose.connection.db},
function(err){
console.log(err || 'connect-mongodb setup ok');
})
}));

Answer

There's an opensource called connect-mongo that does exactly what you need - persists the session data in mongodb

usage example (with a reuse of mongoose opened connection) :

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sess');
app.use(express.session({
    secret:'secret',
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(
    // Following lines of code doesn't work
    // with the connect-mongo version 1.2.1(2016-06-20).
    //    {db:mongoose.connection.db},
    //    function(err){
    //        console.log(err || 'connect-mongodb setup ok');
    //   }
    {mongooseConnection:mongoose.connection}
    )        
}));

you can read more about it here: https://github.com/kcbanner/connect-mongo