Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js one session per user

How can I prevent my users to be logged in my system from two devices same time? So if user logged in from computer, when he logins from different computer, session on first automatically closes (don't need make it realtime).

I use node.js, express.js, mongoose, passport, connect-mongo (to store sessions in database).

like image 250
user3215609 Avatar asked Jan 29 '14 15:01

user3215609


People also ask

How do I handle multiple sessions in node JS?

Here, since sess is global, the session won't work for multiple users as the server will create the same session for all the users. This can be solved by using what is called a session store. We have to store every session in the store so that each one will belong to only a single user.

What is Express session in node JS?

Advertisements. HTTP is stateless; in order to associate a request to any other request, you need a way to store user data between HTTP requests. Cookies and URL parameters are both suitable ways to transport data between the client and the server. But they are both readable and on the client side.

How do I keep a session alive in node JS?

Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );


1 Answers

You can generate a token when user logs in and save it in your database against that user. Now with each request you will need to send this token to server. Consider the following scenario:

User A logs in from Computer A and a token 123 is generated and saved in database. Now whenever User A sends a request to server, it first checks for a valid session and then loads user's token from database to check if its valid.

Now User A logs into the website from Computer B and a token 456 is assigned to the user and is overwritten in database. Next time when User A sends a request from Computer A, server checks for a valid session and when it gets the token from database there is a mismatch indicating that user has logged in from somewhere else so current session is invalid.

like image 96
umair Avatar answered Oct 27 '22 23:10

umair