如何强制用户注销django? [英] How to force user logout in django?

查看:693
本文介绍了如何强制用户注销django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的django应用程序中,在某些情况下,我需要能够强制用户注销用户名。不一定是当前登录的用户,而是其他一些用户。所以我的看法中的请求方法没有关于我要注销的用户的任何会话信息。

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.

我熟悉django.auth和auth。注销方法,但它需要请求作为参数。有没有一个django-way登录用户,如果我有所有的用户名?或者我必须滚动我自己的注销sql?

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?

推荐答案

我不认为有这样做的制裁方式Django还没

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

用户ID存储在会话对象中,但编码。不幸的是,这意味着你必须遍历所有会话,解码和比较...

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

两个步骤:

首先删除目标用户的会话对象。如果他们从多台计算机登录,他们将有多个会话对象。

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()

这篇关于如何强制用户注销django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆