Track user online status offline in sails.js file

I need to find out the status of the user, that is, whether the user is online / offline using websockets in sails.js in my web application.

Please help me. Many thanks

+3
source share
1 answer

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:

// UserController.login

login: function(req, res) {

   // Lookup the user by some credentials (probably username and password)
   User.findOne({...credentials...}).exec(function(err, user) {
     // Do your authorization--this could also be handled by Passport, etc.
     ...
     // Assuming the user is valid, subscribe the connected socket to them.
     // Note: this only works with a socket request!
     User.subscribe(req, user);
     // Save the user in the session
     req.session.user = user;

   });
}


// config/sockets.js

onConnect: function(session, socket) {

  // If a user is logged in, subscribe to them
  if (session.user) {
    User.subscribe(socket, session.user);
  }

},

onDisconnect: function(session, socket) {

  // If a user is logged in, unsubscribe from them
  if (session.user) {
    User.unsubscribe(socket, session.user);
    // If the user has no more subscribers, they're offline
    if (User.subscribers(session.user.id).length == 0) {
      console.log("User "+session.user.id+" is gone!");
      // Do something!
    }
  }

}
+2
source

All Articles