Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I listen to session destroyed event?

I'm currently develop an application with Sails.JS.

I want to count the number of online users and update it once they login/ logout or there session expire, but I don't know how to implement something like session destroyed event and can't update the number of online user whenever a session is expired without user logging out.

like image 986
Bhoomtawath Plinsut Avatar asked Jan 05 '15 16:01

Bhoomtawath Plinsut


2 Answers

As other said above, there is no such events in the default session implementation, Sails session are close to ExpressJs Session, i recommend you to read this article about ExpressJs Sessions :

http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/

Then one idea in order to achieve what you want could be to use a store and query inside of it.

Did you though about other solutions such as using socket.io (built in sails) and adding your users into a channel upon login and then simply counting user inside your channel ?

like image 78
MrVinz Avatar answered Oct 05 '22 00:10

MrVinz


You can wrap the session.destroy() function like so:

var destroyWrapper = buildDestroyWrapper(function(req){
    //do stuff after req.destroy was called
});


function buildDestroyWrapper(afterDestroy){
    return function(req){
        req.destroy();
        afterDestroy(req);
    };
}



//later, in your controller


function controllerAction(req,res,next){
    destroyWrapper(req);
}

this method allows you to handle destruction differently, depending on what callback you pass to buildDestroyWrapper. For example:

var logAfterDestroy = buildDestroyWrapper(function(req){
    console.log("session destroyed");
});
var killAfterDestroy = buildDestroyWrapper(function(req){   
    process.kill();
});


function buildDestroyWrapper(afterDestroy){
    return function(req){
        req.destroy();
        afterDestroy(req);
    };
}



//later, in your controller
function logoutAction(req,res,next){
    logAfterDestroy(req);
}
function killAppAction(req,res,next){
    killAfterDestroy(req);
}
like image 20
aclave1 Avatar answered Oct 05 '22 02:10

aclave1