Restrict multiple login for same user.

Can anyone help with implementing a middleware to restrict the user for multiple login on different browsers.

Are you talking about preventing two people from being logged in at the same time on different machines? What about two different browsers on the same machine? (e.g. Chrome & Firefox)

Are you looking to prevent the second person from logging in? Or are you looking to have the second person log in and disconnect the first login?

How are you going to tell when someone disconnects but doesn’t log off? (They just close their browser, or their network connection is lost, or any of a number of other situations?)

I’m not saying it can’t be done - just be prepared to handle all the problems associated with doing this. (In general, this is a really bad idea.)

I mean i want to restrict a user for login multiple times.

If a user1 is login in machine1 and the same user1 is login again on machine2 then in that case i want to logout the user1 from the 1st machine.

In that case user1 should only have one session that i want to handle in django using middleware.

It’s super easy. U just need to remove last known user session from Session model.

Use a Model to store user session keys.

  1. whenever user trying to login you need to fetch last stored session key from database.
  2. Based on last known session key remove session from Session Table with matching session key.
  3. Finally login user and then store the new session key to your database.

It working for me. It’s easy to implement.

1 Like

Django Session provides three fields expiry, session_data and session_key

And session is different on every login request

Then how can i fetch the last Session that user is login

You just need to store session key in separate Model. The model will store session key everytime a user Login.
Ex
class Visitor(models.Model):
user = models.OnetoOne(User)
sessionKey = models.charfield(max_lenghth=)

def loginView(request):

 # validate user credentials with authentication 
 # if valid fetch session key from visitor model
 # delete session with sessionkey from visitor model
#login user
# store new session key to visitor

Note: if user logs out manually. Then session is removed from session backend. Just make sure session key exists in session backend.

1 Like