django-login512 2.1.1__tar.gz

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,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-login512
3
+ Version: 2.1.1
4
+ Summary: Django authentication backend and login view for Login512 face scan and passkeys
5
+ Home-page: https://login512.com
6
+ Author: Login512 Team
7
+ License: Apache-2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: django>=4.2
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: home-page
19
+ Dynamic: license
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # django-login512 2.1.1
25
+
26
+ Django login with **Login512** (face scan + passkeys): an authentication backend, a login view and a nonce view.
27
+ Tokens are verified by the Login512 API with your **secret key**. Standard library HTTP, no extra dependencies.
28
+
29
+ ## Install
30
+ ```bash
31
+ pip install django-login512
32
+ ```
33
+
34
+ ```python
35
+ # settings.py
36
+ INSTALLED_APPS += ["login512_django"]
37
+ AUTHENTICATION_BACKENDS = ["login512_django.backend.Login512AuthBackend", "django.contrib.auth.backends.ModelBackend"]
38
+ LOGIN512_SECRET_KEY = os.environ["LOGIN512_SECRET_KEY"] # l512_sk_...
39
+ LOGIN512_ENDPOINT = "https://api.login512.com"
40
+ # LOGIN512_USER_FIELD = "username" # User field that equals claims.sub (your external_user_id)
41
+ # LOGIN512_CREATE_USERS = True # False: only users that already exist can log in
42
+
43
+ # urls.py
44
+ urlpatterns += [path("login512/", include("login512_django.urls"))]
45
+ ```
46
+
47
+ ## Frontend
48
+ Use any Login512 frontend package (or `<login512-button>` from `https://login512.com/sdk/login512-sdk.js`), then:
49
+ ```js
50
+ const { nonce } = await (await fetch('/login512/nonce/')).json(); // also sets the csrftoken cookie
51
+ // pass nonce to the button/login(); on success:
52
+ await fetch('/login512/login/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
53
+ body: JSON.stringify({ token }) });
54
+ ```
55
+ `POST /login512/login/` answers 200 `{ok: true, redirect}` and creates the Django session, or 401 `{ok: false, error}`.
56
+
57
+ In code: `django.contrib.auth.authenticate(request, login512_token=token)` or `login512_django.verify_token(token, nonce)`.
58
+
59
+ Created users are never staff or superuser and get an unusable password. 2.1.0 shipped without its Python package
60
+ (the sdist contained only setup.py) and accepted step-up tokens.
@@ -0,0 +1,37 @@
1
+ # django-login512 2.1.1
2
+
3
+ Django login with **Login512** (face scan + passkeys): an authentication backend, a login view and a nonce view.
4
+ Tokens are verified by the Login512 API with your **secret key**. Standard library HTTP, no extra dependencies.
5
+
6
+ ## Install
7
+ ```bash
8
+ pip install django-login512
9
+ ```
10
+
11
+ ```python
12
+ # settings.py
13
+ INSTALLED_APPS += ["login512_django"]
14
+ AUTHENTICATION_BACKENDS = ["login512_django.backend.Login512AuthBackend", "django.contrib.auth.backends.ModelBackend"]
15
+ LOGIN512_SECRET_KEY = os.environ["LOGIN512_SECRET_KEY"] # l512_sk_...
16
+ LOGIN512_ENDPOINT = "https://api.login512.com"
17
+ # LOGIN512_USER_FIELD = "username" # User field that equals claims.sub (your external_user_id)
18
+ # LOGIN512_CREATE_USERS = True # False: only users that already exist can log in
19
+
20
+ # urls.py
21
+ urlpatterns += [path("login512/", include("login512_django.urls"))]
22
+ ```
23
+
24
+ ## Frontend
25
+ Use any Login512 frontend package (or `<login512-button>` from `https://login512.com/sdk/login512-sdk.js`), then:
26
+ ```js
27
+ const { nonce } = await (await fetch('/login512/nonce/')).json(); // also sets the csrftoken cookie
28
+ // pass nonce to the button/login(); on success:
29
+ await fetch('/login512/login/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
30
+ body: JSON.stringify({ token }) });
31
+ ```
32
+ `POST /login512/login/` answers 200 `{ok: true, redirect}` and creates the Django session, or 401 `{ok: false, error}`.
33
+
34
+ In code: `django.contrib.auth.authenticate(request, login512_token=token)` or `login512_django.verify_token(token, nonce)`.
35
+
36
+ Created users are never staff or superuser and get an unusable password. 2.1.0 shipped without its Python package
37
+ (the sdist contained only setup.py) and accepted step-up tokens.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-login512
3
+ Version: 2.1.1
4
+ Summary: Django authentication backend and login view for Login512 face scan and passkeys
5
+ Home-page: https://login512.com
6
+ Author: Login512 Team
7
+ License: Apache-2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: django>=4.2
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: home-page
19
+ Dynamic: license
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # django-login512 2.1.1
25
+
26
+ Django login with **Login512** (face scan + passkeys): an authentication backend, a login view and a nonce view.
27
+ Tokens are verified by the Login512 API with your **secret key**. Standard library HTTP, no extra dependencies.
28
+
29
+ ## Install
30
+ ```bash
31
+ pip install django-login512
32
+ ```
33
+
34
+ ```python
35
+ # settings.py
36
+ INSTALLED_APPS += ["login512_django"]
37
+ AUTHENTICATION_BACKENDS = ["login512_django.backend.Login512AuthBackend", "django.contrib.auth.backends.ModelBackend"]
38
+ LOGIN512_SECRET_KEY = os.environ["LOGIN512_SECRET_KEY"] # l512_sk_...
39
+ LOGIN512_ENDPOINT = "https://api.login512.com"
40
+ # LOGIN512_USER_FIELD = "username" # User field that equals claims.sub (your external_user_id)
41
+ # LOGIN512_CREATE_USERS = True # False: only users that already exist can log in
42
+
43
+ # urls.py
44
+ urlpatterns += [path("login512/", include("login512_django.urls"))]
45
+ ```
46
+
47
+ ## Frontend
48
+ Use any Login512 frontend package (or `<login512-button>` from `https://login512.com/sdk/login512-sdk.js`), then:
49
+ ```js
50
+ const { nonce } = await (await fetch('/login512/nonce/')).json(); // also sets the csrftoken cookie
51
+ // pass nonce to the button/login(); on success:
52
+ await fetch('/login512/login/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken },
53
+ body: JSON.stringify({ token }) });
54
+ ```
55
+ `POST /login512/login/` answers 200 `{ok: true, redirect}` and creates the Django session, or 401 `{ok: false, error}`.
56
+
57
+ In code: `django.contrib.auth.authenticate(request, login512_token=token)` or `login512_django.verify_token(token, nonce)`.
58
+
59
+ Created users are never staff or superuser and get an unusable password. 2.1.0 shipped without its Python package
60
+ (the sdist contained only setup.py) and accepted step-up tokens.
@@ -0,0 +1,12 @@
1
+ README.md
2
+ setup.py
3
+ django_login512.egg-info/PKG-INFO
4
+ django_login512.egg-info/SOURCES.txt
5
+ django_login512.egg-info/dependency_links.txt
6
+ django_login512.egg-info/requires.txt
7
+ django_login512.egg-info/top_level.txt
8
+ login512_django/__init__.py
9
+ login512_django/backend.py
10
+ login512_django/client.py
11
+ login512_django/urls.py
12
+ login512_django/views.py
@@ -0,0 +1 @@
1
+ django>=4.2
@@ -0,0 +1 @@
1
+ login512_django
@@ -0,0 +1,5 @@
1
+ """django-login512: Login512 face scan / passkey login for Django."""
2
+ from .client import Login512Error, generate_nonce, verify_token
3
+
4
+ __version__ = "2.1.1"
5
+ __all__ = ["verify_token", "generate_nonce", "Login512Error", "__version__"]
@@ -0,0 +1,55 @@
1
+ """
2
+ Authentication backend. AUTHENTICATION_BACKENDS = ["login512_django.backend.Login512AuthBackend", ...]
3
+
4
+ claims.sub is the external_user_id YOU chose when enrolling the user (enrollment token / genesis). It is matched to
5
+ User.<LOGIN512_USER_FIELD> (default "username"). Unknown subs create a plain user (never staff/superuser, unusable
6
+ password) unless LOGIN512_CREATE_USERS = False.
7
+ """
8
+ from django.conf import settings
9
+ from django.contrib.auth import get_user_model
10
+ from django.contrib.auth.backends import BaseBackend
11
+
12
+ from .client import verify_token
13
+
14
+ SESSION_NONCE_KEY = "login512_nonce"
15
+
16
+
17
+ class Login512AuthBackend(BaseBackend):
18
+ # Only the dedicated `login512_token` keyword: a generic `token=` would make this backend send OTHER apps'
19
+ # tokens (magic links, OTP) to the Login512 API whenever it is listed first in AUTHENTICATION_BACKENDS.
20
+ def authenticate(self, request, login512_token=None, expected_nonce=None, **kwargs):
21
+ tok = login512_token
22
+ if not tok:
23
+ return None
24
+ if expected_nonce is None and request is not None and hasattr(request, "session"):
25
+ expected_nonce = request.session.pop(SESSION_NONCE_KEY, None)
26
+ res = verify_token(tok, expected_nonce)
27
+ if request is not None:
28
+ request.login512 = res
29
+ if not res.get("valid") or not res.get("sub"):
30
+ return None
31
+
32
+ User = get_user_model()
33
+ field = getattr(settings, "LOGIN512_USER_FIELD", User.USERNAME_FIELD)
34
+ user = User._default_manager.filter(**{field: res["sub"]}).first()
35
+ if user is None:
36
+ if not getattr(settings, "LOGIN512_CREATE_USERS", True):
37
+ return None
38
+ user = User(**{field: res["sub"]})
39
+ user.is_staff = False
40
+ user.is_superuser = False
41
+ user.set_unusable_password()
42
+ user.save()
43
+ return user if self.user_can_authenticate(user) else None
44
+
45
+ @staticmethod
46
+ def user_can_authenticate(user):
47
+ return getattr(user, "is_active", True)
48
+
49
+ def get_user(self, user_id):
50
+ User = get_user_model()
51
+ try:
52
+ user = User._default_manager.get(pk=user_id)
53
+ except User.DoesNotExist:
54
+ return None
55
+ return user if self.user_can_authenticate(user) else None
@@ -0,0 +1,59 @@
1
+ """Token verification against the Login512 API (POST /v1/token/verify with the SECRET key). Standard library only."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import secrets
6
+ import urllib.error
7
+ import urllib.request
8
+
9
+ from django.conf import settings
10
+
11
+ DEFAULT_ENDPOINT = "https://api.login512.com"
12
+
13
+
14
+ class Login512Error(Exception):
15
+ pass
16
+
17
+
18
+ def generate_nonce() -> str:
19
+ return secrets.token_urlsafe(32)
20
+
21
+
22
+ def verify_token(token: str, expected_nonce: str | None = None, *, timeout: float = 8.0) -> dict:
23
+ """
24
+ Returns {"valid": True, "claims": {...}, "sub": "..."} only when the API says valid=true AND no step-up is
25
+ required; otherwise {"valid": False, "error": CODE}. HTTP 200 alone is NOT success: rejected tokens come back as
26
+ 200 {"valid": false, "error": "TOKEN_ALREADY_USED" | "TOKEN_BAD_SIGNATURE" | "NONCE_MISMATCH" | ...}.
27
+ """
28
+ secret_key = getattr(settings, "LOGIN512_SECRET_KEY", "") or ""
29
+ if not secret_key.startswith("l512_sk_"):
30
+ raise Login512Error("settings.LOGIN512_SECRET_KEY must start with l512_sk_")
31
+ if not token:
32
+ return {"valid": False, "error": "MISSING_TOKEN"}
33
+ endpoint = (getattr(settings, "LOGIN512_ENDPOINT", "") or DEFAULT_ENDPOINT).rstrip("/")
34
+ body = {"token": token}
35
+ if expected_nonce:
36
+ body["expected_nonce"] = expected_nonce
37
+ req = urllib.request.Request(
38
+ f"{endpoint}/v1/token/verify", data=json.dumps(body).encode(), method="POST",
39
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {secret_key}",
40
+ "User-Agent": "django-login512/2.1.1"})
41
+ try:
42
+ with urllib.request.urlopen(req, timeout=timeout) as r:
43
+ data = json.loads(r.read() or b"{}")
44
+ except urllib.error.HTTPError as e:
45
+ try:
46
+ err = json.loads(e.read() or b"{}").get("error")
47
+ except Exception:
48
+ err = None
49
+ code = err.get("code") or err.get("message") if isinstance(err, dict) else err
50
+ return {"valid": False, "error": code or f"HTTP_{e.code}"}
51
+ except (urllib.error.URLError, TimeoutError, ValueError) as e:
52
+ return {"valid": False, "error": f"VERIFY_UNAVAILABLE: {e}"}
53
+ if data.get("valid") is not True:
54
+ err = data.get("error")
55
+ return {"valid": False, "error": (err.get("code") if isinstance(err, dict) else err) or "TOKEN_INVALID"}
56
+ if data.get("step_up_required") is True:
57
+ return {"valid": False, "error": "STEP_UP_REQUIRED", "claims": data.get("claims") or {}}
58
+ claims = data.get("claims") or {}
59
+ return {"valid": True, "claims": claims, "sub": claims.get("sub")}
@@ -0,0 +1,9 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ app_name = "login512"
6
+ urlpatterns = [
7
+ path("login/", views.login_view, name="login"),
8
+ path("nonce/", views.nonce_view, name="nonce"),
9
+ ]
@@ -0,0 +1,38 @@
1
+ """
2
+ POST login512/login/ {"token": "..."} (JSON or form; send the CSRF token as X-CSRFToken) -> Django session.
3
+ GET login512/nonce/ -> {"nonce": "..."} + csrftoken cookie; pass the nonce to the button/login(); checked once at login.
4
+ """
5
+ import json
6
+
7
+ from django.conf import settings
8
+ from django.contrib.auth import authenticate, login
9
+ from django.http import JsonResponse
10
+ from django.views.decorators.csrf import ensure_csrf_cookie
11
+ from django.views.decorators.http import require_GET, require_POST
12
+
13
+ from .backend import SESSION_NONCE_KEY
14
+ from .client import generate_nonce
15
+
16
+
17
+ @require_GET
18
+ @ensure_csrf_cookie # also sets the csrftoken cookie, so a JS-only frontend can send X-CSRFToken to login_view
19
+ def nonce_view(request):
20
+ nonce = generate_nonce()
21
+ request.session[SESSION_NONCE_KEY] = nonce
22
+ return JsonResponse({"nonce": nonce})
23
+
24
+
25
+ @require_POST
26
+ def login_view(request):
27
+ token = request.POST.get("token")
28
+ if not token and request.content_type == "application/json":
29
+ try:
30
+ token = (json.loads(request.body or b"{}") or {}).get("token")
31
+ except ValueError:
32
+ token = None
33
+ user = authenticate(request, login512_token=token)
34
+ if user is None:
35
+ res = getattr(request, "login512", None) or {}
36
+ return JsonResponse({"ok": False, "error": res.get("error") or "LOGIN_FAILED"}, status=401)
37
+ login(request, user, backend="login512_django.backend.Login512AuthBackend")
38
+ return JsonResponse({"ok": True, "redirect": getattr(settings, "LOGIN_REDIRECT_URL", "/")})
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,20 @@
1
+ from setuptools import setup
2
+
3
+ setup(
4
+ name="django-login512",
5
+ version="2.1.1",
6
+ packages=["login512_django"],
7
+ install_requires=["django>=4.2"],
8
+ python_requires=">=3.9",
9
+ author="Login512 Team",
10
+ description="Django authentication backend and login view for Login512 face scan and passkeys",
11
+ long_description=open("README.md", encoding="utf-8").read(),
12
+ long_description_content_type="text/markdown",
13
+ license="Apache-2.0",
14
+ url="https://login512.com",
15
+ classifiers=[
16
+ "Programming Language :: Python :: 3",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Operating System :: OS Independent",
19
+ ],
20
+ )