Skip to content

Instantly share code, notes, and snippets.

@peterdemin
Last active May 8, 2023 17:10
Show Gist options
  • Save peterdemin/5829440 to your computer and use it in GitHub Desktop.
Save peterdemin/5829440 to your computer and use it in GitHub Desktop.
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)
@peterdemin
Copy link
Author

@mane-anant धन्यवाद!

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