4

I'm interesting to close (logout/sign out) all the user sessions in nodeJS.

req.logout() is closing only the current session of the user. But for my security panel I want to add the option to close ALL the user sessions. How can I do this?

I'm using MEAN.JS framework. With passport.js library and mongoDB to save the sessions:

// Express MongoDB session storage
app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    cookie: {
        maxAge: 15778476000,
        httpOnly: true,
        secure: false 
    },
    key: 'sessionId',
    store: new mongoStore({
        db: db.connection.db,
        collection: config.sessionCollection
    })
}));

Thank you very much.

Aral Roca
  • 5,442
  • 8
  • 47
  • 78
  • If you're not using sessions for any other purpose besides authentication, you could simply clean-up your `sessionCollection` with MongoDB `sessionCollection.remove({})` command. It'll force all active session to be closed and log all users out. – Leonid Beschastny Nov 16 '15 at 16:48
  • @LeonidBeschastny But then everyone is logged out? I think OP only wants to log out the current user? – Thomas Bormans Nov 16 '15 at 17:56
  • 1
    I would store the userId (Mongo, uuid, ...) inside the session and therefore also in your MongoDB. Next delete all the sessions in your MongoDB with that specific id (almost what @LeonidBeschastny said). – Thomas Bormans Nov 16 '15 at 18:02
  • @ThomasBormans I thought OP wanted to logout all users, but now I think you're right... – Leonid Beschastny Nov 16 '15 at 18:35
  • okey thanks! Yes, I was asking for all sessions from one user. But yes, if cleaning the session storage is working can I use `remove({user:userId})`. Thanks! – Aral Roca Nov 16 '15 at 19:47
  • what if my store cannot find with value, e.g using redis – Abhishek Anand Sep 13 '22 at 08:23

1 Answers1

6

Using connect-mongo, the userId is saved inside a String in mongoDB in sessions collection:

{
    "_id" : "J6fsgZ4d1zKp31ml1MRm18YCdlyhvce-",
    "session" : "{\"cookie\":{\"originalMaxAge\":15778475958,\"expires\":\"2016-05-17T23:47:27.301Z\",\"secure\":false,\"httpOnly\":true,\"path\":\"/\"},\"passport\":{\"user\":\"56420a5a8c6601ce29bbd1c1\"}}",
    "expires" : ISODate("2016-05-17T12:48:22.049Z")
}

Finally, I use this code to remove all his sessions:

var mongoose = require('mongoose'),
Schema = mongoose.Schema,
Session = mongoose.model('Session', new Schema(), 'sessions');


exports.signoutAllSessions = function(req, res) {
   var socketio = req.app.get('socketio');
   var userId = req.user.id;
   var filter = {'session':{'$regex': '.*"user":"'+userId+'".*'}};

   req.logout();
   res.redirect('/');

   Session.remove(filter,function(err,data){
       socketio.sockets.to(userId).emit('user.logout');
   });
};

And an API route call this method.

Aral Roca
  • 5,442
  • 8
  • 47
  • 78