Shang Wang
Shang Wang

Reputation: 25539

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? Thanks!

Upvotes: 4

Views: 5174

Answers (1)

CrazyCasta
CrazyCasta

Reputation: 28302

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

Upvotes: 3

Related Questions