我在ajax视图中编写了此代码,但这是一个更广泛的答案,提供了当前已登录和已注销用户的列表。
该is_authenticated
属性始终True
为我的用户返回,这是我所期望的,因为该属性仅检查AnonymousUsers,但是如果您要开发一个需要登录的用户来显示聊天应用程序,这将毫无用处。
这将检查过期的会话,然后根据解码的_auth_user_id
属性找出它们属于哪个用户:
def ajax_find_logged_in_users(request, client_url):
"""
Figure out which users are authenticated in the system or not.
Is a logical way to check if a user has an expired session (i.e. they are not logged in)
:param request:
:param client_url:
:return:
"""
# query non-expired sessions
sessions = Session.objects.filter(expire_date__gte=timezone.now())
user_id_list = []
# build list of user ids from query
for session in sessions:
data = session.get_decoded()
# if the user is authenticated
if data.get('_auth_user_id'):
user_id_list.append(data.get('_auth_user_id'))
# gather the logged in people from the list of pks
logged_in_users = CustomUser.objects.filter(id__in=user_id_list)
list_of_logged_in_users = [{user.id: user.get_name()} for user in logged_in_users]
# Query all logged in staff users based on id list
all_staff_users = CustomUser.objects.filter(is_resident=False, is_active=True, is_superuser=False)
logged_out_users = list()
# for some reason exclude() would not work correctly, so I did this the long way.
for user in all_staff_users:
if user not in logged_in_users:
logged_out_users.append(user)
list_of_logged_out_users = [{user.id: user.get_name()} for user in logged_out_users]
# return the ajax response
data = {
'logged_in_users': list_of_logged_in_users,
'logged_out_users': list_of_logged_out_users,
}
print(data)
return HttpResponse(json.dumps(data))