9in-django 0.1.0__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.
- 9in_django-0.1.0/.gitignore +17 -0
- 9in_django-0.1.0/CHANGELOG.md +36 -0
- 9in_django-0.1.0/LICENSE +21 -0
- 9in_django-0.1.0/PKG-INFO +491 -0
- 9in_django-0.1.0/README.md +452 -0
- 9in_django-0.1.0/docs/img/logo.png +0 -0
- 9in_django-0.1.0/examples/demo/README.md +23 -0
- 9in_django-0.1.0/pyproject.toml +71 -0
- 9in_django-0.1.0/src/nine_django/__init__.py +75 -0
- 9in_django-0.1.0/src/nine_django/adapter/__init__.py +10 -0
- 9in_django-0.1.0/src/nine_django/adapter/otp.py +57 -0
- 9in_django-0.1.0/src/nine_django/adapter/urls.py +14 -0
- 9in_django-0.1.0/src/nine_django/adapter/users.py +223 -0
- 9in_django-0.1.0/src/nine_django/adapter/views.py +32 -0
- 9in_django-0.1.0/src/nine_django/admin.py +13 -0
- 9in_django-0.1.0/src/nine_django/api.py +181 -0
- 9in_django-0.1.0/src/nine_django/apps.py +20 -0
- 9in_django-0.1.0/src/nine_django/backends.py +241 -0
- 9in_django-0.1.0/src/nine_django/cache.py +53 -0
- 9in_django-0.1.0/src/nine_django/checks.py +118 -0
- 9in_django-0.1.0/src/nine_django/conf.py +220 -0
- 9in_django-0.1.0/src/nine_django/decorators.py +88 -0
- 9in_django-0.1.0/src/nine_django/management/__init__.py +0 -0
- 9in_django-0.1.0/src/nine_django/management/commands/__init__.py +0 -0
- 9in_django-0.1.0/src/nine_django/management/commands/nine_login_link.py +64 -0
- 9in_django-0.1.0/src/nine_django/middleware.py +80 -0
- 9in_django-0.1.0/src/nine_django/migrations/0001_initial.py +41 -0
- 9in_django-0.1.0/src/nine_django/migrations/__init__.py +0 -0
- 9in_django-0.1.0/src/nine_django/models.py +33 -0
- 9in_django-0.1.0/src/nine_django/py.typed +0 -0
- 9in_django-0.1.0/src/nine_django/rest_framework.py +102 -0
- 9in_django-0.1.0/src/nine_django/services.py +189 -0
- 9in_django-0.1.0/src/nine_django/session.py +261 -0
- 9in_django-0.1.0/src/nine_django/signals.py +135 -0
- 9in_django-0.1.0/src/nine_django/templates/nine_django/error.html +33 -0
- 9in_django-0.1.0/src/nine_django/templates/nine_django/otp_email.html +8 -0
- 9in_django-0.1.0/src/nine_django/templates/nine_django/otp_email.txt +6 -0
- 9in_django-0.1.0/src/nine_django/templates/nine_django/otp_email_subject.txt +1 -0
- 9in_django-0.1.0/src/nine_django/urls.py +24 -0
- 9in_django-0.1.0/src/nine_django/views.py +235 -0
- 9in_django-0.1.0/src/nine_django/webhooks.py +82 -0
- 9in_django-0.1.0/tests/__init__.py +0 -0
- 9in_django-0.1.0/tests/conftest.py +101 -0
- 9in_django-0.1.0/tests/fake_tenant.py +587 -0
- 9in_django-0.1.0/tests/live/__init__.py +0 -0
- 9in_django-0.1.0/tests/live/live.py +174 -0
- 9in_django-0.1.0/tests/live/test_live.py +356 -0
- 9in_django-0.1.0/tests/live/urls.py +30 -0
- 9in_django-0.1.0/tests/settings.py +90 -0
- 9in_django-0.1.0/tests/test_adapter.py +364 -0
- 9in_django-0.1.0/tests/test_api.py +287 -0
- 9in_django-0.1.0/tests/test_drf.py +87 -0
- 9in_django-0.1.0/tests/test_middleware.py +162 -0
- 9in_django-0.1.0/tests/test_misc.py +272 -0
- 9in_django-0.1.0/tests/test_signin.py +421 -0
- 9in_django-0.1.0/tests/test_vectors.py +83 -0
- 9in_django-0.1.0/tests/test_webhooks.py +256 -0
- 9in_django-0.1.0/tests/testapp/__init__.py +0 -0
- 9in_django-0.1.0/tests/testapp/drf.py +42 -0
- 9in_django-0.1.0/tests/testapp/migrations/0001_initial.py +30 -0
- 9in_django-0.1.0/tests/testapp/migrations/__init__.py +0 -0
- 9in_django-0.1.0/tests/testapp/models.py +9 -0
- 9in_django-0.1.0/tests/testapp/views.py +53 -0
- 9in_django-0.1.0/tests/urls.py +29 -0
- 9in_django-0.1.0/tox.ini +27 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
The first release of the official Django SDK for 9in, built on the 9in Python SDK (`9in`).
|
|
6
|
+
|
|
7
|
+
- **Sign-in**: `/nine/login`, `/nine/signup`, `/nine/callback` and `/nine/logout` (include
|
|
8
|
+
`nine_django.urls`). Authorization code flow with PKCE S256, single-use `state`, `nonce`, the
|
|
9
|
+
RFC 9207 `iss` check and a verified ID token. `return_to` and `next` accept same-site paths
|
|
10
|
+
only. Logout revokes the refresh token, ends the Django session and the 9in session.
|
|
11
|
+
- **Local users**: `NineBackend` signs each 9in user in as a Django user with
|
|
12
|
+
`django.contrib.auth.login()` (session key cycled). The user is linked through the new
|
|
13
|
+
`NineIdentity` model (`iss` + `sub`, migration included), by the adapter id 9in keeps for
|
|
14
|
+
users of your own database, or by verified email, and created otherwise. `CREATE_USERS`,
|
|
15
|
+
`LINK_BY_EMAIL`, `UPDATE_USERS` and `USER_FIELDS` change this.
|
|
16
|
+
- **`NineMiddleware`**: refreshes the session's tokens before they expire and keeps the
|
|
17
|
+
rotated refresh token. It signs the user out when 9in refuses the refresh token, and sets
|
|
18
|
+
`request.nine` (claims, `sub`, `access_token()`). Works under WSGI and ASGI.
|
|
19
|
+
- **APIs**: `@require_token(scope=...)` for sync and async views, and
|
|
20
|
+
`nine_django.rest_framework.NineTokenAuthentication` + `HasScope` for Django REST framework.
|
|
21
|
+
Tokens go through `HybridTokenVerifier` with Django's cache: hybrid by default when client
|
|
22
|
+
credentials are set, otherwise `local` or `introspect`. `request.user` is the linked user or a
|
|
23
|
+
`TokenUser`.
|
|
24
|
+
- **Webhooks** at `/nine/webhook`: signature check (secret rotation, `WEBHOOK_PATH` behind
|
|
25
|
+
proxies) and eviction of revoked tokens. Each event is processed once with `cache.add`
|
|
26
|
+
(204 / 409 / released on errors) and sent as a Django signal per event type plus
|
|
27
|
+
`event_received`.
|
|
28
|
+
- **Your own user database**: `nine_django.adapter.urls` serves `/nine/authenticate`,
|
|
29
|
+
`/nine/user` and `/nine/event`. `DjangoUserAdapter` answers from `AUTH_USER_MODEL`:
|
|
30
|
+
case-insensitive email and username, `check_password()` with hash upgrades, inactive users
|
|
31
|
+
blocked, claims mapped with `ADAPTER_FIELDS`. `otp.requested` codes are emailed with
|
|
32
|
+
`send_mail`; SMS codes go through the `otp_requested` signal.
|
|
33
|
+
- `python manage.py nine_login_link <user>` creates single-use sign-in links.
|
|
34
|
+
- System checks for the issuer, backend, middleware order, scopes, signed-cookie sessions and
|
|
35
|
+
the cache. Settings come from `NINE_*` environment variables or a `NINE` dict.
|
|
36
|
+
- Django 4.2, 5.2, 6.0 and 6.1 on Python 3.10 to 3.14. An example project is in `examples/demo`.
|
9in_django-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cubelet Ltd [https://cubelet.co.uk]
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: 9in-django
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Django SDK for 9in: sign-in, local users, API tokens, webhooks and your own user database.
|
|
5
|
+
Project-URL: Homepage, https://9in.io
|
|
6
|
+
Project-URL: Documentation, https://9in.io/docs/
|
|
7
|
+
Project-URL: Source, https://github.com/9in-io/django
|
|
8
|
+
Project-URL: Changelog, https://github.com/9in-io/django/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/9in-io/django/issues
|
|
10
|
+
Author-email: Cubelet Ltd <hello@9in.io>
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: 9in,authentication,django,jwt,oauth2,oidc,openid-connect,single-sign-on,sso
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Environment :: Web Environment
|
|
16
|
+
Classifier: Framework :: Django
|
|
17
|
+
Classifier: Framework :: Django :: 4.2
|
|
18
|
+
Classifier: Framework :: Django :: 5.2
|
|
19
|
+
Classifier: Framework :: Django :: 6.0
|
|
20
|
+
Classifier: Framework :: Django :: 6.1
|
|
21
|
+
Classifier: Intended Audience :: Developers
|
|
22
|
+
Classifier: Operating System :: OS Independent
|
|
23
|
+
Classifier: Programming Language :: Python :: 3
|
|
24
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
26
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
27
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
28
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
29
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
30
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Session
|
|
31
|
+
Classifier: Topic :: Security
|
|
32
|
+
Classifier: Typing :: Typed
|
|
33
|
+
Requires-Python: >=3.10
|
|
34
|
+
Requires-Dist: 9in<0.2,>=0.1
|
|
35
|
+
Requires-Dist: django>=4.2
|
|
36
|
+
Provides-Extra: drf
|
|
37
|
+
Requires-Dist: djangorestframework>=3.14; extra == 'drf'
|
|
38
|
+
Description-Content-Type: text/markdown
|
|
39
|
+
|
|
40
|
+
9in Django SDK
|
|
41
|
+
==============
|
|
42
|
+
|
|
43
|
+
<img src="docs/img/logo.png" width="160" alt="9in"/>
|
|
44
|
+
|
|
45
|
+
Official Django SDK for [9in](https://9in.io): hosted login, OpenID Connect provider and SSO.
|
|
46
|
+
|
|
47
|
+
`9in-django` is built on the [9in Python SDK](https://github.com/9in-io/python-sdk) (`9in`,
|
|
48
|
+
`import nine`). It plugs sign-in, API tokens, webhooks and your own user database into Django's
|
|
49
|
+
own machinery: users, sessions, `@login_required`, the admin, signals and the cache.
|
|
50
|
+
|
|
51
|
+
- **Sign users in** at `/nine/login` with the authorization code flow, PKCE, `state`, `nonce` and
|
|
52
|
+
the `iss` check. The ID token is verified against your tenant's keys. Each 9in user signs in
|
|
53
|
+
as a **local Django user**, created or linked on first sign-in, so `request.user`,
|
|
54
|
+
`@login_required` and the admin just work.
|
|
55
|
+
- **Keep sessions in step with 9in**: a middleware refreshes the tokens before they expire
|
|
56
|
+
(rotating refresh tokens) and signs the user out here when 9in ends the session.
|
|
57
|
+
- **Protect your API** with `@require_token(scope=…)`, or with `NineTokenAuthentication` and
|
|
58
|
+
`HasScope` for Django REST framework. Access tokens are verified locally with every algorithm
|
|
59
|
+
of the key library. In **hybrid** mode revocations take effect at once, with answers cached
|
|
60
|
+
in Django's cache.
|
|
61
|
+
- **Receive webhooks** at `/nine/webhook`: verified, processed once per event and sent as
|
|
62
|
+
Django signals.
|
|
63
|
+
- **Keep users in your own database**: `/nine/authenticate`, `/nine/user` and `/nine/event` of the
|
|
64
|
+
adapter protocol, answered from your user model. One-time codes are emailed with `send_mail`.
|
|
65
|
+
- **Manage users** through the Management API, and create sign-in links with
|
|
66
|
+
`manage.py nine_login_link`.
|
|
67
|
+
|
|
68
|
+
Requires Python 3.10+ and Django 4.2, 5.2, 6.0 or 6.1 (Django 6 needs Python 3.12+).
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
pip install 9in-django # add [drf] for Django REST framework
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
| Building with | Use |
|
|
75
|
+
|---|---|
|
|
76
|
+
| Django | `9in-django` (this package) |
|
|
77
|
+
| Flask, FastAPI or plain Python | [`9in`](https://github.com/9in-io/python-sdk) |
|
|
78
|
+
| JavaScript: browsers, Node, Next.js, React | [`@9in-io/sdk`](https://github.com/9in-io/sdk), [`@9in-io/nextjs`](https://github.com/9in-io/nextjs), [`@9in-io/react`](https://github.com/9in-io/react) |
|
|
79
|
+
| PHP or Laravel | [`9in/php-sdk`](https://github.com/9in-io/php-sdk), [`9in/laravel`](https://github.com/9in-io/laravel) |
|
|
80
|
+
|
|
81
|
+
Guides are at [9in.io/docs](https://9in.io/docs/). Start with
|
|
82
|
+
[server-rendered apps](https://9in.io/docs/server-apps/) for how sign-in works.
|
|
83
|
+
|
|
84
|
+
## Set up
|
|
85
|
+
|
|
86
|
+
In the 9in console, create the application: **Applications → Create application → Regular Web
|
|
87
|
+
App**. Use the callback URL `https://your-app.com/nine/callback` and the logout URL
|
|
88
|
+
`https://your-app.com/`, and copy the client ID and secret.
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
NINE_ISSUER=https://acme.9in.io # or your custom login domain; https://acme-sandbox.9in.io to test
|
|
92
|
+
NINE_CLIENT_ID=app_…
|
|
93
|
+
NINE_CLIENT_SECRET=…
|
|
94
|
+
# NINE_AUDIENCE=https://api.acme.com # access tokens for your own API
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
# settings.py
|
|
99
|
+
INSTALLED_APPS = [
|
|
100
|
+
...,
|
|
101
|
+
"nine_django",
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
MIDDLEWARE = [
|
|
105
|
+
...,
|
|
106
|
+
"django.contrib.sessions.middleware.SessionMiddleware",
|
|
107
|
+
...,
|
|
108
|
+
"django.contrib.auth.middleware.AuthenticationMiddleware",
|
|
109
|
+
"nine_django.middleware.NineMiddleware", # after AuthenticationMiddleware
|
|
110
|
+
...,
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
AUTHENTICATION_BACKENDS = [
|
|
114
|
+
"django.contrib.auth.backends.ModelBackend", # keep it for admin passwords
|
|
115
|
+
"nine_django.backends.NineBackend",
|
|
116
|
+
]
|
|
117
|
+
|
|
118
|
+
LOGIN_URL = "nine:login" # @login_required sends users to 9in
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
# urls.py
|
|
123
|
+
from django.urls import include, path
|
|
124
|
+
|
|
125
|
+
urlpatterns = [
|
|
126
|
+
...,
|
|
127
|
+
path("nine/", include("nine_django.urls")), # /nine/login, /signup, /callback, /logout, /webhook
|
|
128
|
+
]
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
python manage.py migrate # creates the NineIdentity table
|
|
133
|
+
python manage.py check # flags common setup mistakes
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Settings come from `NINE_*` environment variables. A `NINE = {...}` dict in your settings
|
|
137
|
+
overrides them; see [Settings](#settings).
|
|
138
|
+
|
|
139
|
+
## Sign users in
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
from django.contrib.auth.decorators import login_required
|
|
143
|
+
from django.shortcuts import render
|
|
144
|
+
|
|
145
|
+
@login_required
|
|
146
|
+
def dashboard(request):
|
|
147
|
+
request.user # your Django user
|
|
148
|
+
request.nine.claims # the verified ID token: sub, email, name, amr…
|
|
149
|
+
request.nine.sub # the 9in user id (usr_…)
|
|
150
|
+
return render(request, "dashboard.html")
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
```html
|
|
154
|
+
<a href="{% url 'nine:login' %}?return_to=/dashboard">Sign in</a>
|
|
155
|
+
<a href="{% url 'nine:signup' %}">Create an account</a> <!-- opens the sign-up form -->
|
|
156
|
+
<a href="{% url 'nine:logout' %}">Sign out</a>
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
| Route | |
|
|
160
|
+
|---|---|
|
|
161
|
+
| `GET /nine/login?return_to=/path` | Starts a sign-in (`next=` works too, so `@login_required` works). `login_hint` pre-fills the identifier. |
|
|
162
|
+
| `GET /nine/signup` | The same, on the sign-up form |
|
|
163
|
+
| `GET /nine/callback` | Completes it: checks `state` (single use), `iss`, PKCE and the ID token, signs the local user in and cycles the session key |
|
|
164
|
+
| `GET` or `POST /nine/logout?return_to=/path` | Revokes the refresh token, ends the Django session, then ends the 9in session and comes back |
|
|
165
|
+
|
|
166
|
+
`return_to` must be a path on your site, so it can't be used for open redirects.
|
|
167
|
+
`/nine/logout` accepts GET so a plain link works, like in the other 9in SDKs. A `POST` from a
|
|
168
|
+
form with `{% csrf_token %}` is protected against cross-site requests; use that when another
|
|
169
|
+
site signing your users out would matter.
|
|
170
|
+
Without one, users land on `LOGIN_REDIRECT_URL` (or `/`). After sign-out they go to
|
|
171
|
+
`LOGOUT_REDIRECT_URL` (or `/`), which must be one of the application's logout URLs.
|
|
172
|
+
|
|
173
|
+
### Local users
|
|
174
|
+
|
|
175
|
+
On first sign-in, `NineBackend` links the 9in user to a Django user and records the link as a
|
|
176
|
+
`NineIdentity` (`iss` + `sub`). It tries these in order:
|
|
177
|
+
|
|
178
|
+
1. the user already linked to this 9in user;
|
|
179
|
+
2. for users of [your own database](#keep-users-in-your-own-database), the local user behind
|
|
180
|
+
the adapter id 9in keeps for them (this needs the Management API);
|
|
181
|
+
3. the one local user with the same email, only when 9in says the email is verified;
|
|
182
|
+
4. otherwise a new user with an unusable password. Their username is the verified email,
|
|
183
|
+
the 9in username or the 9in user id, whichever is free first.
|
|
184
|
+
|
|
185
|
+
Inactive users can't sign in. On every sign-in, `email`, `first_name` and `last_name` are
|
|
186
|
+
copied from the claims (`USER_FIELDS`). To change any step, subclass `NineBackend`, override
|
|
187
|
+
`find_user_to_link`, `create_user` or `update_user`, and list your class in
|
|
188
|
+
`AUTHENTICATION_BACKENDS` instead.
|
|
189
|
+
|
|
190
|
+
```python
|
|
191
|
+
from django.dispatch import receiver
|
|
192
|
+
from nine_django.signals import user_signed_in
|
|
193
|
+
|
|
194
|
+
@receiver(user_signed_in)
|
|
195
|
+
def on_sign_in(sender, request, user, claims, tokens, created, **kwargs):
|
|
196
|
+
if created:
|
|
197
|
+
Profile.objects.create(user=user, locale=claims.get("locale", "en"))
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Tokens in the session
|
|
201
|
+
|
|
202
|
+
The 9in tokens of a signed-in user are kept in the Django session. `NineMiddleware`
|
|
203
|
+
refreshes them shortly before the access token expires. 9in rotates refresh tokens, and the
|
|
204
|
+
new one replaces the old one. If 9in refuses the refresh token, the user is signed out here
|
|
205
|
+
too. That happens after signing out everywhere, when the session is revoked, or when the user
|
|
206
|
+
is blocked or deleted. If 9in can't be reached, the session stays.
|
|
207
|
+
|
|
208
|
+
```python
|
|
209
|
+
import urllib.request
|
|
210
|
+
|
|
211
|
+
token = request.nine.access_token() # refreshed when needed; None without 9in tokens
|
|
212
|
+
req = urllib.request.Request("https://api.acme.com/orders", headers={"Authorization": f"Bearer {token}"})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Use database, cache or `cached_db` sessions. Signed-cookie sessions would put the tokens in
|
|
216
|
+
the browser, and `manage.py check` warns about them. Keep `offline_access` in `SCOPES` (it is
|
|
217
|
+
there by default) to get a refresh token.
|
|
218
|
+
|
|
219
|
+
## Protect your API
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
from nine_django.decorators import require_token
|
|
223
|
+
|
|
224
|
+
@require_token(scope="orders:read")
|
|
225
|
+
def orders(request):
|
|
226
|
+
request.user # the linked Django user, or a TokenUser (sub, claims) when there is none
|
|
227
|
+
request.nine.claims # access token claims: sub, client_id, scope, aud…
|
|
228
|
+
...
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
Tokens must be issued for `NINE_API_AUDIENCE`, which defaults to `NINE_AUDIENCE`.
|
|
232
|
+
|
|
233
|
+
- A missing or invalid token gets `401 invalid_token`. A token without every scope listed
|
|
234
|
+
gets `403 insufficient_scope`. Both answers carry a `WWW-Authenticate` header.
|
|
235
|
+
- The decorator works on sync and async views. Those views are exempt from CSRF checks,
|
|
236
|
+
since the token authenticates the request, not a cookie.
|
|
237
|
+
- **Every key-library algorithm** is accepted: RS256/384/512, PS256/384/512, ES256, ES384 and
|
|
238
|
+
EdDSA through your tenant's JWKS, and HS256/384/512 with the API's shared secret in
|
|
239
|
+
`NINE_API_SECRET`.
|
|
240
|
+
- Only access tokens (`typ: at+jwt`) are accepted, signed with exactly the key's algorithm.
|
|
241
|
+
Signing keys are cached for 10 minutes, and a new key after a rotation is fetched once.
|
|
242
|
+
- `nine_django.verify_access_token(token, scope=...)` runs the same check by hand.
|
|
243
|
+
|
|
244
|
+
### Revocation: hybrid verification
|
|
245
|
+
|
|
246
|
+
With `NINE_CLIENT_ID` and `NINE_CLIENT_SECRET` set (or the `NINE_MANAGEMENT_*` pair), tokens
|
|
247
|
+
are verified in **hybrid** mode:
|
|
248
|
+
|
|
249
|
+
- each token is checked locally, then introspected once;
|
|
250
|
+
- the answer is cached in Django's cache for at most `NINE_TOKEN_CACHE_TTL` seconds
|
|
251
|
+
(default 300);
|
|
252
|
+
- when `/nine/webhook` receives `token.revoked`, `session.revoked` or a `user.*` event, it drops
|
|
253
|
+
the matching answers, so the next request is refused.
|
|
254
|
+
|
|
255
|
+
Subscribe your webhook endpoint to those events (see [Webhooks](#webhooks)). Opaque access
|
|
256
|
+
tokens (`9in_at_…`) are always introspected.
|
|
257
|
+
|
|
258
|
+
`NINE_TOKEN_VERIFICATION=local` skips introspection, so a revoked token keeps working until it
|
|
259
|
+
expires. `introspect` asks 9in on every request. Without client credentials, `local` is used.
|
|
260
|
+
If 9in can't be reached during an introspection, the API answers `503`.
|
|
261
|
+
|
|
262
|
+
### Django REST framework
|
|
263
|
+
|
|
264
|
+
```python
|
|
265
|
+
REST_FRAMEWORK = {
|
|
266
|
+
"DEFAULT_AUTHENTICATION_CLASSES": ["nine_django.rest_framework.NineTokenAuthentication"],
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
```python
|
|
271
|
+
from rest_framework.views import APIView
|
|
272
|
+
from rest_framework.response import Response
|
|
273
|
+
from nine_django.rest_framework import HasScope
|
|
274
|
+
|
|
275
|
+
class Orders(APIView):
|
|
276
|
+
permission_classes = [HasScope("orders:read")] # or [HasScope] with required_scopes = [...]
|
|
277
|
+
|
|
278
|
+
def get(self, request):
|
|
279
|
+
return Response({"sub": request.auth["sub"]}) # request.auth: the access token claims
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
`HasScope` composes with DRF's operators: `[IsAdminUser | HasScope("orders:admin")]`.
|
|
283
|
+
|
|
284
|
+
## Manage users
|
|
285
|
+
|
|
286
|
+
```python
|
|
287
|
+
from nine_django import get_management_client
|
|
288
|
+
|
|
289
|
+
management = get_management_client()
|
|
290
|
+
user = management.create_user({"email": "jane@acme.com", "email_verified": True, "name": "Jane"})
|
|
291
|
+
management.find_user_by_email("jane@acme.com")
|
|
292
|
+
management.update_user(user["id"], {"metadata": {"plan": "pro"}})
|
|
293
|
+
management.block_user(user["id"])
|
|
294
|
+
management.revoke_user_sessions(user["id"])
|
|
295
|
+
link = management.create_login_link(user["id"], return_to="https://your-app.com/nine/callback")
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
```bash
|
|
299
|
+
python manage.py nine_login_link jane@acme.com --return-to https://your-app.com/nine/callback
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
The command prints a single-use sign-in URL. `<user>` is a 9in user id, an email address, or
|
|
303
|
+
the username of a local user who has signed in with 9in.
|
|
304
|
+
|
|
305
|
+
The application needs management scopes. Set `NINE_MANAGEMENT_CLIENT_ID` and
|
|
306
|
+
`NINE_MANAGEMENT_CLIENT_SECRET` to use a separate machine-to-machine application. Field names
|
|
307
|
+
are the API's snake_case and times are ISO 8601 UTC, as everywhere in 9in.
|
|
308
|
+
`get_web_app_auth().client_credentials(audience=..., scope=...)` gets a token for your app's own
|
|
309
|
+
calls to other APIs.
|
|
310
|
+
|
|
311
|
+
## Keep users in your own database
|
|
312
|
+
|
|
313
|
+
Keep your Django users and sign them in with 9in. 9in asks your app to check passwords and
|
|
314
|
+
look users up through three signed endpoints (the adapter protocol v2).
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
urlpatterns = [
|
|
318
|
+
...,
|
|
319
|
+
path("nine/", include("nine_django.urls")),
|
|
320
|
+
path("nine/", include("nine_django.adapter.urls")), # /nine/authenticate, /nine/user, /nine/event
|
|
321
|
+
]
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
In the console, open **Connections → User database → Your server (adapter)**, enter
|
|
325
|
+
`https://your-app.com/nine`, then copy the secret:
|
|
326
|
+
|
|
327
|
+
```bash
|
|
328
|
+
NINE_ADAPTER_SECRET=…
|
|
329
|
+
# NINE_ADAPTER_SECRET_PREVIOUS=… # the old one, while you rotate it
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Requests must be signed with the secret and at most five minutes old. Responses are signed
|
|
333
|
+
over the request path and 9in's request id.
|
|
334
|
+
|
|
335
|
+
`DjangoUserAdapter` answers from `AUTH_USER_MODEL`:
|
|
336
|
+
|
|
337
|
+
- users are found by email or username, case-insensitively, or by phone when you map one;
|
|
338
|
+
- passwords are checked with `check_password()`, and Django upgrades old hashes;
|
|
339
|
+
- inactive users get `blocked`. Unknown users and wrong passwords get the same answer, in
|
|
340
|
+
about the same time.
|
|
341
|
+
|
|
342
|
+
Map more claims, or other fields, with `ADAPTER_FIELDS`. Each entry is an attribute name
|
|
343
|
+
(`__` follows relations), a callable taking the user, or `None` to leave the claim out:
|
|
344
|
+
|
|
345
|
+
```python
|
|
346
|
+
NINE = {
|
|
347
|
+
"ADAPTER_FIELDS": {
|
|
348
|
+
"phone_number": "profile__phone",
|
|
349
|
+
"email_verified": lambda user: user.emailaddress_set.filter(verified=True).exists(),
|
|
350
|
+
"metadata": lambda user: {"plan": user.profile.plan},
|
|
351
|
+
},
|
|
352
|
+
"ADAPTER_IDENTIFIERS": ["email", "username", "phone"],
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
For anything else, subclass `nine_django.adapter.DjangoUserAdapter`, or write a `nine.Adapter`,
|
|
357
|
+
and set `NINE["ADAPTER"]` to its dotted path.
|
|
358
|
+
|
|
359
|
+
**One-time codes.** 9in creates sign-in and password-reset codes and sends them to
|
|
360
|
+
`/nine/event` as `otp.requested`. Email codes are sent with `send_mail` from
|
|
361
|
+
`DEFAULT_FROM_EMAIL` (or `OTP_FROM_EMAIL`). Override the templates
|
|
362
|
+
`nine_django/otp_email_subject.txt`, `otp_email.txt` and `otp_email.html` to change the
|
|
363
|
+
message, or set `"OTP_EMAIL": False` to send codes yourself. Send SMS codes from a receiver:
|
|
364
|
+
|
|
365
|
+
```python
|
|
366
|
+
from django.dispatch import receiver
|
|
367
|
+
from nine_django.signals import otp_requested
|
|
368
|
+
|
|
369
|
+
@receiver(otp_requested)
|
|
370
|
+
def send_sms(sender, data, **kwargs):
|
|
371
|
+
if data["channel"] == "sms":
|
|
372
|
+
sms_client.send(to=data["to"], body=f"Your code is {data['code']}")
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
Adapter users exist in 9in after their first sign-in. When they sign in to your Django app
|
|
376
|
+
through `/nine/login`, `NineBackend` asks the Management API for the adapter id and signs in
|
|
377
|
+
the same Django user. Turn that off with `LINK_ADAPTER_USERS = False`.
|
|
378
|
+
|
|
379
|
+
## Webhooks
|
|
380
|
+
|
|
381
|
+
In the console, open **Advanced → Webhooks → Add endpoint** and add
|
|
382
|
+
`https://your-app.com/nine/webhook`, then set its signing secret:
|
|
383
|
+
|
|
384
|
+
```bash
|
|
385
|
+
NINE_WEBHOOK_SECRET=whsec_…
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
Each verified event is sent on its own Django signal, then on `event_received`. The signal is
|
|
389
|
+
named after the event type, with dots as underscores: `user_created`, `user_updated`,
|
|
390
|
+
`user_deleted`, `user_login`, `token_revoked`…
|
|
391
|
+
|
|
392
|
+
```python
|
|
393
|
+
from django.dispatch import receiver
|
|
394
|
+
from nine_django.signals import user_created, user_deleted
|
|
395
|
+
|
|
396
|
+
@receiver(user_created)
|
|
397
|
+
def add_contact(sender, event, data, **kwargs):
|
|
398
|
+
crm.add(data["user"]["email"]) # the 9in user: snake_case, ISO 8601 times
|
|
399
|
+
|
|
400
|
+
@receiver(user_deleted)
|
|
401
|
+
def remove_contact(sender, data, **kwargs):
|
|
402
|
+
crm.remove(data["user"]["id"])
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Receivers get `event` (`{id, event_type, created_at, tenant, environment, data}`),
|
|
406
|
+
`event_type`, `data` and `source` (`"webhook"`). The signature is checked over the raw body
|
|
407
|
+
and the path, and must be at most five minutes old. Each event is processed **once**:
|
|
408
|
+
|
|
409
|
+
- a retry or redelivery of a processed event id gets `204` without sending the signals again;
|
|
410
|
+
- a retry that arrives while the first delivery is still running gets `409`, and 9in tries
|
|
411
|
+
again later;
|
|
412
|
+
- if a receiver raises, the answer is `500`, the id is released and 9in retries.
|
|
413
|
+
|
|
414
|
+
Event ids are kept for three days in the cache named by `NINE["CACHE"]`. With several
|
|
415
|
+
processes, use a shared cache whose `add()` is atomic (Redis, Memcached, the database cache).
|
|
416
|
+
Answer quickly and queue slow work. Adapter events (`otp_requested`, `user_updated`…) use the
|
|
417
|
+
same signals with `source="adapter"`. `sender` is `nine_django.signals.Webhook` or
|
|
418
|
+
`AdapterEvent`.
|
|
419
|
+
|
|
420
|
+
## Issuers must use https
|
|
421
|
+
|
|
422
|
+
The issuer must use `https://`. Plain http is accepted for `localhost`, `*.localhost` and
|
|
423
|
+
loopback addresses only. Set `NINE_ALLOW_INSECURE_ISSUER=true` for other development hosts,
|
|
424
|
+
such as `http://auth:8897` in Docker. Issuers with a query, a fragment or credentials are
|
|
425
|
+
refused. `manage.py check` reports these errors before the first request.
|
|
426
|
+
|
|
427
|
+
## Settings
|
|
428
|
+
|
|
429
|
+
Each setting is read from `NINE["<NAME>"]`, then the `NINE_<NAME>` environment variable, then
|
|
430
|
+
the default.
|
|
431
|
+
|
|
432
|
+
| Setting | Environment | Default | |
|
|
433
|
+
|---|---|---|---|
|
|
434
|
+
| `ISSUER` | `NINE_ISSUER` | | Your tenant or login domain |
|
|
435
|
+
| `CLIENT_ID`, `CLIENT_SECRET` | `NINE_CLIENT_ID`, `NINE_CLIENT_SECRET` | | The application |
|
|
436
|
+
| `REDIRECT_URI` | `NINE_REDIRECT_URI` | this site's `/nine/callback` | Absolute, or a path on this site |
|
|
437
|
+
| `SCOPES` | | `openid profile email offline_access` | Add your API's scopes |
|
|
438
|
+
| `AUDIENCE` | `NINE_AUDIENCE` | | API to request access tokens for |
|
|
439
|
+
| `LOCALE` | | | Language of the hosted pages: a tag such as `"de"`, or `"auto"` for the active Django language |
|
|
440
|
+
| `LOGIN_REDIRECT_URL`, `LOGOUT_REDIRECT_URL` | `NINE_LOGOUT_REDIRECT_URI` | Django's, else `/` | |
|
|
441
|
+
| `CREATE_USERS`, `LINK_BY_EMAIL`, `UPDATE_USERS` | | `True` | [Local users](#local-users) |
|
|
442
|
+
| `LINK_ADAPTER_USERS` | | on with `ADAPTER_SECRET` | |
|
|
443
|
+
| `USER_FIELDS` | | email, first and last name | Model field → claim name, or callable(claims) |
|
|
444
|
+
| `API_AUDIENCE` | `NINE_API_AUDIENCE` | `AUDIENCE` | Audience of tokens on your API |
|
|
445
|
+
| `TOKEN_VERIFICATION` | `NINE_TOKEN_VERIFICATION` | hybrid with a client secret | `local`, `hybrid` or `introspect` |
|
|
446
|
+
| `API_SECRET` | `NINE_API_SECRET` | | For HS256/384/512 tokens |
|
|
447
|
+
| `TOKEN_CACHE_TTL` | `NINE_TOKEN_CACHE_TTL` | `300` | Seconds a hybrid answer is kept |
|
|
448
|
+
| `MANAGEMENT_CLIENT_ID`, `MANAGEMENT_CLIENT_SECRET` | `NINE_MANAGEMENT_CLIENT_ID`, `…_SECRET` | the application's | Management API and introspection |
|
|
449
|
+
| `WEBHOOK_SECRET`, `WEBHOOK_SECRET_PREVIOUS` | `NINE_WEBHOOK_SECRET`, `…_PREVIOUS` | | Comma-separated for several |
|
|
450
|
+
| `WEBHOOK_DEDUPE`, `WEBHOOK_DEDUPE_TTL` | | `True`, 3 days | |
|
|
451
|
+
| `WEBHOOK_PATH` | | the request path | The path 9in posts to, behind a proxy that rewrites it |
|
|
452
|
+
| `ADAPTER_SECRET`, `ADAPTER_SECRET_PREVIOUS` | `NINE_ADAPTER_SECRET`, `…_PREVIOUS` | | |
|
|
453
|
+
| `ADAPTER` | | `DjangoUserAdapter` | Dotted path of your adapter class |
|
|
454
|
+
| `ADAPTER_FIELDS`, `ADAPTER_IDENTIFIERS` | | | [Your own database](#keep-users-in-your-own-database) |
|
|
455
|
+
| `OTP_EMAIL`, `OTP_FROM_EMAIL` | | `True`, `DEFAULT_FROM_EMAIL` | |
|
|
456
|
+
| `ALLOW_INSECURE_ISSUER` | `NINE_ALLOW_INSECURE_ISSUER` | `False` | |
|
|
457
|
+
| `CACHE` | `NINE_CACHE` | `"default"` | Cache alias for keys, token answers and event ids |
|
|
458
|
+
| `HTTP_CLIENT` | | urllib, 10 s timeout | A `nine.HttpClient` or its dotted path |
|
|
459
|
+
|
|
460
|
+
The shared SDK objects are `get_web_app_auth()`, `get_token_verifier()`,
|
|
461
|
+
`get_management_client()` and `get_cache()`, all importable from `nine_django`.
|
|
462
|
+
|
|
463
|
+
## Errors
|
|
464
|
+
|
|
465
|
+
Errors from 9in are `nine.NineError` (from the Python SDK), with `.error` (the code, such as
|
|
466
|
+
`invalid_grant` or `not_found`), `.description` and `.status`. The views turn them into answers:
|
|
467
|
+
|
|
468
|
+
- a failed sign-in shows `nine_django/error.html` (override it in your templates) with status
|
|
469
|
+
400, or 403 for a user who can't sign in here;
|
|
470
|
+
- API views answer JSON `{"error", "error_description"}` with 401, 403 or 503;
|
|
471
|
+
- webhooks answer `401 invalid_signature`.
|
|
472
|
+
|
|
473
|
+
Missing settings raise `ImproperlyConfigured`. Logs go to the `nine_django` logger and never
|
|
474
|
+
contain tokens or secrets.
|
|
475
|
+
|
|
476
|
+
## Development
|
|
477
|
+
|
|
478
|
+
```bash
|
|
479
|
+
python -m venv .venv && . .venv/bin/activate
|
|
480
|
+
pip install -e . pytest pytest-django djangorestframework
|
|
481
|
+
pytest
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
Every supported Django and Python version: `uvx --with tox-uv tox`. The tests run against a
|
|
485
|
+
fake 9in tenant on a local HTTP server. Live tests against real 9in tenants are opt-in:
|
|
486
|
+
`NINE_E2E=1 NINE_E2E_ENV=/path/to/.env.e2e pytest tests/live`. A runnable example project
|
|
487
|
+
is in [examples/demo](examples/demo).
|
|
488
|
+
|
|
489
|
+
## License
|
|
490
|
+
|
|
491
|
+
The MIT License (MIT). See [LICENSE](LICENSE). 9in is by [Cubelet Ltd](https://cubelet.co.uk).
|