Search code examples
node.jsmongodbexpresspassport.jssession-cookies

Limit session per User - ExpressJS


I am using mongoDB as a Database and passportjs for authentication.

I want to have a maximum of 3 sessions per user.

For that, I created a sessionCount field on my mongo document.

everytime the user logs in, I increment the count and when they log out, I decrement.

But the problem arises when the session auto-expires. The session count stays the same.

Q. is there any way to "detect" session expiration so that I could decrement that sessionCount field ?


Solution

  •     I am also facing the same kind of issue I solve it by using this way->
        
    
    
        app.use(function(req, res, next) {
            //Checking previously set cookie (if there is one)
            var session = JSON.parse(req.cookies['session'] || '');
            if (session && new Date(session.expires) < new Date()) {
                // decrement the count
            }
            next();
        });