How to force a user logout in Django?

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

    As others stated, you can iterate over all sessions in DB, decode all of them, and delete those belonging to that user. But it's slow, particularly if your site has high traffic and there are lots of sessions.

    If you need a faster solution, you can use a session backend that lets you query and get the sessions of a specific user. In these session backends, Session has a foreign key to User, so you don't need to iterate over all session objects:

    • django-qsessions (based on django's db, cached_db session backends)
    • django-user-sessions (based on django's db session backend)

    Using these backends, deleting all sessions of a user can be done in a single line of code:

    user.session_set.all().delete()
    

    Disclaimer: I am the author of django-qsessions.

提交回复
热议问题