bSr
bSr

Reputation: 1526

Django: How to detect inactivity session time out?

I am using django.auth.db connection and have created a table which contains username of a user who is logged in and when the user logged out manually (by clicking logout button) I am removing his/her username from that table. The problem arises when a user logged out due to session out and I am not able to remove his/her username from that table.

So I wanted to know that is there any way to detect when the users' session/cookies out so that I can remove his/her username from that table?

Upvotes: 1

Views: 1358

Answers (2)

Kevin L.
Kevin L.

Reputation: 1471

first you need to retrieve the list of users with active sessions from the session store, thereafter you would need to compare this list with the users in your table and delete those in your table that are not in the list.

You can retrieve the list of users from your session store like so:

from django.contrib.sessions.models import Session
from django.utils import timezone 

# 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()
    uid_list.append(data.get('_auth_user_id', None))

Then you can cycle through the uid_list and compare with your table, using some logic such as (illustrative)

for user in table
    if user not in uid_list
        user.remove_from_table()

Upvotes: 3

Nazkter
Nazkter

Reputation: 1110

you can use the next command to clear all the expired session from the session storage.

django-admin clearsessions

the same result as using:

./manage.py clearsessions

If you configure your storage to a database, then it will delete the sessions from the database.

documentation: https://docs.djangoproject.com/en/dev/ref/django-admin/#django-contrib-sessions

If you want to do it in your views, you can call the method clear_expired():

request.session.clear_expired()

documentation: https://docs.djangoproject.com/en/2.0/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.clear_expired

Upvotes: 1

Related Questions