skip to Main Content

A user can loggin in a website with multiple devices so I create multiple sessions with express-session having redis as a store. Now for security reasons, on user password update, I want to logout all the user sessions and force him to login on all his other devices. I found this NodeJS logout all user sessions and it is using mongodb as a store and some special queries however in redis I am not sure i can do the same thing since the normal redis ( not redis JSON). So the question is how to destroy all user session with express-session on redis ?

UPDATE
Just to clarify, I want to delete all sessions of a specific user. so for example I have 10 users and every user is logged in with his laptop and phone which would make in total 20 sessions. I am looking to logout all sessions of a user which would clear only 2 sessions ( the laptop and phone session).

2

Answers


  1. Chosen as BEST ANSWER

    Solution
    I solved this issue by modifying sessionID keys in redis like this with a certain pattern:

    session:${userId}:${randomId}

    So all a user can have multiple sessions but his sessionIDs will begin with the same pattern. If you want to delete all sessions of one user you just have to look for the keys that begin with "session:${userId}:*" and delete them. See below:

    const generateSessionKey = (req) => {
      const userId = req.session?.user?.id ? req.session.user.id : '';
      const randomId = Math.random().toString(36).substring(2);
      return `session:${userId}:${randomId}`;
    };
    
    app.use(
      session({
        store: new RedisStore({ client: redisClient, prefix: 'session:' }),
        secret: 'your-secret-key',
        resave: false,
        saveUninitialized: false,
        genid: generateSessionKey, // Use the custom session key generator
      })
    );
    
    //to delete the sessions 
    app.post("/clear-sessions",async (req,res,next)=>{
      const sessions = await redisClient.keys(`session:${req.user.id}:*`);
      await redisClient.del(sessions);
    res.send("OK")
      
    })


  2. You can do this by calling clear on your session store object:

    store.clear(callback)
    Optional

    This optional method is used to delete all sessions from the store. The
    callback should be called as callback(error) once the store is cleared.

    Source: https://expressjs.com/en/resources/middleware/session.html

    Implementation for the Redis store: https://github.com/tj/connect-redis/blob/5f5976ea3a94cf8a62efa5701facc4d1200ae78a/index.ts#L130

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search