Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
django middleware that disallows concurent user login while allowing such for administrators
from one_session_per_user.models import User, Visitor
from django.contrib.sessions.models import Session
class OneSessionPerUserMiddleware(object):
"""http://stackoverflow.com/a/1814797"""
def process_request(self, request):
if isinstance(request.user, User):
current_key = request.session.session_key
if hasattr(request.user, 'visitor'):
active_key = request.user.visitor.session_key
print active_key, current_key
if active_key != current_key:
Session.objects.filter(session_key=active_key).delete()
request.user.visitor.session_key = current_key
request.user.visitor.save()
else:
Visitor.objects.create(
pupil=request.user,
session_key=current_key,
)
class Visitor(models.Model):
pupil = models.OneToOneField(User, null=False)
session_key = models.CharField(null=False, max_length=40)
@pcraston
Copy link

pcraston commented Feb 18, 2014

Great snippet!

Since I needed this in my applications I created a django package (https://github.com/pcraston/django-preventconcurrentlogins) which is now on pypi (pip install django-preventconcurrentlogins).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment