✋ 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 TEMPLATESOPTIONScontext_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
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
Simple XML-RPC and JSON-RPC server for modern Django

django-modern-rpc Build an XML-RPC and/or JSON-RPC server as part of your Django project. Major Django and Python versions are supported Main features

Antoine Lorence 82 Dec 04, 2022
Full featured redis cache backend for Django.

Redis cache backend for Django This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidel

Jazzband 2.5k Jan 03, 2023
The best way to have DRY Django forms. The app provides a tag and filter that lets you quickly render forms in a div format while providing an enormous amount of capability to configure and control the rendered HTML.

django-crispy-forms The best way to have Django DRY forms. Build programmatic reusable layouts out of components, having full control of the rendered

4.6k Jan 07, 2023
Adding Firebase Cloud Messaging Service into a Django Project

Adding Firebase Cloud Messaging Service into a Django Project The aim of this repository is to provide a step-by-step guide and a basic project sample

Seyyed Ali Ayati 11 Jan 03, 2023
Inject an ID into every log message from a Django request. ASGI compatible, integrates with Sentry, and works with Celery

Django GUID Now with ASGI support! Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request. In other words,

snok 300 Dec 29, 2022
A simple plugin to attach a debugger in Django on runserver command.

django-debugger A simple plugin to attach a debugger in Django during runserver Installation pip install django-debugger Usage Prepend django_debugger

Sajal Shrestha 11 Nov 15, 2021
Django channels basic chat

Django channels basic chat

Dennis Ivy 41 Dec 24, 2022
simple project management tool for educational purposes

Taskcamp This software is used for educational and demonstrative purposes. It's a simple project management tool powered by Django Framework Install B

Ilia Dmitriev 6 Nov 08, 2022
Management commands to help backup and restore your project database and media files

Django Database Backup This Django application provides management commands to help backup and restore your project database and media files with vari

687 Jan 04, 2023
Django Simple Spam Blocker is blocking spam by regular expression.

Django Simple Spam Blocker is blocking spam by regular expression.

Masahiko Okada 23 Nov 29, 2022
Django-Docker - Django Installation Guide on Docker

Guía de instalación del Framework Django en Docker Introducción: Con esta guía p

Victor manuel torres 3 Dec 02, 2022
Automatic caching and invalidation for Django models through the ORM.

Cache Machine Cache Machine provides automatic caching and invalidation for Django models through the ORM. For full docs, see https://cache-machine.re

846 Nov 26, 2022
Django With VueJS Blog App

django-blog-vue-app frontend Project setup yarn install Compiles and hot-reload

Flavien HUGS 2 Feb 04, 2022
PicoStyle - Advance market place website written in django

Advance market place website written in django :) Online fashion store for whole

AminAli Mazarian 26 Sep 10, 2022
Auto-detecting the n+1 queries problem in Python

nplusone nplusone is a library for detecting the n+1 queries problem in Python ORMs, including SQLAlchemy, Peewee, and the Django ORM. The Problem Man

Joshua Carp 837 Dec 29, 2022
a little task queue for python

a lightweight alternative. huey is: a task queue (2019-04-01: version 2.0 released) written in python (2.7+, 3.4+) clean and simple API redis, sqlite,

Charles Leifer 4.3k Dec 29, 2022
Store events and publish to Kafka

Create an event from Django ORM object model, store the event into the database and also publish it into Kafka cluster.

Diag 6 Nov 30, 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
A simple REST API to manage postal addresses, written in Python/Django.

A simple REST API to manage postal addresses, written in Python/Django.

Attila Bagossy 2 Feb 14, 2022