1 min read

Adding a session timeout in Django

Adding a session timeout in Django
Photo by Ales Krivec / Unsplash

Why do we need a session timeout?

If your users are accessing your website from a public computer at an internet cafe 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

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',
]

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

Invalidate the session after the most recent/last activity:

# settings.py

SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True

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

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 after browser is closed

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.