Reputation: 1692
I need to retrieve a list sessions from sessionStore(MongoStore) and delete previous login session. I am using express-session to store sessions in DB.
var userId = req.query.userid;
if (!userId)
return res.status(400).send({
message: errorHandler.getErrorMessage('No user found in input request')
});
var store = req.sessionStore;
var sessionsColl = store.db.collection('sessions');
sessionsColl.find({
'session.passport.user': userId,
'_id': { '$ne': req.sessionID }
}, function (err, userSessions) {
console.log(userSessions);
if (userSessions !== null && typeof userSessions._id !== 'undefined') {
store.destroy(userSessions._id, function (err, dat) {
console.log(dat);
});
}
});
But in userSessions object i am getting an object instead of collection and I could not understand how can I fetch list of sessions from userSessions object
Upvotes: 4
Views: 3164
Reputation: 1
Below code solve my problem.
var store = req.sessionStore;
for(var sid in store.sessions){
var ses = JSON.parse(store.sessions[sid]);
if(ses.passport.user.username==core_id) {
store.destroy(sid, function (err, dat) {
});
}
}
Upvotes: 0
Reputation: 1692
Finally with the little I would be able solve the issue Here is my code
exports.logoutFromPreviousDevices = function (req, res) {
var userId = req.query.userid;
if (!userId)
return res.status(400).send({
message: errorHandler.getErrorMessage('No user found in input request')
});
var store = req.sessionStore;
var sessionsColl = store.db.collection('sessions');
sessionsColl.find({
// 'session.passport.user': userId,
// we are tryin to remove all sessions, you can leave current
// '_id': { '$ne': req.sessionID }
}, function (err, userSessions) {
if (userSessions !== null) {
userSessions.toArray(function (a, sessionsData) {
sessionsData.forEach(function (element, index) {
var data = JSON.parse(element.session);
if (element._id !== req.sessionID && req.query.userid === data.passport.user) {
store.destroy(element._id, function (destroyerr, dat) {
if (destroyerr)
return res.status(400).send({
message: errorHandler.getErrorMessage(destroyerr)
});
res.jsonp({ status: 'Previous session deleted' });
});
}
});
});
} else {
res.jsonp({ status: 'No session found' });
}
});
};
Upvotes: 2