Allowing only single active session per user in Django app

前端 未结 3 815
孤城傲影
孤城傲影 2020-12-25 13:02

I want to restrict logged-in users to only have one active session, i.e. if the user logs in with a new sessionid, the old session should be terminated. I found a lot of hel

相关标签:
3条回答
  • 2020-12-25 13:18

    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.8
    
    from django.contrib.sessions.models import Session
    from django.contrib.auth.signals import user_logged_in
    from django.db.models import Q
    from django.utils import timezone
    
    def 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()
    
        return
    
    user_logged_in.connect(limit_sessions)
    
    0 讨论(0)
  • 2020-12-25 13:25

    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.

    0 讨论(0)
  • 2020-12-25 13:28

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

    0 讨论(0)
提交回复
热议问题