django-light-auth 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ from django_light_auth.runtimes import ( # noqa F401
2
+ LightAuthMiddleware,
3
+ do_login,
4
+ do_logout,
5
+ do_validate,
6
+ light_auth_validate_func,
7
+ )
8
+ from django_light_auth.views import LoginForm, LoginView, LogoutView # noqa F401
9
+
10
+ default_app_config = "django_light_auth.apps.DjangoLightAuthConfig"
11
+
12
+ __version__ = "0.2.3"
@@ -0,0 +1,3 @@
1
+ # from django.contrib import admin
2
+
3
+ # Register your models here.
@@ -0,0 +1,51 @@
1
+ from datetime import datetime, timedelta
2
+ from uuid import uuid4
3
+
4
+ from django.apps import AppConfig
5
+ from django.conf import settings
6
+
7
+
8
+ class DjangoLightAuthConfig(AppConfig):
9
+ name = "django_light_auth"
10
+ default = True
11
+
12
+ login_path = "/login"
13
+ logout_path = "/logout"
14
+ success_path = "/"
15
+
16
+ validate_func = "django_light_auth.light_auth_validate_func"
17
+
18
+ allow_paths = set()
19
+
20
+ token = uuid4().hex
21
+ # https://docs.djangoproject.com/en/3.1/topics/http/sessions/
22
+ expiry: None | int | datetime | timedelta = 3600 # 1 hour
23
+
24
+ def ready(self):
25
+ # func
26
+ value = getattr(settings, "LIGHT_AUTH_VALIDATE_FUNC", "")
27
+ if value:
28
+ self.validate_func = value
29
+
30
+ # path
31
+ value = getattr(settings, "LIGHT_AUTH_LOGIN_PATH", "")
32
+ if value:
33
+ self.login_path = value.rstrip("/")
34
+ value = getattr(settings, "LIGHT_AUTH_LOGOUT_PATH", "")
35
+ if value:
36
+ self.logout_path = value.rstrip("/")
37
+
38
+ self.allow_paths.add(self.login_path)
39
+ self.allow_paths.add(self.logout_path)
40
+
41
+ # expiry
42
+ value = getattr(settings, "LIGHT_AUTH_EXPIRY", None)
43
+ if value is None:
44
+ # https://docs.djangoproject.com/en/3.1/topics/http/sessions/
45
+ # "If value is None,
46
+ # the session reverts to using the global session expiry policy."
47
+ self.expiry = None
48
+ elif isinstance(value, int) and value >= 0:
49
+ self.expiry = value
50
+ elif isinstance(value, (datetime, timedelta)):
51
+ self.expiry = value
@@ -0,0 +1,119 @@
1
+ import logging
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+
5
+ from django.apps import apps
6
+ from django.http import HttpRequest, HttpResponseRedirect
7
+
8
+ logger = logging.getLogger(__file__)
9
+
10
+ TOKEN_KEY = "light_auth_token"
11
+
12
+
13
+ def _get_session_from_request(request: HttpRequest):
14
+ try:
15
+ session = request.__getattribute__("session")
16
+ except AttributeError:
17
+ raise Exception(
18
+ "Missed django.contrib.sessions.middleware.SessionMiddleware, "
19
+ "django-light-auth depend it."
20
+ )
21
+ return session
22
+
23
+
24
+ def do_login(request: HttpRequest) -> str:
25
+ session = _get_session_from_request(request)
26
+ session[TOKEN_KEY] = apps.get_app_config("django_light_auth").token
27
+ expiry = apps.get_app_config("django_light_auth").expiry
28
+ if expiry is not None:
29
+ # https://docs.djangoproject.com/en/3.1/topics/http/sessions/
30
+ # "If value is None,
31
+ # the session reverts to using the global session expiry policy."
32
+ session.set_expiry(apps.get_app_config("django_light_auth").expiry)
33
+
34
+ return apps.get_app_config("django_light_auth").success_path
35
+
36
+
37
+ def do_logout(request: HttpRequest) -> str:
38
+ session = _get_session_from_request(request)
39
+ session[TOKEN_KEY] = False
40
+
41
+ return apps.get_app_config("django_light_auth").login_path
42
+
43
+
44
+ def _import_func(func_name: str, father_model=None) -> Callable | None:
45
+ try:
46
+ index = func_name.find(".")
47
+ if index == -1:
48
+ func = getattr(father_model, func_name[index + 1 :])
49
+ return func
50
+
51
+ else:
52
+ if father_model is None:
53
+ module = __import__(func_name[:index])
54
+
55
+ else:
56
+ module = getattr(father_model, func_name[:index])
57
+
58
+ return _import_func(func_name[index + 1 :], module)
59
+
60
+ except (ImportError, AttributeError, ValueError) as e:
61
+ logger.error(e)
62
+ logger.error(f"func_name: {func_name}, father_model:{father_model}")
63
+ return None
64
+
65
+
66
+ def do_validate(data: dict[str, Any]) -> bool:
67
+ func_name = apps.get_app_config("django_light_auth").validate_func
68
+
69
+ func = _import_func(func_name)
70
+ if func is None:
71
+ raise ImportError(f"Can import: {func_name}")
72
+
73
+ if func(data):
74
+ return True
75
+
76
+ return False
77
+
78
+
79
+ def light_auth_validate_func(data: dict[str, Any]) -> bool:
80
+ """demo for setting.LIGHT_AUTH_VALIDATE_FUNC"""
81
+ if data.get("username", None) == data.get("password", None):
82
+ return True
83
+
84
+ return False
85
+
86
+
87
+ def validate_request(request: HttpRequest) -> bool:
88
+ path = request.path.rstrip("/")
89
+ if path in apps.get_app_config("django_light_auth").allow_paths:
90
+ return True
91
+
92
+ session = _get_session_from_request(request)
93
+ token = session.get(TOKEN_KEY, "")
94
+ if token == apps.get_app_config("django_light_auth").token:
95
+ return True
96
+
97
+ return False
98
+
99
+
100
+ class LightAuthMiddleware:
101
+ def __init__(self, get_response):
102
+ self.get_response = get_response
103
+ # One-time configuration and initialization.
104
+
105
+ def __call__(self, request: HttpRequest):
106
+ # Code to be executed for each request before
107
+ # the view (and later middleware) are called.
108
+
109
+ response = self.get_response(request)
110
+
111
+ # Code to be executed for each request/response after
112
+ # the view is called.
113
+
114
+ if not validate_request(request):
115
+ return HttpResponseRedirect(
116
+ apps.get_app_config("django_light_auth").login_path
117
+ )
118
+
119
+ return response
@@ -0,0 +1,3 @@
1
+ # from django.test import TestCase
2
+
3
+ # Create your tests here.
@@ -0,0 +1,40 @@
1
+ from django import forms
2
+ from django.contrib import messages
3
+ from django.http import HttpResponseRedirect
4
+ from django.views.generic import FormView, View
5
+
6
+ from django_light_auth.runtimes import do_login, do_logout, do_validate
7
+
8
+
9
+ class LoginForm(forms.Form):
10
+ username = forms.CharField()
11
+ password = forms.CharField(widget=forms.PasswordInput)
12
+ # next = forms.CharField() # TODO
13
+
14
+
15
+ class LoginView(FormView):
16
+ template_name = "django_light_auth/login.html"
17
+ form_class = LoginForm
18
+ initial = dict()
19
+
20
+ def get(self, request, *args, **kwargs):
21
+ # next
22
+ return super().get(request, *args, **kwargs)
23
+
24
+ def form_valid(self, form):
25
+ if do_validate(form.cleaned_data):
26
+ self.success_url = do_login(self.request)
27
+ return HttpResponseRedirect(self.success_url)
28
+
29
+ messages.add_message(
30
+ self.request,
31
+ messages.ERROR,
32
+ "Invalid username and/or password! Please try again.",
33
+ )
34
+ self.initial["username"] = form.cleaned_data["username"]
35
+ return HttpResponseRedirect(self.request.path)
36
+
37
+
38
+ class LogoutView(View):
39
+ def get(self, request, *args, **kwargs):
40
+ return HttpResponseRedirect(do_logout(request))
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-light-auth
3
+ Version: 0.2.3
4
+ Summary: Django Lightweight Authentication without models and databases, only depend on the signed cookies and the Django's SessionMiddleware.
5
+ Author: Rex Zhang
6
+ Author-email: rex.zhang@gmail.com
7
+ Project-URL: homepage, https://github.com/rexzhang/django-light-auth
8
+ Keywords: django,auth
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: Django :: 5.0
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: django>=5.0
15
+ Dynamic: license-file
16
+
17
+ # django-light-auth
18
+
19
+ [![PyPI - Version](https://img.shields.io/pypi/v/django-light-auth.svg)](https://pypi.org/project/django-light-auth/)
20
+ ![Python Version from PEP 621 TOML](https://img.shields.io/python/required-version-toml?tomlFilePath=https://raw.githubusercontent.com/rexzhang/django-light-auth/main/pyproject.toml)
21
+ [![PyPI - Django Version](https://img.shields.io/pypi/djversions/django-light-auth)](https://pypi.org/project/django-light-auth/)
22
+ [![PyPI - Downloads](https://img.shields.io/pypi/dm/django-light-auth.svg)](https://pypi.org/project/django-light-auth/)
23
+
24
+ > Django Lightweight Authentication without models and databases, only depend on the signed cookies and the Django's SessionMiddleware.
25
+
26
+ ## Install
27
+
28
+ ```shell
29
+ pip3 install -U django-light-auth
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ### Basic Usage
35
+
36
+ #### `settings.py`
37
+
38
+ ```python
39
+ INSTALLED_APPS = [
40
+ # ...
41
+ # 'django.contrib.auth',
42
+ 'django_light_auth.apps.DjangoLightAuthConfig',
43
+
44
+ # ...
45
+ ]
46
+
47
+ MIDDLEWARE = [
48
+ # ...
49
+
50
+ 'django.contrib.sessions.middleware.SessionMiddleware',
51
+ # 'django.contrib.auth.middleware.AuthenticationMiddleware',
52
+ 'django_light_auth.LightAuthMiddleware'
53
+
54
+ # ...
55
+ ]
56
+
57
+ # Session
58
+ SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'
59
+
60
+ # django-light-auth
61
+ LIGHT_AUTH_VALIDATE_FUNC = 'your_app.auth.validate_func'
62
+ ```
63
+
64
+ #### `urls.py`
65
+
66
+ ```python
67
+ from django.urls import path
68
+
69
+ from django_light_auth import LoginView, LogoutView
70
+
71
+ urlpatterns = [
72
+ # ...
73
+ path('login', LoginView.as_view(), name='login'),
74
+ path('logout', LogoutView.as_view(), name='logout'),
75
+ ]
76
+ ```
77
+
78
+ #### `your_app/auth/validate_func.py`
79
+
80
+ ```python
81
+ #
82
+ # example at django_light_auth.light_auth_validate_func
83
+ #
84
+
85
+ from typing import Dict, Any
86
+
87
+ from your_app.config import config
88
+
89
+ def light_auth_validate_func(data: Dict[str, Any]) -> bool:
90
+ if data.get('username', None) == config.Auth.username and data.get(
91
+ 'password', None
92
+ ) == config.Auth.password:
93
+ return True
94
+
95
+ return False
96
+ ```
97
+
98
+ ### Custom Login View
99
+
100
+ `your_login_view.py`
101
+
102
+ ```python
103
+ from django_light_auth import LoginView as LoginViewAbs
104
+
105
+
106
+ class LoginView(LoginViewAbs):
107
+ template_name = 'your_app/login.html'
108
+ ```
109
+
110
+ ## History
111
+
112
+ ### 0.2.3 - 20251112
113
+
114
+ - Maintenance release
115
+
116
+ ### v0.2.2 - 20220809
117
+
118
+ - Compatible Django 4.1+
@@ -0,0 +1,11 @@
1
+ django_light_auth/__init__.py,sha256=Uor9sQupAhGTxkdRaCAbf9gCMX-ok-U_ZqhU82KeM6w,331
2
+ django_light_auth/admin.py,sha256=VWlhkFyPcKZz6ThllvIz1NT1yhDC-eBsdDWtpsuuhO0,65
3
+ django_light_auth/apps.py,sha256=tMvGYFHFTl3eqCgEC-pLurVA9TTOxEfco899D0JbPZ0,1569
4
+ django_light_auth/runtimes.py,sha256=jFJPsTG9UHp1bVkMpU1ouzpRdMEGJRMQ-D71oym4v_E,3503
5
+ django_light_auth/tests.py,sha256=oGgalLR6qiJdN-bHSH1ZLbRNhJHX_MyZtKsaR4jRy_Q,62
6
+ django_light_auth/views.py,sha256=8_E7zF9GxRW2Lyr1qBIdIPqyNWZni_l6Up97GND9jeA,1227
7
+ django_light_auth-0.2.3.dist-info/licenses/LICENSE,sha256=MCC2EV4rryc4M1gRogsemKBRr3P_OZe0HcTFxmRY4Uw,1066
8
+ django_light_auth-0.2.3.dist-info/METADATA,sha256=JkRA8GYHTRNqJ-NJL-eaMw6scD84DC2WVc_l0yPOxN4,2842
9
+ django_light_auth-0.2.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ django_light_auth-0.2.3.dist-info/top_level.txt,sha256=GVU2tghDf0-jv2Pp3IRSyxjbkXdmdebG6957XrBOTkI,18
11
+ django_light_auth-0.2.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Rex Zhang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ django_light_auth