如何注销Django中的用户?

2024-05-17 01:02:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我们的Django部署每天晚上都会检查哪些活动用户仍然可以在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)

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


Tags: djangoinsynchronizeiswithnotpasswordldap
3条回答

你可以使用

from django.contrib.auth import logout

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

。。。从任何角度看。

除了登录所需的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):
    ....

您可以使用会话后端来查询和获取特定用户的会话。在这些会话后端中,会话对用户具有外键,因此可以方便地查询会话:

使用这些后端,可以在一行代码中删除用户的所有会话:

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

免责声明:我是django-qsessions的作者。

相关问题 更多 >