1

I'm working on a project using Python(2.7) and Django(1.11) in which I need to display only logged in users for a specific function.

I have achieved to log out the user by the following settings in settings.py:

SESSION_COOKIE_AGE = 180
SESSION_SAVE_EVERY_REQUEST = True
LOGOUT_REDIRECT_URL = 'login'

and I need to get active users of type driver which is I'm getting as:

def get_all_logged_in_users():
    # Query all non-expired sessions
    # use timezone.now() instead of datetime.now() in latest versions of Django
    sessions = Session.objects.filter(expire_date__gte=timezone.now())
    uid_list = []

    # Build a list of user ids from that query
    for session in sessions:
        data = session.get_decoded()
        print(data)
        uid_list.append(data.get('user_id', None))

    # Query all logged in users based on id list
    return user_table.objects.filter(id__in=uid_list, user_type='driver')

It was working till a few days ago but suddenly stopped working anymore. When I refresh the page after the time SESSION_COOKIE_AGE passed it redirected to the login page which is perfect but in the database, the is_active for that user is still True and it's still displaying in the get_all_logged_in_users.

How can I solve this issue?

Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150

1 Answers1

0

I am not entirely sure that I understand your question, but I will try to clear up a few things.


Firstly, the Session framework stores the expiration date of each session, but inactive sessions are NOT deleted automatically; for that you can use the management command clearsessions in a cron job.


Secondly, the field User.is_active does NOT indicate if there are active sessions or not; the docs say:

Designates whether this user account should be considered active. We recommend that you set this flag to False instead of deleting accounts [...]


Your function get_all_logged_in_users() seems correct; a small improvement could be to avoid adding None to the id list and maybe even make that list into a set to avoid repetition for users that have many active sessions.

def get_all_logged_in_users():
    user_id_set = set()

    for session in Session.objects.filter(expire_date__gte=timezone.now()):
        user_id = session.get_decoded().get('user_id', None)
        if user_id is not None:
            user_id_set.add(user_id)

    return user_table.objects.filter(id__in=user_id_set, user_type='driver')

But other than that this function seems to have the correct logic.

Are you sure that it returns users that only have expired sessions? Maybe those users have some active and some inactive sessions and that is why they appear in the output?

Ralf
  • 16,086
  • 4
  • 44
  • 68