Starting with Sails v0.9.8, you can use the onConnectand functions onDisconnectin config/sockets.jsto execute some code whenever a socket is connected or disconnected from the system. These functions give you access to the session, so you can use it to track the user, but keep in mind that just because the socket is disconnected does not mean that the user is logged out! They can have several tabs / windows that can be opened, each of which has its own socket, but they all share a session.
The best way to track is to use Sails PubSub methods. If you have a model Userand UserControllerwith a method login, you can do something like the last Sails build:
login: function(req, res) {
User.findOne({...credentials...}).exec(function(err, user) {
...
User.subscribe(req, user);
req.session.user = user;
});
}
onConnect: function(session, socket) {
if (session.user) {
User.subscribe(socket, session.user);
}
},
onDisconnect: function(session, socket) {
if (session.user) {
User.unsubscribe(socket, session.user);
if (User.subscribers(session.user.id).length == 0) {
console.log("User "+session.user.id+" is gone!");
}
}
}
source
share