5

I need to logout a user after some specific time(lets take it as 1 min for now), and so created a middleware class as below

myproject/middleware.py

from datetime import datetime, timedelta
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()

settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'myproject.middleware.HttpErrorHandler',
    'myproject.middleware.AutoLogout'
)
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
AUTO_LOGOUT_DELAY = 1

Djagno version was 1.4.12

But the above code was not working and i am not sure where i was doing wrong, so can someone let me know why the above code was not working and how to logout a user for every 1 min or 5 min ?

Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313

1 Answers1

12

From Django 1.7 Session management was introduced. Under settings there are two parameters that you can add to help you allow auto logout without necessarily writing you own middleware.

  1. SESSION_EXPIRE_AT_BROWSER_CLOSE
  2. SESSION_COOKIE_AGE

Hope that answers your query. Happy coding!!

rahnama7m
  • 865
  • 10
  • 38
Njogu Mbau
  • 446
  • 1
  • 7
  • 14