How to get currently logged in users in a Django REST API


I am trying to create a quiz game Android application, using Django as a REST API back-end. The ideal user experience would be User1 invites User2 to a game and they both play (answer trivia questions) real time. To make that possible, User1 should know if User2 is currently logged in and active.

Question 1

How can I query the currently logged in users in a Django REST API?
One possible solution for this is to check the valid sessions, provided I am using the standard session authenticaton. Is that a good idea?

Question 2

Would it be possible to know the currently logged in users, if I am using JWT authentication?

In a pure HTTP environment, there is no such thing as a “logged in user”. There is no “active connection” to check. Sessions remain valid for a period of time after the last request has been received, and the server has no way to determine if another request is ever going to be made.

If you need to know who is connected and active, then those people need to be active and connected - websockets.

To effectively do this, you need to use Channels, or something like it.

Thanks a lot! I am planning to use Channels for the real time part anyway. So if I understand correctly it should be possible to query all the clients with an open WebSocket connection to determine who is online?

Channels (out-of-the-box) doesn’t quite work that way. Channels itself doesn’t “track” active connections by a username. There’s no built-in API allowing a connection to inventory other connections.

I use a (slightly-modified) version of django-channels-presence to track what users are in which “rooms” for this purpose.

Wow that’s exactly what I needed! Is there any particular reason that you use a modified version?

See Incompatible with Django 4.0 due to use of provides_args argument for Signal · Issue #23 · mitmedialab/django-channels-presence · GitHub

Also, the current version:

  • Does not prohibit membership in multiple rooms concurrently
  • Will create rooms on-demand. (Trying to join a room that doesn’t exist causes the room to be created.)

Those are two features not permitted in what we’re doing with this. (Note, I’m not saying that “we’re right” and “they’re wrong” - it’s purely an issue of different requirements.)

Is that version open source somewhere?

Unfortunately not at this time. Hopefully this year.

No worries, thanks a lot!