express-socket.io-session icon indicating copy to clipboard operation
express-socket.io-session copied to clipboard

session object accessed in socket middleware preserves session even if i delete it using sessionStore.destroy() method

Open sunilpie1997 opened this issue 3 years ago • 1 comments

const sessionMiddleware = session({
  store: RedisSessionStore,
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false,
  cookie: {
      secure: false, // if true only transmit cookie over https
      httpOnly: true, // if true prevent client side JS from reading the cookie 
      maxAge: 1000 * 60 * 60 * 24 // session max age in miliseconds (1 day)
  }
});

io.use(sharedsession(sessionMiddleware, {
        autoSave: true
    }));
  
    io.use(async (socket,next) => {

        const socketSession = socket.handshake.session;

        // if user is not present, refuse connection
        if(!socketSession.user)
        {
            next(new Error("unauthorised event"));
        }
        else
        {
            // check if it's the first socket connection for this user
            if(!socketSession.socketId)
            {
                // allow connection
                socketSession.socketId = socket.id;
                socketSession.save();
                next();
            }
            else
            {
                // don't allow multiple connections
                next(new Error("already connected"));
            }

        }
    });

The problem is I am using Redis Store and if I delete session from store using 'sessionStore.destroy()', the session is still preserved. Actually the problem disappears if I remove this line

socketSession.socketId = socket.id;
socketSession.save();

sunilpie1997 avatar Jul 14 '21 12:07 sunilpie1997

I think may be it is creating duplicate session objects on calling 'save()' inside socket middleware.

sunilpie1997 avatar Jul 14 '21 12:07 sunilpie1997