views:

625

answers:

2

In my django app under certain conditions I need to be able to force user logout by a username. Not necessarily the current user who is logged in, but some other user. So the request method in my view doesn't have any session information about the user that I want to logout.

I am familiar with django.auth, and with auth.logout method, but it takes request as an argument. Is there a "django-way" to log user out if all I have is the username? Or do I have to roll my own logout sql?

+3  A: 

I don't think there is a sanctioned way to do this in Django yet.

The user id is stored in the session object, but it is encoded. Unfortunately, that means you'll have to iterate through all sessions, decode and compare...

Two steps:

First delete the session objects for your target user. If they log in from multiple computers they will have multiple session objects.

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

# grab the user in question 
user = User.objects.get(username='johndoe')

[s.delete() for s in Session.objects.all() if s.get_decoded().get('_auth_user_id') == user.id]

Then, if you need to, lock them out....

user.is_active = False
user.save()
Harold
Thank you for the suggestion, this seams rather brute force solution, the one I was trying to avoid. However if there are no other options I might have to go with it, probably with a small improvement instead of getting "all" sessions get the ones that were updated within last "x" minutes, hopefully that would drastically improve the perfomance.
No prob. Filtering the session data on last updated would be a worthwhile improvement.
Harold
+2  A: 

Perhaps, a bit of middleware that references a list of users who have been forced to log out. Next time the user tries to do anything, log them out then, redirects them, etc.

Unless of course, they need to be logged out immediately. But then again, they wouldn't notice until they next tried to make a request anyway, so the above solution may just work.

danros