如何在Django中注销用户?

时间:2021-09-30 01:18:23

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:

我们的Django部署每晚都会检查哪些活动用户仍然可以在out LDAP目录中找到。如果再也找不到它们,我们将它们设置为非活动。如果他们下次尝试登录,这将失败。下面是我们的代码:

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.

但是如果他们仍然登录,这个会话仍然在工作。我们怎么能让他们立即失效呢?会话中间件的所有设置都是默认值。

2 个解决方案

#1


11  

You can log them out using

你可以用日志记录下来

from django.contrib.auth import logout

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

... from within any view.

…在任何视图。

#2


1  

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

除了login_required decorator之外,还可以使用user_passes_test decorator来测试用户是否仍然处于活动状态。

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):
    ....

#1


11  

You can log them out using

你可以用日志记录下来

from django.contrib.auth import logout

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

... from within any view.

…在任何视图。

#2


1  

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

除了login_required decorator之外,还可以使用user_passes_test decorator来测试用户是否仍然处于活动状态。

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):
    ....