how to manage multiple session in express js
Asked Answered
M

2

6

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

Mauromaurois answered 7/5, 2017 at 21:51 Comment(3)
What does "conflicting" mean? For us to help you, we need to know exactly what you observe so we can understand what problem you want help with. We probably also need to know what the index and admin functions are supposed to do and see their code. Usually, a specific route like this would be app.get('/', index) not app.use(), but it depends upon what you're trying to do with those routes. Need to see more code. Need for you to describe the exact problem. "Conflicting" is not a precise description.Performative
ok am going to update my code nowMauromaurois
my code has been updatedMauromaurois
P
8

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.

Performative answered 8/5, 2017 at 0:32 Comment(3)
thanks a lot it work but the flash messages is not changing for instance in '/user/login' when continue button is click without any login credential it generate an flash message 'Please enter your username and password' and this message stays on the page even if i reload the message is still there here is th link to page linkMauromaurois
[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.] If we do this, and suppose if session maxage is 5 minute. Now if admin logs in at 01:00, admin expiry should be at 01:05, if user logs in at 01:01, user expiry should be at 01:06. But as we are using only 1 session, both admin and user expiry will be 01:06 after user logs in. How to resolve this issue?Complaint
@AmanChaudhary - You get one expiration per session so you either have to live with the same expiration for admin vs. non-admin or adjust the expiration based on whether it's admin or not. If you really want long lived expiration for non-admin and short-expiration for admin, then separate sessions is probably easiest.Performative
L
0

I think it is possible that the flash widget is somewhere in the shared app? Rather than split out into the different paths?

Does that make sense

Lemmie answered 6/4, 2021 at 9:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.