wonton
wonton

Reputation: 8287

How do I log out any user when using the cache session backend?

I am building a form into django admin where I can submit a user id and the system is expected to log the user out.

I cannot do django.contrib.auth.logout() because it does not take a user id as a parameter.

I also cannot query against django.contrib.sessions.models.Session because I am using the django.contrib.sessions.backends.cache session engine.

Upvotes: 0

Views: 87

Answers (1)

wonton
wonton

Reputation: 8287

The only way I could find to accomplish this is by doing something like

from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
SessionStore(session_id).delete()

You may notice that I don't have the code that connects a user id to a session id. This is because as far as I can tell, with the cache session engine by default there is no way to do that linking because the session key is only stored on the browser. The key is a secure random string and it gets looked up by the backend.

Therefore you will need to store the session id somewhere in your database and associate that key with your user.

In my case, I issue a set of tokens to the user at login time, so I was able to attach the session id to the token. Then when I initiate an admin action to forcibly logout a user, I can do

for token in Token.objects.filter(user=request.user):
    SessionStore(token.session_id).delete()
    token.delete()

Upvotes: 1

Related Questions