How to force a user logout in Django?

前端 未结 10 2146
粉色の甜心
粉色の甜心 2020-11-30 17:27

In my Django app under certain conditions I want to be able to force users to log out by a username. Not necessarily the current user who is logged in, but another user. So,

10条回答
  •  失恋的感觉
    2020-11-30 18:24

    This is in response to Balon's query:

    Yes, with around 140k sessions to iterate through I can see why Harold's answer may not be as fast as you may like!

    The way I would recommend is to add a model whose only two properties are foreign keys to User and Session objects. Then add some middleware that keeps this model up-to-date with current user sessions. I have used this sort of setup before; in my case, I borrowed the sessionprofile module from this Single Sign-On system for phpBB (see the source code in the "django/sessionprofile" folder) and this (I think) would suit your needs.

    What you would end up with is some management function somewhere in your code like this (assuming the same code names and layout as in the sessionprofile module linked above):

    from sessionprofile.models import SessionProfile
    from django.contrib.auth.models import User
    
    # Find all SessionProfile objects corresponding to a given username
    sessionProfiles = SessionProfile.objects.filter(user__username__exact='johndoe')
    
    # Delete all corresponding sessions
    [sp.session.delete() for sp in sessionProfiles]
    

    (I think this will also delete the SessionProfile objects, as from what I recall, Django's default behaviour when an object referenced by a ForeignKey is deleted is to cascade it and also delete the object containing the ForeignKey, but if not then it is trivial enough to delete the contents of sessionProfiles when you are done.)

提交回复
热议问题