3

Is there a quick and simple way to get all the users that are currently logged in to a web2py application? I would like to show the administrator of the page how many non-admin users are logged in at the moment. Thanks..

1 Answers1

10

Note, "currently logged in" is not a well-defined concept. You can log in but then walk away from your computer or close your browser. In that case, are you still logged in? You probably shouldn't be counted as logged in, yet the server doesn't know you walked away or closed your browser. The Auth system does record login and logout events in the auth_events table, so one option is to find all users who have logged in within a defined period but not explicitly logged out since. Note, this may overstate the number of logged in users, because some may have left your site without explicitly logging out. Here's some code:

import datetime
limit = request.now - datetime.timedelta(minutes=30)
query = db.auth_event.time_stamp > limit
query &= db.auth_event.description.contains('Logged-')
events = db(query).select(db.auth_event.user_id, db.auth_event.description,
    orderby=db.auth_event.user_id|db.auth_event.time_stamp)
users = []
for i in range(len(events)):
    last_event = ((i == len(events) - 1) or
                   events[i+1].user_id != events[i].user_id)
    if last_event and 'Logged-in' in events[i].description:
        users.append(events[i].user_id)
logged_in_users = db(db.auth_user.id.belongs(users)).select()

The above gives you all the users who have logged in within the last 30 minutes but not explicitly logged out.

A more sophisticated approach would involve tracking the requests of users who have logged in to determine who is actively using the application. You could cache a dictionary that stores a timestamp of the most recent request for each logged in user. When a report is requested, show the users with timestamps within some recent timeframe (and purge users with older timestamps to keep the cache from growing too large).

Another option would be to inspect the session files. Identify sessions that have been modified within some timeframe. Among those, find the ones that include an "auth" object, and check auth.last_visit for the time of the last request (actually, auth.last_visit only updates if the time since the previous visit exceeds 1/10 of the auth.settings.expiration time, which defaults to 3600 seconds).

Anthony
  • 25,466
  • 3
  • 28
  • 57
  • Hey Anthony thank you so much for your answer, it was really elaborated and complete. I will definitely try that and update with the result.. – Juan Ignacio Galan Sep 03 '12 at 15:29