✋ 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
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Dec 29, 2022
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries. An example o

pytest-dev 9.6k Jan 06, 2023
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 simple demonstration of how a django-based website can be set up for local development with microk8s

Django with MicroK8s Start Building Your Project This project provides a Django web app running as a single node Kubernetes cluster in microk8s. It is

Noah Jacobson 19 Oct 22, 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
A simple E-commerce shop made with Django and Bulma

Interiorshop A Simple E-Commerce app made with Django Instructions Make sure you have python installed Step 1. Open a terminal Step 2. Paste the given

Aditya Priyadarshi 3 Sep 03, 2022
A simple demonstration of integrating a sentiment analysis tool in a django project

sentiment-analysis A simple demonstration of integrating a sentiment analysis tool in a django project (watch the video .mp4) To run this project : pi

2 Oct 16, 2021
Dynamic Django settings.

Constance - Dynamic Django settings A Django app for storing dynamic settings in pluggable backends (Redis and Django model backend built in) with an

Jazzband 1.5k Jan 07, 2023
Simple web site for sharing your short stories and beautiful pictures

Story Contest Simple web site for sharing your short stories and beautiful pictures.(Cloud computing first assignment) Clouds The table below shows cl

Alireza Akhoundi 5 Jan 04, 2023
Code coverage measurement for Python

Coverage.py Code coverage testing for Python. Coverage.py measures code coverage, typically during test execution. It uses the code analysis tools and

Ned Batchelder 2.3k Jan 05, 2023
Example project demonstrating using Django’s test runner with Coverage.py

Example project demonstrating using Django’s test runner with Coverage.py Set up with: python -m venv --prompt . venv source venv/bin/activate python

Adam Johnson 5 Nov 29, 2021
Easy thumbnails for Django

Easy Thumbnails A powerful, yet easy to implement thumbnailing application for Django 1.11+ Below is a quick summary of usage. For more comprehensive

Chris Beaven 1.3k Dec 30, 2022
Django React Project Setup

Django-React-Project-Setup INSTALLATION: python -m pip install drps USAGE: in your cmd: python -m drps Starting fullstack project with Django and Reac

Ghazi Zabalawi 7 Feb 06, 2022
Django Persistent Filters is a Python package which provide a django middleware that take care to persist the querystring in the browser cookies.

Django Persistent Filters Django Persistent Filters is a Python package which provide a django middleware that take care to persist the querystring in

Lorenzo Prodon 2 Aug 05, 2022
Store model history and view/revert changes from admin site.

django-simple-history django-simple-history stores Django model state on every create/update/delete. This app supports the following combinations of D

Jazzband 1.8k Jan 08, 2023
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

sageteam 51 Sep 15, 2022
An airlines clone website with django

abc_airlines is a clone website of an airlines system the way it works is that first you add flights to the website then the users can search flights

milad 1 Nov 16, 2021
Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.

Django Activity Stream What is Django Activity Stream? Django Activity Stream is a way of creating activities generated by the actions on your site. I

Justin Quick 2.1k Dec 29, 2022
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
Tools to easily create permissioned CRUD endpoints in graphene-django.

graphene-django-plus Tools to easily create permissioned CRUD endpoints in graphene-django. Install pip install graphene-django-plus To make use of ev

Zerosoft 74 Aug 09, 2022