Yasser Yasser - 3 months ago 23
Node.js Question

Implement cookie based authentication in Node JS with Passport

Below is my server.js (app.js). I am using express with passport, for user authentication. But whenever I restart my node server user logsout.

I am very new to nodejs, I was wondering how I could implement a cookie based authentication. So that user does not log out even if the server starts. I'm sure theres some config change which I have not able to find.

// server.js

// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

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

var configDB = require('./config/database.js');

// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({ secret: 'yassers' })); // session secret
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
console.log('The magic happens on port ' + port);


Its logout when you restart your start because its stored in MemoryStore(RAM). Use mongoStore to store your session mongodb. Try below code:

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);

var mongoStore = new MongoStore({
  url: 'your mongo db url'  

  secret: 'your secret',
  saveUninitialized: true, // don't create session until something stored
  resave: false, //don't save session if unmodified
  store: mongoStore,
  cookie: {
    domain: 'domain name',    
    maxAge: 1000 * 24 * 60