Django Logout on Inactivity

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.

Comments (3)

  1. Daniel Ryan on March 12, 2010

    Looks like you're getting a UTF8 character in there. Click the View Raw link
    on the snippet then copy that code.
    On Mar 12, 2010, at 1:34 AM, "JS-Kit.com Comments" <
    js-kit-m2c-EKDHC7C7ET7TBPT7GMH0MED5F7D9ML2KP7AEGPF13LVIONHV61EG@reply.js-kit.com>
    wrote:
    New item from *stormlifter* on Django Logout on Inactivity — Articles —
    dryan <http://dryan.com/articles/django-logout-inactivity/>
    I'm getting an odd error "SyntaxError: Non-ASCII character '\xe2' in file"
    on this line: "if datetime.now() – request.session.get_expiry_date() <
    timedelta(seconds = COOKIE_AGE):"
    To respond to this item, you may simply reply to this email or visit the
    page <http://dryan.com/articles/django-logout-inactivity/>.

  2. stormlifter on March 12, 2010

    How about just this

    [code]
    class InactivityLogout(object):
    def process_request( self, request ):
    request.session.modified = True
    return None # pass through
    [/code]

    In raw: http://dpaste.com/171097/

  3. Daniel Ryan on March 12, 2010

    It's still Unicode apparently. You need to convert it to ASCII or set your
    python file to work in UTF8.

Leave a Comment

Please log in to post a comment.

Summary

Django middleware class to allow session expiration to move forward with each use.

Sharing

About the Author