βœ‹ Auto logout a user after specific time in Django

Overview

django-auto-logout

Build Status

Auto logout a user after specific time in Django.

Works with

  • Python 🐍 β‰₯ 3.7,
  • Django 🌐 β‰₯ 3.0.

βœ”οΈ Installation

pip install django-auto-logout

Append to settings.py middlewares:

MIDDLEWARE = [
    # append after default middlewares
    'django_auto_logout.middleware.auto_logout',
]

NOTE

Make sure that the following middlewares are used before doing this:

  • django.contrib.sessions.middleware.SessionMiddleware
  • django.contrib.auth.middleware.AuthenticationMiddleware
  • django.contrib.messages.middleware.MessageMiddleware

πŸ’€ Logout in case of idle

Logout a user if there are no requests for a long time.

Add to settings.py:

AUTO_LOGOUT = {'IDLE_TIME': 600}  # logout after 10 minutes of downtime

or the same, but with datetime.timedelta (more semantically):

from datetime import timedelta

AUTO_LOGOUT = {'IDLE_TIME': timedelta(minutes=10)}

βŒ› Limit session time

Logout a user after 3600 seconds (hour) from the last login.

Add to settings.py:

AUTO_LOGOUT = {'SESSION_TIME': 3600}

or the same, but with datetime.timedelta (more semantically):

from datetime import timedelta

AUTO_LOGOUT = {'SESSION_TIME': timedelta(hours=1)}

βœ‰οΈ Show messages when logging out automatically

Set the message that will be displayed after the user automatically logs out of the system:

AUTO_LOGOUT = {
    'SESSION_TIME': 3600,
    'MESSAGE': 'The session has expired. Please login again to continue.',
}

It uses django.contrib.messages. Don't forget to display messages in templates:

{% for message in messages %}
    <div class="message {{ message.tags }}">
        {{ message }}
    </div>
{% endfor %}

NOTE

messages template variable provides by django.contrib.messages.context_processors.messages context processor.

See TEMPLATES β†’ OPTIONS β†’ context_processors in your settings.py file.


🌈 Combine configurations

You can combine previous configurations. For example, you may want to logout a user in case of downtime (5 minutes or more) and not allow working within one session for more than half an hour:

from datetime import timedelta

AUTO_LOGOUT = {
    'IDLE_TIME': timedelta(minutes=5),
    'SESSION_TIME': timedelta(minutes=30),
    'MESSAGE': 'The session has expired. Please login again to continue.',
}
You might also like...
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Rosetta is a Django application that eases the translation process of your Django projects
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

django-quill-editor makes Quill.js easy to use on Django Forms and admin sites
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot πŸš€ Features A Django stater project with fully basic requirements for a production-ready

Comments
  • How to Auto-redirect to login page.

    How to Auto-redirect to login page.

    Hello all,

    The app is great works like a charm, really appreciate your effort, I would like to know is there any way to redirect the user to the login page when the IDLE_TIME is reached.

    Right now when the IDLE_TIME is reached the users have to refresh the page to redirect to the LOGIN_URL.

    any help really appreciated. Thanks!

    opened by HarishOsthe 4
  •  WSGI application 'project.wsgi.application' could not be loaded; Error importing module.

    WSGI application 'project.wsgi.application' could not be loaded; Error importing module.

    When I tried to install and use the django-auto-logout I got an error.

    What I did

    I followed the instructions here:

    Installation

    pip install django-auto-logout

    Append to settings middleware:

    MIDDLEWARE = [
    ...
        'django_auto_logout.middleware.auto_logout',
    ]
    

    REDIRECT_TO_LOGIN_IMMEDIATELY after the idle-time has expired

    from datetime import timedelta
    AUTO_LOGOUT = {
        'IDLE_TIME': timedelta(minutes=5),
        'REDIRECT_TO_LOGIN_IMMEDIATELY': True,
    }
    

    The Error

    Traceback (most recent call last):
      File "[SOME PATH]\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application
        return import_string(app_path)
      File "[SOME PATH]\site-packages\django\utils\module_loading.py", line 30, in import_string
        return cached_import(module_path, class_name)
      File "[SOME PATH]\site-packages\django\utils\module_loading.py", line 15, in cached_import
        module = import_module(module_path)
      File "[SOME PATH]\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 883, in exec_module
      File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
      File "C:\Users\mshem\PycharmProjects\hilal\hilal\wsgi.py", line 16, in <module>
        application = get_wsgi_application()
      File "[SOME PATH]\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application
        return WSGIHandler()
      File "[SOME PATH]\site-packages\django\core\handlers\wsgi.py", line 125, in __init__
        self.load_middleware()
      File "[SOME PATH]\site-packages\django\core\handlers\base.py", line 40, in load_middleware
        middleware = import_string(middleware_path)
      File "[SOME PATH]\site-packages\django\utils\module_loading.py", line 30, in import_string
        return cached_import(module_path, class_name)
      File "[SOME PATH]\site-packages\django\utils\module_loading.py", line 15, in cached_import
        module = import_module(module_path)
      File "[SOME PATH]\importlib\__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 883, in exec_module
      File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
      File "[SOME PATH]\site-packages\django_auto_logout\middleware.py", line 8, in <module>
        from .utils import now, seconds_until_idle_time_end, seconds_until_session_end
      File "[SOME PATH]\site-packages\django_auto_logout\utils.py", line 5, in <module>
        from pytz import timezone
    ModuleNotFoundError: No module named 'pytz'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "[SOME PATH]\threading.py", line 1016, in _bootstrap_inner
        self.run()
      File "[SOME PATH]\threading.py", line 953, in run
        self._target(*self._args, **self._kwargs)
      File "[SOME PATH]\site-packages\django\utils\autoreload.py", line 64, in wrapper
        fn(*args, **kwargs)
        return get_internal_wsgi_application()
      File "[SOME PATH]\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application
        raise ImproperlyConfigured(
    django.core.exceptions.ImproperlyConfigured: WSGI application '[My Project].wsgi.application' could not be loaded; Error importing module.
    

    Fix

    Since it clearly says ModuleNotFoundError: No module named 'pytz' the fix was easy:

    pip install pytz

    opened by mshemuni 2
Releases(v0.5.1)
Owner
Georgy Bazhukov
Georgy Bazhukov
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot πŸš€ Features A Django stater project with fully basic requirements for a production-ready

8 Jun 27, 2022
A middleware to log the requests and responses using loguru.

Django Loguru The extension was based on another one and added some extra flavours. One of the biggest problems with the apps is the logging and that

Tiago Silva 9 Oct 11, 2022
Extensions for using Rich with Django.

django-rich Extensions for using Rich with Django. Requirements Python 3.6 to 3.10 supported. Django 2.2 to 4.0 supported. Are your tests slow? Check

Adam Johnson 88 Dec 26, 2022
Django friendly finite state machine support

Django friendly finite state machine support django-fsm adds simple declarative state management for django models. If you need parallel task executio

Viewflow 2.1k Dec 31, 2022
Opinionated boilerplate for starting a Django project together with React front-end library and TailwindCSS CSS framework.

Opinionated boilerplate for starting a Django project together with React front-end library and TailwindCSS CSS framework.

JoΓ£o VΓ­tor Carli 10 Jan 08, 2023
A Student/ School management application built using Django and Python.

Student Management An awesome student management app built using Django.! Explore the docs Β» View Demo Β· Report Bug Β· Request Feature Table of Content

Nishant Sethi 1 Feb 10, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 02, 2023
Alt1-compatible widget host for RuneScape 3

RuneKit Alt1-compatible toolbox for RuneScape 3, for Linux and macOS. Compatibility macOS installation guide Running This project use Poetry as packag

Manatsawin Hanmongkolchai 75 Nov 28, 2022
PEP-484 stubs for django-rest-framework

pep484 stubs for Django REST framework Mypy stubs for DRF 3.12.x. Supports Python 3.6, 3.7, 3.8 and 3.9. Installation pip install djangorestframework-

TypedDjango 303 Dec 27, 2022
A standalone package to scrape financial data from listed Vietnamese companies via Vietstock

Scrape Financial Data of Vietnamese Listed Companies - Version 2 A standalone package to scrape financial data from listed Vietnamese companies via Vi

Viet Anh (Vincent) Tran 45 Nov 16, 2022
Django + Next.js integration

Django Next.js Django + Next.js integration From a comment on StackOverflow: Run 2 ports on the same server. One for django (public facing) and one fo

Quera 162 Jan 03, 2023
Forward and backwards compatibility layer for Django 1.4, 1.7, 1.8, 1.9, 1.10, and 1.11

django-compat Forward and backwards compatibility layer for Django 1.4 , 1.7 , 1.8, 1.9, 1.10 and 1.11 Consider django-compat as an experiment based o

arteria GmbH 106 Mar 28, 2022
Dynamic, database-driven Django forms

Django Dataforms django-dataforms is a wrapper for the Django forms API that lets you dynamically define forms in a database, rather than hard-coding

35 Dec 16, 2022
PWA is a simple Django app to develope and deploy a Progressive Web Application.

PWA PWA is a simple Django app to develope and deploy a Progressive Web Application. Detailed documentation is in the "docs" directory. Quick start Ad

Nima 6 Dec 09, 2022
Auth module for Django and GarpixCMS

Garpix Auth Auth module for Django/DRF projects. Part of GarpixCMS. Used packages: django rest framework social-auth-app-django django-rest-framework-

GARPIX CMS 18 Mar 14, 2022
Full-text multi-table search application for Django. Easy to install and use, with good performance.

django-watson django-watson is a fast multi-model full-text search plugin for Django. It is easy to install and use, and provides high quality search

Dave Hall 1.1k Dec 22, 2022
Learn Python and the Django Framework by building a e-commerce website

The Django-Ecommerce is an open-source project initiative and tutorial series built with Python and the Django Framework.

Very Academy 275 Jan 08, 2023
django-compat-lint

django_compat_lint -- check Django compatibility of your code Django's API stability policy is nice, but there are still things that change from one v

James Bennett 40 Sep 30, 2021
Hotwired/Turbo Django response helpers

This package provides helpers for server-side rendering of Hotwired/Turbo streams and frames. Disclaimer: the Hotwired/Turbo client libraries are, at

Hotwire for Django 66 Apr 07, 2022
This is a simple Todo web application built Django (back-end) and React JS (front-end)

Django REST Todo app This is a simple Todo web application built with Django (back-end) and React JS (front-end). The project enables you to systemati

Maxim Mukhin 5 May 06, 2022