Skip to content
loading...

Prevent Multiple Sessions for a User in your Django Application

Emmanuel Okiche on May 05, 2018

Welcome to my first tutorial on this platform. In this one i'm going to show you how to prevent a user account from having multiple sessions at the... [Read Full]
markdown guide
 

Nice! BTW in a real world app instead of logging out the other user(s) you would probably tell them "Hey, stop streaming 50 videos :D".

Having more than one session could be accidental: I'm logged in on the phone and on the computer and I would hate to be automatically logged out on the other device.

 

That's very true.
Thanks for your comment on my first post here. I really appreciate.
My approach could be useful when the partner to a cheat in a relationship picks up the phone and the cheat is logged in on my tinder-like app. The cheater could quickly rush to his/her computer and log out. (LIFE SAVER SCENARIO)
The idea was just to show how to create a custom middleware. Like i stated in while concluding, this might not be the best approach.

 

this one works for me:
class OneSessionPerUserMiddleware:
# Called only once when the web server starts
def init(self, get_response):
self.get_response = get_response

def call(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
if request.user.is_authenticated:
session_key = request.session.session_key

try:
logged_in_user = request.user.logged_in_user
stored_session_key = logged_in_user.session_key
# stored_session_key exists so delete it if it's different
if stored_session_key and stored_session_key != request.session.session_key:
Session.objects.get(session_key=stored_session_key).delete()
request.user.logged_in_user.session_key = request.session.session_key
request.user.logged_in_user.save()
except LoggedInUser.DoesNotExist:
LoggedInUser.objects.create(user=request.user, session_key=session_key)
stored_session_key = request.user.logged_in_user.session_key

# if there is a stored_session_key in our database and it is
# different from the current session, delete the stored_session_key
# session_key with from the Session table
if stored_session_key and stored_session_key != request.session.session_key:
Session.objects.get(session_key=stored_session_key).delete()

request.user.logged_in_user.session_key = request.session.session_key
request.user.logged_in_user.save()

response = self.get_response(request)

# This is where you add any extra code to be executed for each request/response after
# the view is called.
# For this tutorial, we're not adding any code so we just return the response

return response

 

class OneSessionPerUserMiddleware:

Called only once when the web server starts

def init(self, get_response):
self.get_response = get_response

How do you implement this code? Could you spell out where this code should reside? Which directories, files etc ...?

 

Gracias Excelente. me ayudo bastante βœ”πŸ˜ƒπŸ‘Œ

 

Thank you. I'm glad it was helpful to you. Gracias amigo

 

Is there a specific reason why you do this check with middleware (every request)? Why don't you just check once when the user logs in?

 

Did that for demonstration purpose just to show how middlewares work and how you could use them.
You could just trigger the check in a signal when the user logs in and it would still give you the same result.
I stated in the conclusion that this might not be the perfect solution for such feature.
Thanks for your comment and i'm glad you spotted that.
You're really smart.

All the best

 

After log in, I get error 'User' object has no attribute 'user_session'. How to fix this error?

 

Could you provide the code where this error points to.
This could be caused by different reasons.
Are you sure you're importing the User model from the right path?
Finally could you show where you used user_session in your code.

 

I got this error 'CustomUser' object has no attribute 'logged_in_user' full trace back dpaste.com/16N37EM

 

Hi. I replied to your comment and YouTube but guess you deleted it.
Here you go:

The code snippet you posted has expired but from your error message, it shows you created a CustomUser model and it has no reverse relation with the LoggedInUser model.
Make sure you set the CustomUser model as the OneToOneField for user in your LoggedInUser model.

That could be the possible cause for this because i used settings.AUTH_USER_MODEL for mine. Or you could just set the AUTH_USER_MODEL to your CustomUser model in your settings.py file and your code should work as expected.

 
code of conduct - report abuse