βœ‹ 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
Django-powered application about blockchain (bitcoin)

Django-powered application about blockchain (bitcoin)

Igor Izvekov 0 Jun 23, 2022
Add Chart.js visualizations to your Django admin using a mixin class

django-admincharts Add Chart.js visualizations to your Django admin using a mixin class. Example from django.contrib import admin from .models import

Dropseed 22 Nov 22, 2022
Django-discord-bot - Framework for creating Discord bots using Django

django-discord-bot Framework for creating Discord bots using Django Uses ASGI fo

Jamie Bliss 1 Mar 04, 2022
Django API that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format).

"Casares News" API Api that scrapes and provides the last news of the city of Carlos Casares by semantic way (RDF format). Usage Consume the articles

AndrΓ©s Milla 6 May 12, 2022
Django-MySQL extends Django's built-in MySQL and MariaDB support their specific features not available on other databases.

Django-MySQL The dolphin-pony - proof that cute + cute = double cute. Django-MySQL extends Django's built-in MySQL and MariaDB support their specific

Adam Johnson 504 Jan 04, 2023
Transparently use webpack with django

Looking for maintainers This repository is unmaintained as I don't have any free time to dedicate to this effort. If you or your organisation are heav

Owais Lone 2.4k Jan 06, 2023
PEP-484 type hints bindings for the Django web framework

mypy-django Type stubs to use the mypy static type-checker with your Django projects This project includes the PEP-484 compatible "type stubs" for Dja

Machinalis 223 Jun 17, 2022
https://django-storages.readthedocs.io/

Installation Installing from PyPI is as easy as doing: pip install django-storages If you'd prefer to install from source (maybe there is a bugfix in

Josh Schneier 2.3k Jan 06, 2023
Python CSS/Javascript minifier

Squeezeit - Python CSS and Javascript minifier Copyright (C) 2011 Sam Rudge This program is free software: you can redistribute it and/or modify it un

Smudge 152 Apr 03, 2022
Official Python agent for the Elastic APM

elastic-apm -- Elastic APM agent for Python This is the official Python module for Elastic APM. It provides full out-of-the-box support for many of th

elastic 369 Jan 05, 2023
Fast / fuzzy PostgreSQL counts for Django

Created by Stephen McDonald Introduction Up until PostgreSQL 9.2, COUNT queries generally required scanning every row in a database table. With millio

stephenmcd 85 Oct 25, 2021
Loguru is an exceeding easy way to do logging in Python

Django Easy Logging Easy Django logging with Loguru Loguru is an exceeding easy way to do logging in Python. django-easy-logging makes it exceedingly

Neutron Sync 8 Oct 17, 2022
Automatically reload your browser in development.

django-browser-reload Automatically reload your browser in development. Requirements Python 3.6 to 3.10 supported. Django 2.2 to 4.0 supported. Are yo

Adam Johnson 254 Jan 04, 2023
Automatically upgrade your Django projects.

django-upgrade Automatically upgrade your Django projects. Installation Use pip: python -m pip install django-upgrade Python 3.8 to 3.10 supported. Or

Adam Johnson 525 Dec 29, 2022
Keep track of failed login attempts in Django-powered sites.

django-axes Axes is a Django plugin for keeping track of suspicious login attempts for your Django based website and implementing simple brute-force a

Jazzband 1.1k Dec 30, 2022
Django server-side adapter for Inertia.js

django-inertia Django server-side new adapter for Inertia.js. Getting Started Install the package pip install django-inertia Configure your project A

Samuel Girardin 14 Sep 16, 2022
A calendaring app for Django. It is now stable, Please feel free to use it now. Active development has been taken over by bartekgorny.

Django-schedule A calendaring/scheduling application, featuring: one-time and recurring events calendar exceptions (occurrences changed or cancelled)

Tony Hauber 814 Dec 26, 2022
Simple tagging for django

django-taggit This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines. django-tagg

Jazzband 3k Jan 02, 2023
This website serves as an online database (hosted via SQLLite) for fictional businesses in the area to store contact information (name, email, phone number, etc.) for fictional customers.

Django-Online-Business-Database-Project this project is still in progress Overview of Website This website serves as an online database (hosted via SQ

1 Oct 30, 2021
Django's class-based generic views are awesome, let's have more of them.

Django Extra Views - The missing class-based generic views for Django Django-extra-views is a Django package which introduces additional class-based v

Andy Ingram 1.3k Jan 04, 2023