DEV Community

Cover image for Adding a Session timeout in Django
Arno Pretorius
Arno Pretorius

Posted on

Adding a Session timeout in Django

Why do we need a session timeout?

If your users are accessing your website from a public computer at an internet café or a library, then there is a chance that they may forget to log out. If that is the case, then what stops a stranger from accessing their profile and reading all their sensitive information.

What can also happen is the user may not click log out, but instead close their browser. Someone who has some wits about them could easily re-trace the previous user's history and again play around with their profile.

So, how do we sort this out?


Step 1:
To install django-session-timeout type in the below command:

pip install django-session-timeout
Enter fullscreen mode Exit fullscreen mode

Step 2:
Next, you must add the middleware for django-session-timeout, this can be inserted anywhere. The middleware is as follows:

# settings.py

MIDDLEWARE = [
   'django.contrib.sessions.middleware.SessionMiddleware',
   'django_session_timeout.middleware.SessionTimeoutMiddleware',
]
Enter fullscreen mode Exit fullscreen mode

Step 3:
Some useful configurations that you can include in your settings.py are as follows:


Session timeout expiry time:
The code below will render your session invalid after 30 minutes from the start of an activity.

To set the session timeout expiry time, simply use:

# settings.py

SESSION_EXPIRE_SECONDS = 1800  # Expire after 30 minutes
Enter fullscreen mode Exit fullscreen mode

Invalidate the session after the most recent/last activity:

# settings.py

SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True
Enter fullscreen mode Exit fullscreen mode

Re-direct users to another page:
After your session has expired, re-direct your users away to another page, it could be your home page perhaps, but anyway, here is how you would approach it:

# settings.py

SESSION_TIMEOUT_REDIRECT = 'redirect_url_/' # Add your URL
Enter fullscreen mode Exit fullscreen mode

Expire the session when the browser closes:
Many of your users WILL forget to log out of their account and instead will close the browser, be prepared for this, by adding this line:

# settings.py

SESSION_EXPIRE_AT_BROWSER_CLOSE=True # Invalid session
Enter fullscreen mode Exit fullscreen mode

Conclusion

Okay, so that's that! You will now be able to handle your user's sessions more efficiently and in a more secure manner.


A final note…

For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course - 2022

Top comments (0)