简体   繁体   English

Django:如何测试用户当前是否已登录

[英]Django: How to test if a user is currently logged in

I need some help to find out how to test if a user is currently logged in or not. 我需要一些帮助来了解如何测试用户当前是否登录。 I searched online and found that there are solutions for view method to pull out user from request and test it: 我在网上搜索,发现有一些解决方法可以从请求中提取用户并测试它:

if request.user.is_authenticated():

However, in my situation I need something like the following: 但是,在我的情况下,我需要以下内容:

user = User.objects.get(id=1)
if user.is_logging_in():
    # do something
else:
    # do something else

Does this kind of functionality exists in Django? Django中是否存在这种功能? Thanks! 谢谢!

I do not believe that that information exists in a supported manner. 我不认为该信息以受支持的方式存在。 My understanding is that the user authentication system uses the SessionMiddleware to store whether the session has an authenticated user associated with it. 我的理解是,用户身份验证系统使用SessionMiddleware来存储会话是否具有与之关联的经过身份验证的用户。 To clarify, when a user logs in, the session stores data saying that the client on the other side is user such and such. 为了阐明,当用户登录时,会话存储数据,该数据表明另一方的客户端是用户等。

What you would need to do is go through all the sessions and determine whether or not the session has an associated user and if so, who that user is. 您需要做的是遍历所有会话并确定会话是否具有关联用户,如果是,则该用户是谁。 As far as I understand, there is no way to iterate through the sessions, but I could be wrong. 据我所知,没有办法迭代会话,但我可能是错的。

From this answer I have found a way that you could achieve the same effect however. 这个答案我发现了一种可以达到同样效果的方法。

from django.contrib.auth.signals import user_logged_in, user_logged_out

def record_user_logged_in(sender, user, request, **kwargs):
    # Record the user logged in

def record_user_logged_out(sender, user, request, **kwargs):
    # Record the user logged out

user_logged_in.connect(record_user_logged_in)
user_logged_out.connect(record_user_logged_out)

I'll leave it up to you as to how to store the information pertained to logged in/out but a model would be a good way of doing it. 我将向您介绍如何存储与登录/退出相关的信息,但模型将是一种很好的方式。 I should point out that I don't believe this covers the case of users' credentials timing out (from session timing out). 我应该指出,我不相信这会涵盖用户凭据超时的情况(从会话超时)。

Also, I have just come across this answer which links here which is a project to track active users. 另外,我刚刚看到这个链接这是一个跟踪活跃用户的项目。 I'm not sure how much overhead it adds, but just thought I'd add it. 我不确定它增加了多少开销,但只是想我会添加它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM