Allowing only single active session per user in Django app Allowing only single active session per user in Django app python python

Allowing only single active session per user in Django app


There is indeed a lot of similar questions all over the place, but here is my solution.

When a user logins go over all active sessions and remove the ones with the same user.id. For smaller websites, this should do just fine.

# __init__.py# Logs user out from all other sessions on login, django 1.8from django.contrib.sessions.models import Sessionfrom django.contrib.auth.signals import user_logged_infrom django.db.models import Qfrom django.utils import timezonedef limit_sessions(sender, user, request, **kwargs):    # this will be slow for sites with LOTS of active users    for session in Session.objects.filter(        ~Q(session_key = request.session.session_key),        expire_date__gte = timezone.now()    ):        data = session.get_decoded()        if data.get('_auth_user_id', None) == str(user.id):            # found duplicate session, expire it            session.expire_date = timezone.now()            session.save()    returnuser_logged_in.connect(limit_sessions)


You can always use this approach though not recommended, it works.

my_old_sessions = Session.objects.all()for row in my_old_sessions:   if row.get_decoded().get("_username") == request.user.username:      row.delete()

You would implement the code above in your login() function right before authenticating the user.

This of course only works if you have a login() function method that stores the USERS username in his session like follows:

request.session["_username"] = request.user.username

If you use this approach just remember to empty your database of all of your sessions before running your server after you've made these changes because it will raise KeyLookUp errors.


I feel that, somehow, django.contrib.auth signals could help here. On login, invalidate older user sessions.