How to expire Django session in 5minutes?
Update for Django 1.6
The middleware code below is not working in Django 1.6 and above version because of json serializable. To make it work in all versions of Django, put the session serializer.
settings.py
#Handle session is not Json Serializable
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
The above sample of serializer is for Django 1.6. Kindly search for other version. Thanks...
Create middleware.py
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib import auth
class AutoLogout:
def process_request(self, request):
if not request.user.is_authenticated() :
#Can't log out if not logged in
return
try:
if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
auth.logout(request)
del request.session['last_touch']
return
except KeyError:
pass
request.session['last_touch'] = datetime.now()
Update your settings.py:
MIDDLEWARE_CLASSES = [
.........................
'app_name.middleware.AutoLogout',
]
# Auto logout delay in minutes
AUTO_LOGOUT_DELAY = 5 #equivalent to 5 minutes
There are two parameters to expire sessions, SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE. If you want to expire in 5 minutes yours settings should like as:
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 5 * 60
To combine both learn how do it writing your custom middleware "Is there a way to combine behavior of SESSION_EXPIRE_AT_BROWSER_CLOSE and SESSION_COOKIE_AGE"
Django 1.9
Edit your settings.py and add the following:
# SESSION AGE 5 Minutes
SESSION_COOKIE_AGE = 5*60