Allowing only single active session per user in Django app

前端 未结 3 829
孤城傲影
孤城傲影 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: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.

提交回复
热议问题