How to force a user logout in Django?

前端 未结 10 2144
粉色の甜心
粉色の甜心 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:19

    As Tony Abou-Assaleh, I also needed to log out users who were set to inactive, so I started by implementing his solution. After some time I found out that the middleware is forcing a DB query on all requests (to check if the user was blocked), and thus hurts performance on pages that doesn't require login.

    I have a custom user object and Django >= 1.7, so what I ended up doing is overriding its get_session_auth_hash function to invalidate the session when the user is inactive. A possible implementation is:

    def get_session_auth_hash(self):
        if not self.is_active:
            return "inactive"
        return super(MyCustomUser, self).get_session_auth_hash()
    

    For this to work, django.contrib.auth.middleware.SessionAuthenticationMiddleware should be in settings.MIDDLEWARE_CLASSES

提交回复
热议问题