Search code examples
node.jssessionsails.js

Current session id in sails js


I want to delete all sessions from all devices by one click in sails.js. How to get the current session id?

For example:

console.log(req.session.sessid) // sess:jV-M6_ZNCp-8x_jYPbSfbUilXd_T85i_

sails.js version 1.1.0-3


Solution

  • All sessions are unaware of which user they belong to unless you've mapped the session in a persistent storage system like Redis/Memcached cache or MySQL, MongoDB database.

    One of the many solutions I could think of is as below:

    • Create a model in your sails app which can be called SessionMapper

      • Add three columns: userID, sessionID, and isActive (boolean).
    • Now whenever a user signs in, create an entry in this model/table.

    • Create a middleware through which all API requests (except /login and public APIs) will flow
      • This middleware will check if the current session is still active -- acting like an extra layer of authentication.
        • If the session is active, grant access / next()
        • if the session is invalid or isActive === false, log out the user internally and redirect to login page with some message.

    To sign-out an users all active sessions, set isActive = false for userID = <user-id> in SessionMapper model.

    Note: This method will increase a lot of READ operations on the datasource which is connected to SessionMapper. Move it to a better and efficient solution like Redis/Memcached if it hurts the primary operations.

    I hope this pseudo code help you achieve your task. @tspentzas, the next time when you seek for a solution-- kindly add whatever you've tried so far in your question for the community to help you in a better way.