oskosk / express-socket.io-session

Share a cookie-based express-session middleware with socket.io
https://www.npmjs.com/package/express-socket.io-session
MIT License
135 stars 14 forks source link

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

Open sunilpie1997 opened 3 years ago

sunilpie1997 commented 3 years ago
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 commented 3 years ago

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