Skip to content

Commit de9d1e5

Browse files
committed
Add auto logout on SESSION_TIME expired
0 parents  commit de9d1e5

File tree

23 files changed

+455
-0
lines changed

23 files changed

+455
-0
lines changed

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/.*
2+
!.gitignore
3+
!.travis.yml
4+
__pycache__
5+
*.egg-info
6+
venv
7+
htmlcov

.travis.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
language: python
2+
python:
3+
- "3.5"
4+
- "3.6"
5+
- "3.7"
6+
- "3.8"
7+
- "3.9"
8+
- "3.10"
9+
install:
10+
- pip install -r requirements.txt
11+
script:
12+
- tox

README.rst

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
django-auto-logout
2+
==================
3+
4+
.. figure:: https://travis-ci.org/bugov/django-auto-logout.svg?branch=master
5+
6+
Auto logout a user after specific time in Django.
7+
8+
Works with Python ≥ 3.5, Django ≥ 3.0.
9+
10+
Installation
11+
------------
12+
13+
.. code:: bash
14+
15+
pip install django-auto-logout
16+
17+
18+
Append to `settings` middlewares:
19+
20+
.. code:: python
21+
22+
MIDDLEWARE = (
23+
...
24+
'django_auto_logout.middleware.auto_logout',
25+
)
26+
27+
Limit session time
28+
------------------
29+
30+
Logout a user after 3600 seconds (hour) from the last login.
31+
32+
Add to `settings`:
33+
34+
.. code:: python
35+
36+
AUTO_LOGOUT = {'SESSION_TIME': 3600}

django_auto_logout/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__version__ = '0.1.0'

django_auto_logout/middleware.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from datetime import datetime, timedelta
2+
import logging
3+
from typing import Callable
4+
from django.conf import settings
5+
from django.http import HttpRequest, HttpResponse
6+
from django.contrib.auth import get_user_model, logout
7+
from pytz import timezone
8+
9+
UserModel = get_user_model()
10+
logger = logging.getLogger(__name__)
11+
12+
13+
def _auto_logout(request: HttpRequest, options):
14+
user = request.user
15+
should_logout = False
16+
17+
if settings.USE_TZ:
18+
now = datetime.now(tz=timezone(settings.TIME_ZONE))
19+
else:
20+
now = datetime.now()
21+
22+
if 'SESSION_TIME' in options:
23+
ttl = options['SESSION_TIME']
24+
should_logout = user.last_login < now - timedelta(seconds=ttl)
25+
logger.debug('Check SESSION_TIME: %s < %s (%s)', user.last_login, now, should_logout)
26+
27+
if should_logout:
28+
logger.debug('Logout user %s', user)
29+
logout(request)
30+
31+
32+
def auto_logout(get_response: Callable[[HttpRequest], HttpResponse]) -> Callable:
33+
def middleware(request: HttpRequest) -> HttpResponse:
34+
if not request.user.is_anonymous and hasattr(settings, 'AUTO_LOGOUT'):
35+
_auto_logout(request, settings.AUTO_LOGOUT)
36+
37+
return get_response(request)
38+
return middleware

example/example/__init__.py

Whitespace-only changes.

example/example/asgi.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
ASGI config for example project.
3+
4+
It exposes the ASGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.asgi import get_asgi_application
13+
14+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
15+
16+
application = get_asgi_application()

example/example/settings.py

Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
"""
2+
Django settings for example project.
3+
4+
Generated by 'django-admin startproject' using Django 3.2.8.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/3.2/topics/settings/
8+
9+
For the full list of settings and their values, see
10+
https://docs.djangoproject.com/en/3.2/ref/settings/
11+
"""
12+
13+
from pathlib import Path
14+
15+
# Build paths inside the project like this: BASE_DIR / 'subdir'.
16+
BASE_DIR = Path(__file__).resolve().parent.parent
17+
18+
19+
# Quick-start development settings - unsuitable for production
20+
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
21+
22+
# SECURITY WARNING: keep the secret key used in production secret!
23+
SECRET_KEY = 'django-insecure-1d*y)p@6kwiv_oh+6wh(k=z3+mb90+z3)3oyzkz67*8lb^(*-9'
24+
25+
# SECURITY WARNING: don't run with debug turned on in production!
26+
DEBUG = True
27+
28+
ALLOWED_HOSTS = []
29+
30+
31+
# Application definition
32+
33+
INSTALLED_APPS = [
34+
'django.contrib.admin',
35+
'django.contrib.auth',
36+
'django.contrib.contenttypes',
37+
'django.contrib.sessions',
38+
'django.contrib.messages',
39+
'django.contrib.staticfiles',
40+
41+
'some_app_login_required',
42+
]
43+
44+
MIDDLEWARE = [
45+
'django.middleware.security.SecurityMiddleware',
46+
'django.contrib.sessions.middleware.SessionMiddleware',
47+
'django.middleware.common.CommonMiddleware',
48+
'django.middleware.csrf.CsrfViewMiddleware',
49+
'django.contrib.auth.middleware.AuthenticationMiddleware',
50+
'django.contrib.messages.middleware.MessageMiddleware',
51+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
52+
'django_auto_logout.middleware.auto_logout',
53+
]
54+
55+
ROOT_URLCONF = 'example.urls'
56+
57+
TEMPLATES = [
58+
{
59+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
60+
'DIRS': [],
61+
'APP_DIRS': True,
62+
'OPTIONS': {
63+
'context_processors': [
64+
'django.template.context_processors.debug',
65+
'django.template.context_processors.request',
66+
'django.contrib.auth.context_processors.auth',
67+
'django.contrib.messages.context_processors.messages',
68+
],
69+
},
70+
},
71+
]
72+
73+
WSGI_APPLICATION = 'example.wsgi.application'
74+
75+
76+
# Database
77+
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
78+
79+
DATABASES = {
80+
'default': {
81+
'ENGINE': 'django.db.backends.sqlite3',
82+
'NAME': BASE_DIR / 'db.sqlite3',
83+
}
84+
}
85+
86+
87+
# Password validation
88+
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
89+
90+
AUTH_PASSWORD_VALIDATORS = [
91+
{
92+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
93+
},
94+
{
95+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
96+
},
97+
{
98+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
99+
},
100+
{
101+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
102+
},
103+
]
104+
105+
106+
# Internationalization
107+
# https://docs.djangoproject.com/en/3.2/topics/i18n/
108+
109+
LANGUAGE_CODE = 'en-us'
110+
111+
TIME_ZONE = 'UTC'
112+
113+
USE_I18N = True
114+
115+
USE_L10N = True
116+
117+
USE_TZ = True
118+
119+
120+
# Static files (CSS, JavaScript, Images)
121+
# https://docs.djangoproject.com/en/3.2/howto/static-files/
122+
123+
STATIC_URL = '/static/'
124+
125+
# Default primary key field type
126+
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
127+
128+
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
129+
130+
131+
LOGGING = {
132+
'version': 1,
133+
'disable_existing_loggers': False,
134+
'filters': {
135+
'require_debug_false': {
136+
'()': 'django.utils.log.RequireDebugFalse'
137+
}
138+
},
139+
'formatters': {
140+
'standard': {
141+
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
142+
},
143+
},
144+
'handlers': {
145+
'default': {
146+
'level': 'DEBUG',
147+
'formatter': 'standard',
148+
'class': 'logging.StreamHandler',
149+
},
150+
},
151+
'loggers': {
152+
'': {
153+
'handlers': ['default'],
154+
'level': 'DEBUG',
155+
'propagate': False,
156+
},
157+
},
158+
}
159+
160+
LOGIN_URL = '/login/'
161+
162+
163+
# DJANGO AUTO LOGIN

example/example/urls.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from django.contrib import admin
2+
from django.urls import path
3+
4+
from some_app_login_required.views import login_page, login_required_view
5+
6+
urlpatterns = [
7+
path('admin/', admin.site.urls),
8+
path('login/', login_page),
9+
path('login-required/', login_required_view),
10+
]

example/example/wsgi.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
WSGI config for example project.
3+
4+
It exposes the WSGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.wsgi import get_wsgi_application
13+
14+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'example.settings')
15+
16+
application = get_wsgi_application()

0 commit comments

Comments
 (0)