Zaid Iqbal Zaid Iqbal - 16 days ago 6
Node.js Question

Delete previous sessions if login from new device MEANJS

I want to remove previous session from MongoStore/sessionStore if a user login from new device. MEANJS is using


express-session
connect-mongo


to store sessions in mongodb. I did search on it but could not find a solution to fetch the list of sessions from db. Please help me here

MongoStore = require('connect-mongo')(session),
favicon = require('serve-favicon'),

module.exports.initSession = function (app, db) {
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
cookie: {
maxAge: config.sessionCookie.maxAge,
httpOnly: config.sessionCookie.httpOnly,
secure: config.sessionCookie.secure && config.secure.ssl
},
key: config.sessionKey,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection
})
}));
};

Answer

This should work, at least it's a good starting point for you

var async = require('async'); //npm install async --save
exports.removeSessionsForUser = function(req, res, next) {
    var userId = req.user ? req.user.id : undefined;
    if (!userId)
        return next(new Error('No user found in req. Exiting'));

    var store = req.sessionStore;
    var sessionsColl = store.db.collection('sessions');

    sessionsColl.find({
        'session.user': userId,
        // we are tryin to remove all sessions, you can leave current
        // '_id': { '$ne': req.sessionID }
    }, { _id : 1 }, function (err, userSessions) {
        async.each(userSessions, function (userSession, cb) {
            store.destroy(userSession._id, cb);
        }, function(notDone) {
            if(notDone)
                return next(new Error(notDone));

            res.send('ok');
        });
    });
}

This uses async.each, which is

async.each(Array, function(item, callback) {/* iterate */}, function(error) {/* end */});