User sessions Node.js

Hi everyone,

I’m trying to implement logout from all devices functionality or specific devices.

I currently store express-sessions in a database like this where I have 3 columns:

sid sess expire
AH_oe3YCEahqcKA2VxxHp_Xf {“cookie”:{“originalMaxAge”:7200000,“expires”:“2021-01-15T11:11:02.164Z”,“secure”:false,“httpOnly”:true,“path”:"/"},“flash”:{},“passport”:{“user”:“106”}} 2021-01-15 12:11:03

For this I have used the connect-pg-simple store.

I have been trying to solve 2 problems, but I could not come up with any solutions.

I want to store user-agent and ip-address, but how do I store that?

I also want to display the sessions for logged in user(s) and allow user(s) to revoke any previous sessions from any device. Similar to how Google or Facebook allows you to log out devices.

For displaying it, I thought of making a select query e.g. selecting session by doing something like this:

const id = req.user.id;
pool.query(`SELECT * FROM session WHERE user = $1`, [id], (err, results) => {
      if (err) {
        throw err;
      }

So I would get the ID of the currently logged in user and select sessions that belong to the logged in user, but not sure how I could select userid from that JSON string.

I’m also not sure if this would work and if this is a good approach or if there’s a better way to do it.

There is an article explaining how to do it using JWT, but I want to do this with sessions instead.

I will gladly provide more code that I have or information about the packages that I have used. I have searched, but I could not find any information.

Any help would be appreciated. Thanks.

While storing a session, along with 3 existing columns why don’t you store another column with userId in it so you can query by user id?

I would do that, which would also solve all of the problems above, because I could easily query it, but I’m not sure how. I have followed the instructions for “connect-pg-simple” to store the session data.

I don’t think we can pass an extra query while saving a session using that package, worth creating a GitHub issue asking for help, they might be able to help you with a solution for your use case or suggest otherwise.

1 Like

Okay I will try to do that. Thank you.

1 Like