Torsten Bronger
Torsten Bronger

Reputation: 11116

How can I logout a user in Django?

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.

Upvotes: 25

Views: 34169

Answers (3)

user2867522
user2867522

Reputation:

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.

Upvotes: 38

Mohammad Javad Naderi
Mohammad Javad Naderi

Reputation: 506

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 can query sessions easily:

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

# log-out a user
user.session_set.all().delete()

Disclaimer: I am the author of django-qsessions.

Upvotes: 1

klasske
klasske

Reputation: 2174

In addition to the login_required decorator, you could use the user_passes_test decorator to test if the user is still active.

from django.contrib.auth import user_passes_test

def is_user_active(user):
    return user.is_active

@user_passes_test(is_user_active, login_url='/your_login')
def your_function(request):
    ....

Upvotes: 1

Related Questions