kik-oidc 0.2.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.
@@ -0,0 +1,239 @@
1
+ Metadata-Version: 2.4
2
+ Name: kik-oidc
3
+ Version: 0.2.0
4
+ Summary: Reusable Django OIDC authentication app using Authlib
5
+ Author: Wichert Akkerman
6
+ Author-email: Wichert Akkerman <wichert@wiggy.net>
7
+ License-Expression: EUPL-1.2
8
+ Requires-Dist: authlib>=1.9.5
9
+ Requires-Dist: django>=4.2,<5.3
10
+ Requires-Dist: kik-os[django]
11
+ Requires-Dist: requests
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+
15
+ # kik-oidc
16
+
17
+ OpenID Connect (OIDC) authentication for Kik-OS Django projects. kik-oidc
18
+ uses [Authlib](https://authlib.org/) for the authorization-code flow and
19
+ provides login, callback and logout views, user provisioning, and session
20
+ token refresh.
21
+
22
+ ## Requirements
23
+
24
+ - Python 3.12 or later
25
+ - Django 4.2 or later, before 5.3
26
+ - Kik-OS with its Django components
27
+ - An OIDC provider that supports discovery, ID tokens and UserInfo
28
+
29
+ Install the package in your Django project's environment:
30
+
31
+ ```console
32
+ uv add kik-oidc
33
+ ```
34
+
35
+ ## Django configuration
36
+
37
+ Add `kik_oidc` to `INSTALLED_APPS`. Its application config registers the
38
+ Authlib client named `oidc`.
39
+
40
+ Configure the client using your provider's issuer, client ID and client
41
+ secret. Load secrets from your deployment's secret store rather than
42
+ committing them to settings.
43
+
44
+ <!-- markdownlint-capture -->
45
+ <!-- markdownlint-disable line-length -->
46
+ ```python
47
+ import os
48
+
49
+ INSTALLED_APPS = [
50
+ # Your existing applications...
51
+ "kik_oidc",
52
+ ]
53
+
54
+ OIDC_HTTP_TIMEOUT = 10
55
+ OIDC_RP_SCOPES = "openid email profile"
56
+
57
+ AUTHLIB_OAUTH_CLIENTS = {
58
+ "oidc": {
59
+ "client_id": os.environ["OIDC_CLIENT_ID"],
60
+ "client_secret": os.environ["OIDC_CLIENT_SECRET"],
61
+ "server_metadata_url": (
62
+ os.environ["OIDC_ISSUER"].rstrip("/")
63
+ + "/.well-known/openid-configuration"
64
+ ),
65
+ "client_kwargs": {
66
+ "scope": OIDC_RP_SCOPES,
67
+ "default_timeout": OIDC_HTTP_TIMEOUT,
68
+ },
69
+ },
70
+ }
71
+
72
+ AUTHENTICATION_BACKENDS = [
73
+ "kik_oidc.auth.SsoAuthenticationBackend",
74
+ # Optional: retain local authentication for administrators.
75
+ "django.contrib.auth.backends.ModelBackend",
76
+ ]
77
+
78
+ MIDDLEWARE.insert(
79
+ MIDDLEWARE.index(
80
+ "django.contrib.auth.middleware.AuthenticationMiddleware"
81
+ ) + 1,
82
+ "kik_oidc.middleware.OidcSessionMiddleware",
83
+ )
84
+
85
+ LOGIN_URL = "/oidc/login"
86
+ LOGIN_REDIRECT_URL = "/"
87
+
88
+ # A stable, secret key used to encrypt OIDC tokens in the database.
89
+ KIK_OS_SECRET_KEY = os.environ["KIK_OS_SECRET_KEY"]
90
+ ```
91
+ <!-- markdownlint-restore -->
92
+
93
+ `OidcSessionMiddleware` must come after `AuthenticationMiddleware`. Do not
94
+ remove `SessionMiddleware` or Django's session authentication machinery:
95
+ OIDC credentials are tied to Django sessions.
96
+
97
+ To enable PKCE with S256, add the following to `client_kwargs`:
98
+
99
+ ```python
100
+ "code_challenge_method": "S256",
101
+ ```
102
+
103
+ Use PKCE only when your provider supports it.
104
+
105
+ ### URLs
106
+
107
+ Include the OIDC URLs and use the package's logout view. The following
108
+ example keeps local login and logout available when OIDC is disabled:
109
+
110
+ ```python
111
+ from django.conf import settings
112
+ from django.contrib.auth import views as auth_views
113
+ from django.urls import include, path
114
+
115
+ from kik_oidc.views import logout
116
+
117
+ urlpatterns = [
118
+ path("login/", auth_views.LoginView.as_view(), name="login"),
119
+ path("logout/", logout, name="logout"),
120
+ path("oidc/", include("kik_oidc.urls")),
121
+ # Your existing URLs...
122
+ ]
123
+ ```
124
+
125
+ When OIDC is the only authentication method, use
126
+ `kik_oidc.views.login` for `/login/` as well, or set `LOGIN_URL` to
127
+ `/oidc/login` as shown above. Mounting the URLs at `/oidc/` provides:
128
+
129
+ | URL | Purpose |
130
+ | --- | --- |
131
+ | `/oidc/login` | Start the authorization-code flow |
132
+ | `/oidc/callback` | Handle the provider callback |
133
+ | `/oidc/logged-out` | Local post-logout page |
134
+
135
+ Register these callback URLs with the provider, using the public origin of
136
+ your application:
137
+
138
+ ```text
139
+ https://app.example.org/oidc/callback
140
+ https://app.example.org/oidc/logged-out
141
+ ```
142
+
143
+ The callback URI is generated with `request.build_absolute_uri()`. Configure
144
+ Django's host and proxy settings correctly when running behind a reverse
145
+ proxy, including `ALLOWED_HOSTS`, `SECURE_PROXY_SSL_HEADER` and HTTPS
146
+ redirects as appropriate.
147
+
148
+ Log out with a POST request, for example:
149
+
150
+ ```html
151
+ <form method="post" action="{% url 'logout' %}">
152
+ {% csrf_token %}
153
+ <button type="submit">Sign out</button>
154
+ </form>
155
+ ```
156
+
157
+ GET requests to the OIDC logout view are rejected. If the provider supports
158
+ end-session, logout includes an `id_token_hint` and a post-logout redirect.
159
+
160
+ ## Provider claims
161
+
162
+ The requested scopes must produce a verified ID token containing `iss` and
163
+ `sub`, and a UserInfo response whose `sub` matches the ID token. The
164
+ `organization` claim is required in UserInfo.
165
+
166
+ The standard `openid email profile` scopes normally provide the identity
167
+ claims below. Configure your provider to add `organization` as a custom
168
+ UserInfo claim; it is not supplied by all providers by default.
169
+
170
+ | Claim | Use |
171
+ | --- | --- |
172
+ | `iss`, `sub` | Stable OIDC identity |
173
+ | `organization` | Kik-OS hub slug |
174
+ | `email` | User email address |
175
+ | `given_name`, `family_name` | User first and last name |
176
+ | `name` | SSO profile full name |
177
+
178
+ A user is identified by the unique `(iss, sub)` pair, not by username or
179
+ email address. New users receive an unusable password and a deterministic
180
+ OIDC username derived from the issuer and subject. Returning users have
181
+ non-empty changed profile claims updated.
182
+
183
+ ## Hubs and memberships
184
+
185
+ `organization` must be a valid lowercase hub slug. The user must be active,
186
+ the hub must be active, and the user must be an accepted member.
187
+
188
+ With Kik-OS schema tenancy (`KIK_TENANCY = "schemas"`), a missing valid hub
189
+ is created and provisioned, and the user receives an ordinary accepted
190
+ membership. Existing membership roles and states are preserved. Ambiguous
191
+ schema names and reserved slugs are rejected.
192
+
193
+ With single-hub tenancy (`KIK_TENANCY = "single"`), the hub must already
194
+ exist. An unknown organization is rejected rather than creating a hub.
195
+
196
+ Do not use the first OIDC login as the only way to grant administrative
197
+ access: newly provisioned users receive ordinary memberships.
198
+
199
+ ## Sessions and token storage
200
+
201
+ The session middleware checks OIDC credentials on authenticated requests
202
+ and refreshes tokens shortly before access-token expiry. Refresh and ID
203
+ tokens are encrypted in the database; access tokens are not persisted.
204
+ Sessions still expire at their normal Django expiry, even if the provider
205
+ allows longer-lived refresh tokens.
206
+
207
+ Keep `KIK_OS_SECRET_KEY` stable and secret. Losing all configured decryption
208
+ keys makes stored tokens unusable. A project can instead set
209
+ `KIK_OS_SECRET_BOX` to a dotted path for a Kik-OS-compatible encryption
210
+ module.
211
+
212
+ Paths beginning with `/oidc/` or `/logout/` are excluded from session
213
+ refresh checks by default. Set `OIDC_PUBLIC_PATHS` to override this tuple.
214
+ If your Kik-OS project uses sign-in gating or schema-aware hub middleware,
215
+ also allow the OIDC endpoints through those layers, for example:
216
+
217
+ ```python
218
+ KIK_EXTRA_OPEN_PATHS = ("/oidc",)
219
+ KIK_CENTRAL_PATHS = ("/oidc/", "/logout/")
220
+ ```
221
+
222
+ Use a scheduled call to `kik_oidc.sessions.cleanup()` if you want to remove
223
+ credentials associated with expired Django sessions.
224
+
225
+ ## Development
226
+
227
+ Run the test suite and linter with:
228
+
229
+ ```console
230
+ uv run --frozen pytest
231
+ uv run ruff check tests
232
+ ```
233
+
234
+ The test suite uses SQLite and mocked provider responses; no external OIDC
235
+ provider is needed.
236
+
237
+ Releases are managed with Release Please. Merging its release pull request
238
+ creates a GitHub release and publishes the package to PyPI through trusted
239
+ publishing.
@@ -0,0 +1,225 @@
1
+ # kik-oidc
2
+
3
+ OpenID Connect (OIDC) authentication for Kik-OS Django projects. kik-oidc
4
+ uses [Authlib](https://authlib.org/) for the authorization-code flow and
5
+ provides login, callback and logout views, user provisioning, and session
6
+ token refresh.
7
+
8
+ ## Requirements
9
+
10
+ - Python 3.12 or later
11
+ - Django 4.2 or later, before 5.3
12
+ - Kik-OS with its Django components
13
+ - An OIDC provider that supports discovery, ID tokens and UserInfo
14
+
15
+ Install the package in your Django project's environment:
16
+
17
+ ```console
18
+ uv add kik-oidc
19
+ ```
20
+
21
+ ## Django configuration
22
+
23
+ Add `kik_oidc` to `INSTALLED_APPS`. Its application config registers the
24
+ Authlib client named `oidc`.
25
+
26
+ Configure the client using your provider's issuer, client ID and client
27
+ secret. Load secrets from your deployment's secret store rather than
28
+ committing them to settings.
29
+
30
+ <!-- markdownlint-capture -->
31
+ <!-- markdownlint-disable line-length -->
32
+ ```python
33
+ import os
34
+
35
+ INSTALLED_APPS = [
36
+ # Your existing applications...
37
+ "kik_oidc",
38
+ ]
39
+
40
+ OIDC_HTTP_TIMEOUT = 10
41
+ OIDC_RP_SCOPES = "openid email profile"
42
+
43
+ AUTHLIB_OAUTH_CLIENTS = {
44
+ "oidc": {
45
+ "client_id": os.environ["OIDC_CLIENT_ID"],
46
+ "client_secret": os.environ["OIDC_CLIENT_SECRET"],
47
+ "server_metadata_url": (
48
+ os.environ["OIDC_ISSUER"].rstrip("/")
49
+ + "/.well-known/openid-configuration"
50
+ ),
51
+ "client_kwargs": {
52
+ "scope": OIDC_RP_SCOPES,
53
+ "default_timeout": OIDC_HTTP_TIMEOUT,
54
+ },
55
+ },
56
+ }
57
+
58
+ AUTHENTICATION_BACKENDS = [
59
+ "kik_oidc.auth.SsoAuthenticationBackend",
60
+ # Optional: retain local authentication for administrators.
61
+ "django.contrib.auth.backends.ModelBackend",
62
+ ]
63
+
64
+ MIDDLEWARE.insert(
65
+ MIDDLEWARE.index(
66
+ "django.contrib.auth.middleware.AuthenticationMiddleware"
67
+ ) + 1,
68
+ "kik_oidc.middleware.OidcSessionMiddleware",
69
+ )
70
+
71
+ LOGIN_URL = "/oidc/login"
72
+ LOGIN_REDIRECT_URL = "/"
73
+
74
+ # A stable, secret key used to encrypt OIDC tokens in the database.
75
+ KIK_OS_SECRET_KEY = os.environ["KIK_OS_SECRET_KEY"]
76
+ ```
77
+ <!-- markdownlint-restore -->
78
+
79
+ `OidcSessionMiddleware` must come after `AuthenticationMiddleware`. Do not
80
+ remove `SessionMiddleware` or Django's session authentication machinery:
81
+ OIDC credentials are tied to Django sessions.
82
+
83
+ To enable PKCE with S256, add the following to `client_kwargs`:
84
+
85
+ ```python
86
+ "code_challenge_method": "S256",
87
+ ```
88
+
89
+ Use PKCE only when your provider supports it.
90
+
91
+ ### URLs
92
+
93
+ Include the OIDC URLs and use the package's logout view. The following
94
+ example keeps local login and logout available when OIDC is disabled:
95
+
96
+ ```python
97
+ from django.conf import settings
98
+ from django.contrib.auth import views as auth_views
99
+ from django.urls import include, path
100
+
101
+ from kik_oidc.views import logout
102
+
103
+ urlpatterns = [
104
+ path("login/", auth_views.LoginView.as_view(), name="login"),
105
+ path("logout/", logout, name="logout"),
106
+ path("oidc/", include("kik_oidc.urls")),
107
+ # Your existing URLs...
108
+ ]
109
+ ```
110
+
111
+ When OIDC is the only authentication method, use
112
+ `kik_oidc.views.login` for `/login/` as well, or set `LOGIN_URL` to
113
+ `/oidc/login` as shown above. Mounting the URLs at `/oidc/` provides:
114
+
115
+ | URL | Purpose |
116
+ | --- | --- |
117
+ | `/oidc/login` | Start the authorization-code flow |
118
+ | `/oidc/callback` | Handle the provider callback |
119
+ | `/oidc/logged-out` | Local post-logout page |
120
+
121
+ Register these callback URLs with the provider, using the public origin of
122
+ your application:
123
+
124
+ ```text
125
+ https://app.example.org/oidc/callback
126
+ https://app.example.org/oidc/logged-out
127
+ ```
128
+
129
+ The callback URI is generated with `request.build_absolute_uri()`. Configure
130
+ Django's host and proxy settings correctly when running behind a reverse
131
+ proxy, including `ALLOWED_HOSTS`, `SECURE_PROXY_SSL_HEADER` and HTTPS
132
+ redirects as appropriate.
133
+
134
+ Log out with a POST request, for example:
135
+
136
+ ```html
137
+ <form method="post" action="{% url 'logout' %}">
138
+ {% csrf_token %}
139
+ <button type="submit">Sign out</button>
140
+ </form>
141
+ ```
142
+
143
+ GET requests to the OIDC logout view are rejected. If the provider supports
144
+ end-session, logout includes an `id_token_hint` and a post-logout redirect.
145
+
146
+ ## Provider claims
147
+
148
+ The requested scopes must produce a verified ID token containing `iss` and
149
+ `sub`, and a UserInfo response whose `sub` matches the ID token. The
150
+ `organization` claim is required in UserInfo.
151
+
152
+ The standard `openid email profile` scopes normally provide the identity
153
+ claims below. Configure your provider to add `organization` as a custom
154
+ UserInfo claim; it is not supplied by all providers by default.
155
+
156
+ | Claim | Use |
157
+ | --- | --- |
158
+ | `iss`, `sub` | Stable OIDC identity |
159
+ | `organization` | Kik-OS hub slug |
160
+ | `email` | User email address |
161
+ | `given_name`, `family_name` | User first and last name |
162
+ | `name` | SSO profile full name |
163
+
164
+ A user is identified by the unique `(iss, sub)` pair, not by username or
165
+ email address. New users receive an unusable password and a deterministic
166
+ OIDC username derived from the issuer and subject. Returning users have
167
+ non-empty changed profile claims updated.
168
+
169
+ ## Hubs and memberships
170
+
171
+ `organization` must be a valid lowercase hub slug. The user must be active,
172
+ the hub must be active, and the user must be an accepted member.
173
+
174
+ With Kik-OS schema tenancy (`KIK_TENANCY = "schemas"`), a missing valid hub
175
+ is created and provisioned, and the user receives an ordinary accepted
176
+ membership. Existing membership roles and states are preserved. Ambiguous
177
+ schema names and reserved slugs are rejected.
178
+
179
+ With single-hub tenancy (`KIK_TENANCY = "single"`), the hub must already
180
+ exist. An unknown organization is rejected rather than creating a hub.
181
+
182
+ Do not use the first OIDC login as the only way to grant administrative
183
+ access: newly provisioned users receive ordinary memberships.
184
+
185
+ ## Sessions and token storage
186
+
187
+ The session middleware checks OIDC credentials on authenticated requests
188
+ and refreshes tokens shortly before access-token expiry. Refresh and ID
189
+ tokens are encrypted in the database; access tokens are not persisted.
190
+ Sessions still expire at their normal Django expiry, even if the provider
191
+ allows longer-lived refresh tokens.
192
+
193
+ Keep `KIK_OS_SECRET_KEY` stable and secret. Losing all configured decryption
194
+ keys makes stored tokens unusable. A project can instead set
195
+ `KIK_OS_SECRET_BOX` to a dotted path for a Kik-OS-compatible encryption
196
+ module.
197
+
198
+ Paths beginning with `/oidc/` or `/logout/` are excluded from session
199
+ refresh checks by default. Set `OIDC_PUBLIC_PATHS` to override this tuple.
200
+ If your Kik-OS project uses sign-in gating or schema-aware hub middleware,
201
+ also allow the OIDC endpoints through those layers, for example:
202
+
203
+ ```python
204
+ KIK_EXTRA_OPEN_PATHS = ("/oidc",)
205
+ KIK_CENTRAL_PATHS = ("/oidc/", "/logout/")
206
+ ```
207
+
208
+ Use a scheduled call to `kik_oidc.sessions.cleanup()` if you want to remove
209
+ credentials associated with expired Django sessions.
210
+
211
+ ## Development
212
+
213
+ Run the test suite and linter with:
214
+
215
+ ```console
216
+ uv run --frozen pytest
217
+ uv run ruff check tests
218
+ ```
219
+
220
+ The test suite uses SQLite and mocked provider responses; no external OIDC
221
+ provider is needed.
222
+
223
+ Releases are managed with Release Please. Merging its release pull request
224
+ creates a GitHub release and publishes the package to PyPI through trusted
225
+ publishing.
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "kik-oidc"
3
+ version = "0.2.0"
4
+ description = "Reusable Django OIDC authentication app using Authlib"
5
+ license = "EUPL-1.2"
6
+ readme = "README.md"
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "authlib>=1.9.5",
10
+ "Django>=4.2,<5.3",
11
+ "kik-os[django]",
12
+ "requests",
13
+ ]
14
+
15
+ [[project.authors]]
16
+ name = "Wichert Akkerman"
17
+ email = "wichert@wiggy.net"
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "pytest-django",
22
+ "pytest-mock",
23
+ "psycopg[binary]>=3.1",
24
+ ]
25
+
26
+ [tool.pytest.ini_options]
27
+ DJANGO_SETTINGS_MODULE = "tests.settings"
28
+ pythonpath = ["."]
29
+ python_files = [
30
+ "tests.py",
31
+ "test_*.py",
32
+ "*_tests.py",
33
+ ]
34
+ testpaths = ["tests"]
35
+
36
+ [tool.uv]
37
+ exclude-newer = "7 days"
38
+
39
+ [tool.uv.sources.kik-os]
40
+ git = "https://github.com/cornae/kik-os.git"
41
+ rev = "546df816f864b12e35682c72e599cc279cd87aba"
42
+
43
+ [build-system]
44
+ requires = ["uv_build>=0.13.10,<0.14.0"]
45
+ build-backend = "uv_build"
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "kik-oidc"
3
+ version = "0.2.0"
4
+ description = "Reusable Django OIDC authentication app using Authlib"
5
+ license = "EUPL-1.2"
6
+ readme = "README.md"
7
+ authors = [{ name = "Wichert Akkerman", email = "wichert@wiggy.net" }]
8
+ requires-python = ">=3.12"
9
+ dependencies = [
10
+ "authlib>=1.9.5",
11
+ "Django>=4.2,<5.3",
12
+ "kik-os[django]",
13
+ "requests",
14
+ ]
15
+
16
+ [dependency-groups]
17
+ dev = [
18
+ "pytest-django",
19
+ "pytest-mock",
20
+ "psycopg[binary]>=3.1",
21
+ ]
22
+
23
+ [tool.pytest.ini_options]
24
+ DJANGO_SETTINGS_MODULE = "tests.settings"
25
+ pythonpath = ["."]
26
+ python_files = ["tests.py", "test_*.py", "*_tests.py"]
27
+ testpaths = ["tests"]
28
+
29
+ [tool.uv.sources]
30
+ kik-os = { git = "https://github.com/cornae/kik-os.git", rev = "546df816f864b12e35682c72e599cc279cd87aba" }
31
+
32
+ [tool.uv]
33
+ exclude-newer = "7 days"
34
+
35
+ [build-system]
36
+ requires = ["uv_build>=0.13.10,<0.14.0"]
37
+ build-backend = "uv_build"
@@ -0,0 +1,3 @@
1
+ from authlib.integrations.django_client import OAuth
2
+
3
+ oauth = OAuth()
@@ -0,0 +1 @@
1
+ # Register your models here.
@@ -0,0 +1,13 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class KikOidcConfig(AppConfig):
5
+ name = "kik_oidc"
6
+ verbose_name = "Kik-OS OIDC support"
7
+
8
+ def ready(self):
9
+ # Authlib's Django integration only reads AUTHLIB_OAUTH_CLIENTS when a
10
+ # client is created, so the name has to be registered explicitly.
11
+ from kik_oidc import oauth
12
+
13
+ oauth.register("oidc")
@@ -0,0 +1,79 @@
1
+ import hashlib
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.db import models, transaction
5
+
6
+ from kik_oidc.hubs import ensure_hub
7
+ from kik_oidc.models import SsoProfile
8
+
9
+ User = get_user_model()
10
+
11
+
12
+ def _username(claims):
13
+ digest = hashlib.md5(
14
+ f"{claims['iss']}\0{claims['sub']}".encode(), usedforsecurity=False
15
+ ).hexdigest()
16
+ return f"oidc-{digest}"
17
+
18
+
19
+ def update_from_claims(
20
+ obj: models.Model, claims: dict[str, str], field_list: list[tuple[str, str]]
21
+ ):
22
+ changed = []
23
+ for claim, field in field_list:
24
+ v = claims.get(claim)
25
+ if v and getattr(obj, field) != v:
26
+ setattr(obj, field, v)
27
+ changed.append(field)
28
+ if changed:
29
+ obj.save(update_fields=changed)
30
+
31
+
32
+ class SsoAuthenticationBackend:
33
+ @transaction.atomic
34
+ def authenticate(self, request, claims=None):
35
+ if (
36
+ not claims
37
+ or not isinstance(claims.get("iss"), str)
38
+ or not claims["iss"]
39
+ or not isinstance(claims.get("sub"), str)
40
+ or not claims["sub"]
41
+ ):
42
+ return None
43
+ iss, sub = claims["iss"], claims["sub"]
44
+ with transaction.atomic():
45
+ profile = (
46
+ SsoProfile.objects.select_related("user")
47
+ .filter(iss=iss, sub=sub)
48
+ .first()
49
+ )
50
+ if profile is not None:
51
+ user = profile.user
52
+ if not user.is_active:
53
+ return None
54
+ update_from_claims(
55
+ user,
56
+ claims,
57
+ [
58
+ ("email", "email"),
59
+ ("given_name", "first_name"),
60
+ ("family_name", "last_name"),
61
+ ],
62
+ )
63
+ update_from_claims(profile, claims, [("name", "fullname")])
64
+ else:
65
+ user = User(
66
+ username=_username(claims),
67
+ email=claims.get("email") or "",
68
+ first_name=claims.get("given_name") or "",
69
+ last_name=claims.get("family_name") or "",
70
+ )
71
+ user.set_unusable_password()
72
+ user.save()
73
+ SsoProfile.objects.create(
74
+ user=user, iss=iss, sub=sub, fullname=claims.get("name") or ""
75
+ )
76
+ return user if ensure_hub(user, claims.get("organization")) else None
77
+
78
+ def get_user(self, user_id):
79
+ return User.objects.filter(pk=user_id).first()
@@ -0,0 +1,72 @@
1
+ import re
2
+ import threading
3
+
4
+ from django.db import transaction
5
+ from django.utils.text import slugify
6
+ from kik_os import people, tenancy
7
+ from kik_os.project import hubs as project_hubs
8
+
9
+ _locks = {}
10
+ _locks_guard = threading.Lock()
11
+ _valid_slug = re.compile(r"[a-z0-9][a-z0-9-]*\Z")
12
+
13
+
14
+ def _valid(organization):
15
+ if not isinstance(organization, str) or not organization or len(organization) > 100:
16
+ return False
17
+ if organization != slugify(organization) or not _valid_slug.fullmatch(organization):
18
+ return False
19
+ if organization in project_hubs.RESERVED or organization == "oidc":
20
+ return False
21
+ if not project_hubs.enabled():
22
+ return True
23
+ schema = tenancy.db_name(organization)
24
+ if len(schema.encode()) > 63:
25
+ return False
26
+ # org_ uses '-' and '_' interchangeably: reject an ambiguous assignment
27
+ # rather than putting two organizations' data in one schema.
28
+ hub_model = people.hub_model()
29
+ for slug in hub_model.objects.exclude(slug=organization).values_list("slug", flat=True):
30
+ if tenancy.db_name(slug) == schema:
31
+ return False
32
+ return True
33
+
34
+
35
+ def _hub_lock(hub):
36
+ with _locks_guard:
37
+ return _locks.setdefault(hub.pk, threading.Lock())
38
+
39
+
40
+ def ensure_hub(user, organization):
41
+ if not user.is_active or not _valid(organization):
42
+ return False
43
+ hub_model = people.hub_model()
44
+ membership_model = people.membership_model()
45
+ with transaction.atomic():
46
+ if project_hubs.enabled():
47
+ hub, _ = hub_model.objects.get_or_create(
48
+ slug=organization,
49
+ defaults={"name": organization.capitalize()},
50
+ )
51
+ else:
52
+ hub = hub_model.objects.filter(slug=organization).first()
53
+ if hub is None or not hub.is_active:
54
+ return False
55
+ membership_model.objects.get_or_create(
56
+ user=user,
57
+ defaults={
58
+ "role": membership_model.ROLE_MEMBER,
59
+ "state": membership_model.STATE_ACCEPTED,
60
+ },
61
+ **{membership_model.HUB_FIELD: hub},
62
+ )
63
+ if not people.is_member(user, hub):
64
+ return False
65
+ if project_hubs.enabled() and tenancy.db_for(hub.slug, load=False) is None:
66
+ # Schema setup must not hold the central transaction open. Lock per hub
67
+ # in this process; concurrent first logins may use their DB advisory
68
+ # locks too if the installation runs multiple workers.
69
+ with _hub_lock(hub):
70
+ if tenancy.db_for(hub.slug, load=False) is None:
71
+ project_hubs.provision(hub)
72
+ return True
@@ -0,0 +1,6 @@
1
+ {% extends "layout.html" %}
2
+ {% block content %}
3
+ <form action="{{ url('login') }}" method="post">
4
+ <button type="" submit">Login</button>
5
+ </form>
6
+ {% endblock %}
@@ -0,0 +1,17 @@
1
+ from django.conf import settings
2
+
3
+ from kik_oidc.sessions import check_session
4
+
5
+
6
+ class OidcSessionMiddleware:
7
+ def __init__(self, get_response):
8
+ self.get_response = get_response
9
+
10
+ def __call__(self, request):
11
+ if request.user.is_authenticated and not request.path_info.startswith(
12
+ tuple(getattr(settings, "OIDC_PUBLIC_PATHS", ("/oidc/", "/logout/")))
13
+ ):
14
+ response = check_session(request)
15
+ if response is not None:
16
+ return response
17
+ return self.get_response(request)
@@ -0,0 +1,47 @@
1
+ # Generated by Django 5.2.19 on 2026-11-28 11:26
2
+
3
+ from typing import ClassVar
4
+
5
+ import django.db.models.deletion
6
+ import django.utils.timezone
7
+ from django.conf import settings
8
+ from django.db import migrations, models
9
+
10
+
11
+ class Migration(migrations.Migration):
12
+
13
+ initial = True
14
+
15
+ dependencies: ClassVar[list] = [
16
+ ('sessions', '0001_initial'),
17
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
18
+ ]
19
+
20
+ operations: ClassVar[list] = [
21
+ migrations.CreateModel(
22
+ name='SsoProfile',
23
+ fields=[
24
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
25
+ ('sub', models.CharField(unique=True)),
26
+ ('fullname', models.CharField(blank=True, default='')),
27
+ ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
28
+ ],
29
+ ),
30
+ migrations.CreateModel(
31
+ name='OidcCredential',
32
+ fields=[
33
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
34
+ ('refresh_token', models.TextField(blank=True, default='')),
35
+ ('id_token', models.TextField(blank=True, default='')),
36
+ ('expires_at', models.DateTimeField()),
37
+ ('refreshed_at', models.DateTimeField(default=django.utils.timezone.now)),
38
+ ('hard_deadline', models.DateTimeField()),
39
+ ('refresh_deadline', models.DateTimeField(blank=True, null=True)),
40
+ ('session', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='oidc_credential', to='sessions.session')),
41
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
42
+ ],
43
+ options={
44
+ 'indexes': [models.Index(fields=['expires_at'], name='kik_oidc_oi_expires_dfe740_idx')],
45
+ },
46
+ ),
47
+ ]
@@ -0,0 +1,23 @@
1
+ from typing import ClassVar
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ def reject_legacy_profiles(apps, schema_editor):
7
+ profiles = apps.get_model("kik_oidc", "SsoProfile").objects.using(schema_editor.connection.alias)
8
+ if profiles.exists():
9
+ raise RuntimeError("Cannot migrate existing SSO profiles: their OIDC issuers are unknown.")
10
+
11
+
12
+ class Migration(migrations.Migration):
13
+ dependencies: ClassVar[list] = [("kik_oidc", "0001_initial")]
14
+
15
+ operations: ClassVar[list] = [
16
+ migrations.RunPython(reject_legacy_profiles, migrations.RunPython.noop),
17
+ migrations.AddField(model_name="ssoprofile", name="iss", field=models.CharField()),
18
+ migrations.AlterField(model_name="ssoprofile", name="sub", field=models.CharField()),
19
+ migrations.AddConstraint(
20
+ model_name="ssoprofile",
21
+ constraint=models.UniqueConstraint(fields=["iss", "sub"], name="kik_oidc_unique_iss_sub"),
22
+ ),
23
+ ]
File without changes
@@ -0,0 +1,49 @@
1
+ from typing import ClassVar
2
+
3
+ from django.conf import settings
4
+ from django.contrib.auth.models import User
5
+ from django.db import models
6
+ from django.utils import timezone
7
+
8
+
9
+ class SsoProfile(models.Model):
10
+ user = models.OneToOneField(User, on_delete=models.CASCADE)
11
+ iss = models.CharField()
12
+ sub = models.CharField()
13
+ fullname = models.CharField(blank=True, default="")
14
+
15
+ class Meta:
16
+ constraints: ClassVar[list[models.BaseConstraint]] = [models.UniqueConstraint(fields=["iss", "sub"], name="kik_oidc_unique_iss_sub")]
17
+
18
+
19
+ class OidcCredential(models.Model):
20
+ session = models.OneToOneField(
21
+ "sessions.Session", on_delete=models.CASCADE, related_name="oidc_credential"
22
+ )
23
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
24
+ refresh_token = models.TextField(blank=True, default="")
25
+ id_token = models.TextField(blank=True, default="")
26
+ expires_at = models.DateTimeField()
27
+ refreshed_at = models.DateTimeField(default=timezone.now)
28
+ hard_deadline = models.DateTimeField()
29
+ refresh_deadline = models.DateTimeField(null=True, blank=True)
30
+
31
+ class Meta:
32
+ indexes: ClassVar[list[models.Index]] = [models.Index(fields=["expires_at"])]
33
+
34
+ def decrypted(self, name):
35
+ from kik_os.secret_box import box
36
+
37
+ value = box().decrypt(getattr(self, name))
38
+ if not value and getattr(self, name):
39
+ raise ValueError(f"Could not decrypt OIDC {name.replace('_', ' ')}.")
40
+ return value
41
+
42
+ def set_tokens(self, *, refresh_token=None, id_token=None):
43
+ from kik_os.secret_box import box
44
+
45
+ encrypt = box().encrypt
46
+ if refresh_token is not None:
47
+ self.refresh_token = encrypt(refresh_token)
48
+ if id_token is not None:
49
+ self.id_token = encrypt(id_token)
File without changes
@@ -0,0 +1,159 @@
1
+ from datetime import UTC, datetime, timedelta
2
+
3
+ import requests
4
+ from authlib.integrations.base_client import OAuthError
5
+ from django.contrib.auth import logout as django_logout
6
+ from django.contrib.sessions.models import Session
7
+ from django.db import transaction
8
+ from django.utils import timezone
9
+
10
+ from kik_oidc.models import OidcCredential
11
+ from kik_oidc.tokens import OIDC_REQUEST_KEY
12
+
13
+
14
+ def _timestamp(value):
15
+ if value is None:
16
+ return None
17
+ return timezone.datetime.fromtimestamp(float(value), tz=UTC)
18
+
19
+
20
+ def bind_credentials(request, user, token):
21
+ expires_at = _timestamp(token.get("expires_at"))
22
+ if expires_at is None and token.get("expires_in") is not None:
23
+ expires_at = timezone.now() + timedelta(seconds=float(token["expires_in"]))
24
+ if expires_at is None:
25
+ raise ValueError("OIDC token response has no access-token expiry.")
26
+ hard_deadline = min(
27
+ datetime.max.replace(tzinfo=UTC) if token.get("refresh_token") else expires_at,
28
+ request.session.get_expiry_date(),
29
+ )
30
+ credential = OidcCredential(
31
+ session_id=request.session.session_key,
32
+ user=user,
33
+ expires_at=expires_at,
34
+ hard_deadline=hard_deadline,
35
+ refresh_deadline=_timestamp(token.get("refresh_expires_at")),
36
+ )
37
+ if (
38
+ credential.refresh_deadline is None
39
+ and token.get("refresh_expires_in") is not None
40
+ ):
41
+ credential.refresh_deadline = timezone.now() + timedelta(
42
+ seconds=float(token["refresh_expires_in"])
43
+ )
44
+ credential.set_tokens(
45
+ refresh_token=token.get("refresh_token") or "",
46
+ id_token=token.get("id_token") or "",
47
+ )
48
+ credential.save()
49
+ request.session[OIDC_REQUEST_KEY] = True
50
+ request.session.save()
51
+
52
+
53
+ def _definitive_error(error):
54
+ if isinstance(error, OAuthError):
55
+ return True
56
+ if isinstance(error, requests.RequestException) and error.response is not None:
57
+ return 400 <= error.response.status_code < 500
58
+ return False
59
+
60
+
61
+ def check_session(request):
62
+ if not request.user.is_authenticated:
63
+ return
64
+ credential = OidcCredential.objects.filter(
65
+ session_id=request.session.session_key
66
+ ).first()
67
+ if credential is None:
68
+ if request.session.get(OIDC_REQUEST_KEY):
69
+ django_logout(request)
70
+ return
71
+ now = timezone.now()
72
+ if now >= credential.hard_deadline or (
73
+ credential.refresh_deadline is not None and now >= credential.refresh_deadline
74
+ ):
75
+ django_logout(request)
76
+ credential.delete()
77
+ return
78
+ if now < credential.expires_at - timedelta(seconds=60):
79
+ return
80
+ if not credential.refresh_token:
81
+ if now >= credential.expires_at:
82
+ django_logout(request)
83
+ credential.delete()
84
+ return
85
+ return _refresh(request, credential, now)
86
+
87
+
88
+ def _refresh(request, credential, now):
89
+ from kik_oidc import oauth
90
+ from kik_oidc.tokens import refresh
91
+
92
+ try:
93
+ with transaction.atomic():
94
+ credential = OidcCredential.objects.select_for_update().get(
95
+ pk=credential.pk, session_id=request.session.session_key
96
+ )
97
+ if now < credential.expires_at - timedelta(seconds=60):
98
+ return
99
+ token = refresh(oauth.oidc, credential)
100
+ credential.expires_at = _timestamp(token.get("expires_at"))
101
+ if credential.expires_at is None:
102
+ credential.expires_at = now + timedelta(
103
+ seconds=float(token["expires_in"])
104
+ )
105
+ credential.refreshed_at = timezone.now()
106
+ if token.get("refresh_token"):
107
+ credential.set_tokens(refresh_token=token["refresh_token"])
108
+ if token.get("refresh_expires_at") is not None:
109
+ credential.refresh_deadline = _timestamp(token["refresh_expires_at"])
110
+ elif token.get("refresh_expires_in") is not None:
111
+ credential.refresh_deadline = timezone.now() + timedelta(
112
+ seconds=float(token["refresh_expires_in"])
113
+ )
114
+ # Keep the already validated ID token: a refresh response's token
115
+ # has not passed login's nonce/issuer/client/subject validation.
116
+ credential.save()
117
+ except (OidcCredential.DoesNotExist, ValueError):
118
+ django_logout(request)
119
+ return
120
+ except (OAuthError, requests.RequestException, OSError, KeyError, TypeError) as error:
121
+ if _definitive_error(error):
122
+ django_logout(request)
123
+ OidcCredential.objects.filter(pk=credential.pk).delete()
124
+ return
125
+ if now >= credential.expires_at:
126
+ from django.http import HttpResponse
127
+
128
+ return HttpResponse(
129
+ "Identity provider temporarily unavailable.", status=503
130
+ )
131
+ return None
132
+
133
+
134
+ def logout_credentials(request):
135
+ credential = OidcCredential.objects.filter(
136
+ session_id=request.session.session_key
137
+ ).first()
138
+ if credential is None:
139
+ return None
140
+ # Delete before logout or a provider request. The foreign key cascades on
141
+ # normal session cleanup; a racing refresh cannot recreate this row.
142
+ credential.delete()
143
+ try:
144
+ return credential.decrypted("id_token") or None
145
+ except ValueError:
146
+ return None
147
+
148
+
149
+ def cleanup():
150
+ OidcCredential.objects.filter(session__expire_date__lt=timezone.now()).delete()
151
+
152
+
153
+ __all__ = [
154
+ "Session",
155
+ "bind_credentials",
156
+ "check_session",
157
+ "cleanup",
158
+ "logout_credentials",
159
+ ]
@@ -0,0 +1,17 @@
1
+ from django.conf import settings
2
+
3
+ OIDC_REQUEST_KEY = "_kik_oidc_authenticated"
4
+
5
+
6
+ def refresh(client, credential):
7
+ refresh_token = credential.decrypted("refresh_token")
8
+ if not refresh_token:
9
+ raise ValueError("No usable OIDC refresh token.")
10
+ metadata = client.load_server_metadata()
11
+ with client._get_oauth_client(**metadata) as session:
12
+ session.token = {"refresh_token": refresh_token}
13
+ return session.refresh_token(
14
+ client.access_token_url or metadata["token_endpoint"],
15
+ refresh_token=refresh_token,
16
+ timeout=settings.OIDC_HTTP_TIMEOUT,
17
+ )
@@ -0,0 +1,9 @@
1
+ from django.urls import path
2
+
3
+ from . import views
4
+
5
+ urlpatterns = [
6
+ path("login", views.login, name="login"),
7
+ path("callback", views.authorize, name="authorize"),
8
+ path("logged-out", views.logged_out, name="logged_out"),
9
+ ]
@@ -0,0 +1,97 @@
1
+ from authlib.integrations.base_client import OAuthError
2
+ from django.conf import settings
3
+ from django.contrib.auth import (
4
+ authenticate,
5
+ )
6
+ from django.contrib.auth import (
7
+ login as django_login,
8
+ )
9
+ from django.contrib.auth import (
10
+ logout as django_logout,
11
+ )
12
+ from django.db import transaction
13
+ from django.http import HttpRequest, HttpResponse
14
+ from django.shortcuts import redirect
15
+ from django.urls import reverse
16
+ from django.utils.http import url_has_allowed_host_and_scheme
17
+ from django.views.decorators.http import require_POST
18
+
19
+ from . import oauth
20
+ from .sessions import bind_credentials, logout_credentials
21
+
22
+
23
+ def _next(request):
24
+ url = request.session.pop("oidc_next", "")
25
+ return (
26
+ url
27
+ if url
28
+ and url_has_allowed_host_and_scheme(
29
+ url,
30
+ allowed_hosts={request.get_host()},
31
+ require_https=request.is_secure(),
32
+ )
33
+ else settings.LOGIN_REDIRECT_URL
34
+ )
35
+
36
+
37
+ def login(request: HttpRequest) -> HttpResponse:
38
+ next_url = request.GET.get("next", "")
39
+ if next_url and url_has_allowed_host_and_scheme(
40
+ next_url,
41
+ allowed_hosts={request.get_host()},
42
+ require_https=request.is_secure(),
43
+ ):
44
+ request.session["oidc_next"] = next_url
45
+ else:
46
+ request.session.pop("oidc_next", None)
47
+ redirect_uri = request.build_absolute_uri(reverse("authorize"))
48
+ return oauth.oidc.authorize_redirect(request, redirect_uri)
49
+
50
+
51
+ def authorize(request: HttpRequest) -> HttpResponse:
52
+ try:
53
+ token = oauth.oidc.authorize_access_token(request)
54
+ verified = token["userinfo"]
55
+ userinfo = oauth.oidc.userinfo(token=token)
56
+ if (
57
+ not verified.get("iss")
58
+ or not verified.get("sub")
59
+ or userinfo.get("sub") != verified["sub"]
60
+ ):
61
+ return HttpResponse("Authentication failed.", status=401)
62
+ claims = {**userinfo, "iss": verified["iss"]}
63
+ with transaction.atomic():
64
+ user = authenticate(request, claims=claims)
65
+ if user is None:
66
+ return HttpResponse("Authentication failed.", status=403)
67
+ django_login(request, user)
68
+ request.session.save()
69
+ bind_credentials(request, user, token)
70
+ except (OAuthError, KeyError):
71
+ return HttpResponse("Authentication failed.", status=401)
72
+ except (TypeError, ValueError):
73
+ logout_credentials(request)
74
+ django_logout(request)
75
+ return HttpResponse("Authentication failed.", status=503)
76
+ return redirect(_next(request))
77
+
78
+
79
+ @require_POST
80
+ def logout(request: HttpRequest) -> HttpResponse:
81
+ id_token = logout_credentials(request)
82
+ django_logout(request)
83
+ redirect_uri = request.build_absolute_uri(reverse("logged_out"))
84
+ if id_token:
85
+ try:
86
+ return oauth.oidc.logout_redirect(
87
+ request,
88
+ post_logout_redirect_uri=redirect_uri,
89
+ id_token_hint=id_token,
90
+ )
91
+ except (OAuthError, KeyError, RuntimeError, ValueError):
92
+ pass
93
+ return redirect("logged_out")
94
+
95
+
96
+ def logged_out(request: HttpRequest) -> HttpResponse:
97
+ return HttpResponse("You have been logged out")