Django Logout on Inactivity

18 December 2009

For a project I'm working on the client requested that their logged in sessions expire at either browser close or after 2 hours of inactivity. By default, Django supports the browser close option, but only allows for a time based log out set x seconds from when the user logged in. To get around this limitation, I wrote a simple middleware class that updates the session expiration on each page view to settings.SESSION_COOKIE_AGE plus the current datetime.

This uses the same setting that the Session module uses by default, so you can easily drop this in an existing app. If you don't have SESSION_COOKIE_AGE set, the middleware defaults to 2 hours (the normal default is 2 weeks).

To use it, add the code to your middleware file and add the class to your MIDDLEWARE_CLASSES setting.

View the source code on Github