Skip to content
loading...

re: Prevent Multiple Sessions for a User in your Django Application VIEW POST

FULL DISCUSSION
 

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 ...?

code of conduct - report abuse