✋ 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
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
A generic system for filtering Django QuerySets based on user selections

Django Filter Django-filter is a reusable Django application allowing users to declaratively add dynamic QuerySet filtering from URL parameters. Full

Carlton Gibson 3.9k Jan 3, 2023
:couple: Multi-user accounts for Django projects

django-organizations Summary Groups and multi-user account management Author Ben Lopatin (http://benlopatin.com / https://wellfire.co) Status Separate

Ben Lopatin 1.1k Jan 1, 2023
User Authentication In Django/Ajax/Jquery

User Authentication In Django/Ajax/Jquery Demo: Authentication System Using Django/Ajax/Jquery Demo: Authentication System Using Django Overview The D

Suman Raj Khanal 10 Mar 26, 2022
A Django app that allows visitors to interact with your site as a guest user without requiring registration.

django-guest-user A Django app that allows visitors to interact with your site as a guest user without requiring registration. Largely inspired by dja

Julian Wachholz 21 Dec 17, 2022
An example of Django project with basic user functionality and account activation.

Simple Django Login and Registration An example of Django project with basic user functionality. Screenshots Log In Create an account Authorized page

Hussein Sarea 3 Oct 19, 2022
django social media app with real time features

django-social-media django social media app with these features: signup, login and old registered users are saved by cookies posts, comments, replies,

null 8 Apr 30, 2022
It takes time to start a Django Project and make it almost production-ready.

It takes time to start a Django Project and make it almost production-ready. A developer needs to spend a lot of time installing required libraries, setup a database, setup cache as well as hiding secrets, configuring `settings` files. With the help of django-setup-cli a developer can start an `almost production ready` project in a minute.

Khan Asfi Reza 1 Jan 1, 2022
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022