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).
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")
})