[Fixed] how to manage multiple session in express js

Issue

i am building a site that as two url (‘/’,’/admin’) session are conflicting
here is my app.js session code

  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(session({
      secret: "JHGF>,./?;;LJ8#$?,KL:>>>,,KJJJDHE",
      resave: true,
      saveUninitialized: true
  }));
  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(express.static(path.join(__dirname, 'public')));

  app.use('/', index);
  app.use('/admin', admin);

please how can i fix this?

here is index.js

   var express = require('express');

    var User = require('../models/user');
    var Admin = require('../models/admin');
     var Pandingpay = require('../models/pandingpay');
     var Confirmpay = require('../models/confirmpay');
    var passport = require('passport');
   var moment = require('moment');

   var router = express.Router();


  function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
    next();
  } else {
     req.flash("info", "You must be logged in to see this page.");
     res.redirect("/user/login");
   }
  };
    function Authenticated(req, res, next) {
   if (req.isAuthenticated()) {
      res.redirect('/user/dashboard/');
   }else {
    next();
    }
  };

    router.use(function(req, res, next){
      res.locals.currentUser = req.user;
      res.locals.errors = req.flash("error");
     res.locals.infos = req.flash("info");
     next();
     });

     /* GET home page. */
     router.get('/', function(req, res) {
     res.render('index',{
           title: 'Home'
      });
     });

   router.post('/login', function(req, res, next) {
        passport.authenticate('user-local', {failureFlash:true}, function(err, user, info) {
       if(!req.body.password || !req.body.username){
      req.flash("error", "Please enter your username and password");
      return res.redirect("/login");
    }
   if (err) { return next(err); }
   if (!user) { 
      req.flash("error", "Sorry  username or password is invalied!");
      return res.redirect('/login'); 
    }
       req.logIn(user, function(err) {
         if (err) { return next(err); }
       return res.redirect('/dashboard');
      });
     })(req, res, next);
     });

and here is my admin.js

   var express = require('express');

   var User = require('../models/user');
   var Admin = require('../models/admin');
   var Pandingpay = require('../models/pandingpay');
   var Confirmpay = require('../models/confirmpay');
    var passport = require('passport');
   var moment = require('moment');

   var routeradmin = express.Router();


   function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
      next();
     } else {
      req.flash("info", "You must be logged in to see this page.");
       res.redirect("/admin/login");
       }
      };



      routeradmin.use(function(req, res, next){
       res.locals.currentUser = req.user;
       res.locals.errors = req.flash("error");
         res.locals.infos = req.flash("info");
        next();
        });

       /* GET home page. */

      routeradmin.get('/login', function(req, res) {
          res.render('adminlogin');
         });


       routeradmin.post('/login', function(req, res, next) {
  passport.authenticate('admin-local', {failureFlash:true}, function(err, user, info) {
   if(!req.body.password || !req.body.username){
      req.flash("error", "Please enter your username and password");
      return res.redirect("/admin/login");
    }
   if (err) { return next(err); }
   if (!user) { 
      req.flash("error", "Sorry  username or password is invalied!");
      return res.redirect('/admin/login'); 
    }
  req.logIn(user, function(err) {
    if (err) { return next(err); }
    return res.redirect('/admin/allusers/' + user.username);
 });
})(req, res, next);
});

what i mean by conflicting is that the when an admin login instead of creating a new session for admin it uses the session of an already login useruser

Solution

If you want two separate session objects, one for regular usage and one for admin usage with no overlap between them, then you have to do two separate app.use('/path1', session(...)) and app.use('/path2', session(...)) statements so you have two separate session managers for different paths and make sure each has a different cookie name (using the name parameter to the session() options). And, then you have to design your URLs to be sub-paths of those so they get the right path.

Usually, people only use one session and then just keep a flag in the session whether it’s admin login or not and you can check that flag when needed.

Leave a Reply

(*) Required, Your email will not be published