How can I logout a user in Django?

Torsten Bronger picture Torsten Bronger · Aug 11, 2014 · Viewed 18.2k times · Source

Our Django deployment checks every night which active users can still be found in out LDAP directory. If they cannot be found anymore, we set them to inactive. If they try to login next time, this will fail. Here is our code that does this:

def synchronize_users_with_ad(sender, **kwargs):
    """Signal listener which synchronises all active users without a usable
    password against the LDAP directory.  If a user cannot be
    found anymore, he or she is set to “inactive”.
    """
    ldap_connection = LDAPConnection()
    for user in User.objects.filter(is_active=True):
        if not user.has_usable_password() and not existing_in_ldap(user):
            user.is_active = user.is_staff = user.is_superuser = False
            user.save()
            user.groups.clear()
            user.user_permissions.clear()

maintain.connect(synchronize_users_with_ad)

But if they are still logged in, this session(s) is/are still working. How can we make them invalid immediately? All settings of the session middleware are default values.

Answer

user2867522 picture user2867522 · Aug 11, 2014

You can log them out using

from django.contrib.auth import logout

if <your authentication validation logic>:
    logout(request) 

... from within any view.

logout() Django docs here.