rn-forge-django 0.6.0__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.
- rn_forge/django/__init__.py +3 -0
- rn_forge/django/_typing.py +77 -0
- rn_forge/django/auth/__init__.py +43 -0
- rn_forge/django/auth/_typing.py +24 -0
- rn_forge/django/auth/accounts.py +206 -0
- rn_forge/django/auth/admin.py +99 -0
- rn_forge/django/auth/apps.py +14 -0
- rn_forge/django/auth/authorization.py +191 -0
- rn_forge/django/auth/csrf.py +162 -0
- rn_forge/django/auth/drf/__init__.py +43 -0
- rn_forge/django/auth/drf/authorization.py +106 -0
- rn_forge/django/auth/drf/oidc.py +63 -0
- rn_forge/django/auth/drf/principal.py +164 -0
- rn_forge/django/auth/drf/serializers.py +140 -0
- rn_forge/django/auth/drf/session.py +81 -0
- rn_forge/django/auth/drf/views.py +67 -0
- rn_forge/django/auth/migrations/0001_initial.py +64 -0
- rn_forge/django/auth/migrations/__init__.py +0 -0
- rn_forge/django/auth/models.py +53 -0
- rn_forge/django/auth/rate_limit.py +80 -0
- rn_forge/django/auth/routes.py +591 -0
- rn_forge/django/auth/sessions.py +238 -0
- rn_forge/django/auth/stores.py +113 -0
- rn_forge/django/auth/urls.py +24 -0
- rn_forge/django/celery.py +43 -0
- rn_forge/django/cors.py +42 -0
- rn_forge/django/deprecation.py +51 -0
- rn_forge/django/drf/__init__.py +39 -0
- rn_forge/django/drf/_typing.py +136 -0
- rn_forge/django/drf/casing.py +147 -0
- rn_forge/django/drf/concurrency.py +79 -0
- rn_forge/django/drf/exceptions.py +187 -0
- rn_forge/django/drf/idempotency.py +154 -0
- rn_forge/django/drf/openapi.py +296 -0
- rn_forge/django/drf/pagination.py +302 -0
- rn_forge/django/drf/routers.py +68 -0
- rn_forge/django/drf/serializers/__init__.py +14 -0
- rn_forge/django/drf/serializers/base.py +52 -0
- rn_forge/django/drf/serializers/fields.py +119 -0
- rn_forge/django/drf/transfer.py +698 -0
- rn_forge/django/drf/urls.py +18 -0
- rn_forge/django/drf/utils.py +127 -0
- rn_forge/django/drf/views/__init__.py +26 -0
- rn_forge/django/drf/views/base.py +36 -0
- rn_forge/django/drf/views/enums.py +57 -0
- rn_forge/django/drf/views/mixins.py +522 -0
- rn_forge/django/exceptions.py +157 -0
- rn_forge/django/fixtures.py +265 -0
- rn_forge/django/messaging/__init__.py +9 -0
- rn_forge/django/messaging/apps.py +13 -0
- rn_forge/django/messaging/consumer.py +91 -0
- rn_forge/django/messaging/models.py +60 -0
- rn_forge/django/messaging/relay.py +76 -0
- rn_forge/django/models/__init__.py +50 -0
- rn_forge/django/models/_meta.py +47 -0
- rn_forge/django/models/base.py +224 -0
- rn_forge/django/models/cache.py +71 -0
- rn_forge/django/models/concurrency.py +165 -0
- rn_forge/django/models/enums.py +50 -0
- rn_forge/django/models/fields.py +69 -0
- rn_forge/django/models/sequences.py +129 -0
- rn_forge/django/models/soft_delete.py +65 -0
- rn_forge/django/models/utils.py +79 -0
- rn_forge/django/py.typed +0 -0
- rn_forge/django/security.py +55 -0
- rn_forge/django/settings.py +230 -0
- rn_forge/django/tracing.py +34 -0
- rn_forge/django/urls.py +14 -0
- rn_forge/django/utils.py +49 -0
- rn_forge/django/views.py +201 -0
- rn_forge_django-0.6.0.dist-info/METADATA +203 -0
- rn_forge_django-0.6.0.dist-info/RECORD +74 -0
- rn_forge_django-0.6.0.dist-info/WHEEL +4 -0
- rn_forge_django-0.6.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Internal protocols and runtime-safe aliases for Django types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from django.db import models
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AbstractUserProtocol",
|
|
11
|
+
"DateField",
|
|
12
|
+
"DjangoAuthProtocol",
|
|
13
|
+
"EnumFieldBase",
|
|
14
|
+
"NullableDateField",
|
|
15
|
+
"StrField",
|
|
16
|
+
"TimestampField",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
# Protocols
|
|
22
|
+
# ---------------------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@runtime_checkable
|
|
26
|
+
class AbstractUserProtocol(Protocol):
|
|
27
|
+
"""Typed proxy for user-like auth objects used by credential helpers."""
|
|
28
|
+
|
|
29
|
+
is_authenticated: bool
|
|
30
|
+
is_staff: bool
|
|
31
|
+
is_superuser: bool
|
|
32
|
+
email: str
|
|
33
|
+
id: object
|
|
34
|
+
pk: object
|
|
35
|
+
|
|
36
|
+
def has_permission(self, permission: str) -> bool: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class DjangoAuthProtocol(Protocol):
|
|
40
|
+
"""Typed proxy for the ``django.contrib.auth`` functions used here."""
|
|
41
|
+
|
|
42
|
+
def authenticate(self, *args: object, **kwargs: object) -> object | None: ...
|
|
43
|
+
|
|
44
|
+
def login(self, request: object, user: object) -> None: ...
|
|
45
|
+
|
|
46
|
+
def logout(self, request: object) -> None: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# django-stubs generic aliases
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
if TYPE_CHECKING:
|
|
54
|
+
from datetime import date, datetime
|
|
55
|
+
|
|
56
|
+
from .models.enums import BaseEnum
|
|
57
|
+
|
|
58
|
+
# ``Field[_ST, _GT]`` names the assignable type and the type read back off a
|
|
59
|
+
# model instance.
|
|
60
|
+
type StrField = models.CharField[str, str]
|
|
61
|
+
type TimestampField = models.DateTimeField[datetime, datetime]
|
|
62
|
+
type DateField = models.DateField[date, date]
|
|
63
|
+
type NullableDateField = models.DateField[date | None, date | None]
|
|
64
|
+
# Used as an EnumField base class below, so it must stay a TypeAlias — a
|
|
65
|
+
# PEP 695 "type" statement alias cannot be subclassed.
|
|
66
|
+
EnumFieldBase: TypeAlias = models.CharField[ # noqa: UP040 # subclassed, not a type alias
|
|
67
|
+
BaseEnum | str | None, BaseEnum | None
|
|
68
|
+
] # NOSONAR(S6794)
|
|
69
|
+
else:
|
|
70
|
+
# Runtime fallbacks: the unsubscripted classes. Every alias gets one so that
|
|
71
|
+
# consumers can use a single plain import rather than repeating a
|
|
72
|
+
# ``TYPE_CHECKING`` guard at each site.
|
|
73
|
+
StrField = models.CharField
|
|
74
|
+
TimestampField = models.DateTimeField
|
|
75
|
+
DateField = models.DateField
|
|
76
|
+
NullableDateField = models.DateField
|
|
77
|
+
EnumFieldBase = models.CharField
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Opinionated rn-forge Django auth app."""
|
|
2
|
+
|
|
3
|
+
from rn_forge.django.auth.apps import AuthConfig
|
|
4
|
+
from rn_forge.django.auth.csrf import (
|
|
5
|
+
CSRF_MIDDLEWARE,
|
|
6
|
+
CSRF_SETTINGS,
|
|
7
|
+
AuthCsrfMiddleware,
|
|
8
|
+
enforce_csrf,
|
|
9
|
+
)
|
|
10
|
+
from rn_forge.django.auth.rate_limit import FixedWindowLimiter, RateLimit
|
|
11
|
+
from rn_forge.django.auth.routes import (
|
|
12
|
+
TRANSACTION_COOKIE,
|
|
13
|
+
AuthRoutesConfig,
|
|
14
|
+
auth_urlpatterns,
|
|
15
|
+
)
|
|
16
|
+
from rn_forge.django.auth.sessions import (
|
|
17
|
+
SESSION_COOKIE,
|
|
18
|
+
SESSION_SETTINGS,
|
|
19
|
+
ActiveSession,
|
|
20
|
+
Sessions,
|
|
21
|
+
rotate_session,
|
|
22
|
+
)
|
|
23
|
+
from rn_forge.django.auth.stores import CacheReplayStore, CacheTransactionStore
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"CSRF_MIDDLEWARE",
|
|
27
|
+
"CSRF_SETTINGS",
|
|
28
|
+
"SESSION_COOKIE",
|
|
29
|
+
"SESSION_SETTINGS",
|
|
30
|
+
"TRANSACTION_COOKIE",
|
|
31
|
+
"ActiveSession",
|
|
32
|
+
"AuthConfig",
|
|
33
|
+
"AuthCsrfMiddleware",
|
|
34
|
+
"AuthRoutesConfig",
|
|
35
|
+
"CacheReplayStore",
|
|
36
|
+
"CacheTransactionStore",
|
|
37
|
+
"FixedWindowLimiter",
|
|
38
|
+
"RateLimit",
|
|
39
|
+
"Sessions",
|
|
40
|
+
"auth_urlpatterns",
|
|
41
|
+
"enforce_csrf",
|
|
42
|
+
"rotate_session",
|
|
43
|
+
]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Runtime-safe type aliases for Django admin classes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, TypeAlias
|
|
6
|
+
|
|
7
|
+
from django.contrib import admin
|
|
8
|
+
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"PermissionAdminBase",
|
|
12
|
+
"UserAdminBase",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from django.contrib.auth.models import AbstractUser, Permission
|
|
17
|
+
|
|
18
|
+
# Both are used as admin base classes below, so they must stay TypeAlias —
|
|
19
|
+
# a PEP 695 "type" statement alias cannot be subclassed.
|
|
20
|
+
PermissionAdminBase: TypeAlias = admin.ModelAdmin[Permission] # noqa: UP040 # NOSONAR(S6794)
|
|
21
|
+
UserAdminBase: TypeAlias = DjangoUserAdmin[AbstractUser] # noqa: UP040 # NOSONAR(S6794)
|
|
22
|
+
else:
|
|
23
|
+
PermissionAdminBase = admin.ModelAdmin
|
|
24
|
+
UserAdminBase = DjangoUserAdmin
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""The default :class:`~rn_forge.auth.AccountResolver` on Django's user model."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Literal, cast
|
|
9
|
+
|
|
10
|
+
from django.contrib.auth import get_user_model
|
|
11
|
+
from django.contrib.auth.models import AbstractUser
|
|
12
|
+
from django.db import IntegrityError, transaction
|
|
13
|
+
from django.db.models import F
|
|
14
|
+
from rn_forge.auth import AccountRejected, ExternalIdentity
|
|
15
|
+
from rn_forge.auth.audit import audit
|
|
16
|
+
from rn_forge.django.auth.models import AccountState, ExternalAccount
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"DjangoAccountResolver",
|
|
20
|
+
"DjangoAccountStateWriter",
|
|
21
|
+
"ProviderPolicy",
|
|
22
|
+
"account_session_version",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class ProviderPolicy:
|
|
28
|
+
"""How logins from one provider are linked and provisioned.
|
|
29
|
+
|
|
30
|
+
Attributes:
|
|
31
|
+
provisioning: ``existing`` rejects a user with no account; ``jit``
|
|
32
|
+
creates the account on first login.
|
|
33
|
+
email_domains: With ``jit``, the email domains that may be provisioned.
|
|
34
|
+
Empty allows any. A non-empty allowlist also requires a verified
|
|
35
|
+
email.
|
|
36
|
+
authoritative_domains: Email domains for which this provider is
|
|
37
|
+
authoritative: a verified email in one links to the existing user
|
|
38
|
+
with that address.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
provisioning: Literal["existing", "jit"] = "existing"
|
|
42
|
+
email_domains: frozenset[str] = frozenset()
|
|
43
|
+
authoritative_domains: frozenset[str] = frozenset()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def account_session_version(user: AbstractUser) -> int:
|
|
47
|
+
"""The session version of *user*; ``0`` before the first bump."""
|
|
48
|
+
return (
|
|
49
|
+
AccountState.objects.filter(user=user)
|
|
50
|
+
.values_list("session_version", flat=True)
|
|
51
|
+
.first()
|
|
52
|
+
or 0
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _domain(email: str | None) -> str:
|
|
57
|
+
return email.rpartition("@")[2].lower() if email else ""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class DjangoAccountResolver:
|
|
61
|
+
"""Links, provisions or rejects external identities as Django users.
|
|
62
|
+
|
|
63
|
+
An identity already linked on ``(issuer, subject)`` resolves to its user.
|
|
64
|
+
Otherwise a verified email in one of the provider's
|
|
65
|
+
:attr:`~ProviderPolicy.authoritative_domains` links to the user with that
|
|
66
|
+
address (case-insensitively, and only when exactly one matches). Otherwise
|
|
67
|
+
the provider's ``jit`` policy provisions a user, and ``existing`` rejects.
|
|
68
|
+
An unverified email never links and is never stored on a provisioned user.
|
|
69
|
+
A provider with no policy is rejected.
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
policies: The policy of each provider, by provider ID.
|
|
73
|
+
sync: Called with the user and the identity at every successful login,
|
|
74
|
+
inside the transaction, to copy attributes onto the user. It must
|
|
75
|
+
save what it changes.
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
policies: Mapping[str, ProviderPolicy],
|
|
81
|
+
*,
|
|
82
|
+
sync: Callable[[AbstractUser, ExternalIdentity], None] | None = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
self._policies = policies
|
|
85
|
+
self._sync = sync
|
|
86
|
+
|
|
87
|
+
def resolve(self, identity: ExternalIdentity) -> str:
|
|
88
|
+
"""Return the account ID of *identity*.
|
|
89
|
+
|
|
90
|
+
Raises:
|
|
91
|
+
AccountRejected: The provider has no policy, or the policy refuses
|
|
92
|
+
the identity.
|
|
93
|
+
"""
|
|
94
|
+
policy = self._policies.get(identity.provider)
|
|
95
|
+
if policy is None:
|
|
96
|
+
raise AccountRejected(f"no policy for provider {identity.provider}")
|
|
97
|
+
try:
|
|
98
|
+
with transaction.atomic():
|
|
99
|
+
user = self._user_for(identity, policy)
|
|
100
|
+
if self._sync is not None:
|
|
101
|
+
self._sync(user, identity)
|
|
102
|
+
except IntegrityError:
|
|
103
|
+
# A concurrent first login created the link.
|
|
104
|
+
user = self._linked(identity.issuer, identity.subject)
|
|
105
|
+
if user is None:
|
|
106
|
+
raise
|
|
107
|
+
return str(user.pk)
|
|
108
|
+
|
|
109
|
+
def lookup(self, issuer: str, subject: str) -> str | None:
|
|
110
|
+
"""Return the account ID linked to *issuer* and *subject*, if any."""
|
|
111
|
+
user = self._linked(issuer, subject)
|
|
112
|
+
return str(user.pk) if user is not None else None
|
|
113
|
+
|
|
114
|
+
def link(
|
|
115
|
+
self, issuer: str, subject: str, user: AbstractUser, *, provider: str = ""
|
|
116
|
+
) -> None:
|
|
117
|
+
"""Link *issuer* and *subject* to *user*, such as a service account.
|
|
118
|
+
|
|
119
|
+
Raises:
|
|
120
|
+
IntegrityError: The pair is already linked.
|
|
121
|
+
"""
|
|
122
|
+
ExternalAccount.objects.create(
|
|
123
|
+
issuer=issuer, subject=subject, user=user, provider=provider
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
def _user_for(
|
|
127
|
+
self, identity: ExternalIdentity, policy: ProviderPolicy
|
|
128
|
+
) -> AbstractUser:
|
|
129
|
+
user = self._linked(identity.issuer, identity.subject)
|
|
130
|
+
if user is not None:
|
|
131
|
+
return user
|
|
132
|
+
domain = _domain(identity.email)
|
|
133
|
+
verified = identity.email_verified and bool(domain)
|
|
134
|
+
if verified and domain in policy.authoritative_domains:
|
|
135
|
+
user = self._by_email(cast(str, identity.email))
|
|
136
|
+
if user is None:
|
|
137
|
+
if policy.provisioning != "jit":
|
|
138
|
+
raise AccountRejected("no account for this identity")
|
|
139
|
+
if policy.email_domains and not (
|
|
140
|
+
verified and domain in policy.email_domains
|
|
141
|
+
):
|
|
142
|
+
raise AccountRejected("email domain is not allowed")
|
|
143
|
+
user = self._provision(identity, verified)
|
|
144
|
+
self.link(identity.issuer, identity.subject, user, provider=identity.provider)
|
|
145
|
+
return user
|
|
146
|
+
|
|
147
|
+
@staticmethod
|
|
148
|
+
def _linked(issuer: str, subject: str) -> AbstractUser | None:
|
|
149
|
+
link = (
|
|
150
|
+
ExternalAccount.objects.select_related("user")
|
|
151
|
+
.filter(issuer=issuer, subject=subject)
|
|
152
|
+
.first()
|
|
153
|
+
)
|
|
154
|
+
return cast(AbstractUser, link.user) if link is not None else None
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _by_email(email: str) -> AbstractUser | None:
|
|
158
|
+
users = list(
|
|
159
|
+
_user_model()._default_manager.filter(email__iexact=email)[:2]
|
|
160
|
+
) # Django's documented manager access
|
|
161
|
+
if len(users) > 1:
|
|
162
|
+
raise AccountRejected("email matches more than one account")
|
|
163
|
+
return users[0] if users else None
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _provision(identity: ExternalIdentity, verified: bool) -> AbstractUser:
|
|
167
|
+
user = _user_model()(
|
|
168
|
+
**{_user_model().USERNAME_FIELD: uuid.uuid4().hex},
|
|
169
|
+
email=identity.email if verified else "",
|
|
170
|
+
)
|
|
171
|
+
user.set_unusable_password()
|
|
172
|
+
user.save()
|
|
173
|
+
account_id, provider = str(user.pk), identity.provider
|
|
174
|
+
# A first-login race rolls the loser back; only a committed account is audited.
|
|
175
|
+
transaction.on_commit(
|
|
176
|
+
lambda: audit(
|
|
177
|
+
"account.provisioned", account_id=account_id, provider=provider
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
return user
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _user_model() -> type[AbstractUser]:
|
|
184
|
+
return cast(type[AbstractUser], get_user_model())
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class DjangoAccountStateWriter:
|
|
188
|
+
"""The :class:`~rn_forge.auth.AccountStateWriter` for Django users."""
|
|
189
|
+
|
|
190
|
+
def set_active(self, account_id: str, active: bool) -> None:
|
|
191
|
+
"""Store whether the user may authenticate."""
|
|
192
|
+
_user_model()._default_manager.filter(pk=account_id).update(
|
|
193
|
+
is_active=active
|
|
194
|
+
) # Django's documented manager access
|
|
195
|
+
if not active:
|
|
196
|
+
audit("account.disabled", account_id=account_id)
|
|
197
|
+
|
|
198
|
+
def bump_session_version(self, account_id: str) -> int:
|
|
199
|
+
"""Increase the user's session version and return the new one."""
|
|
200
|
+
with transaction.atomic():
|
|
201
|
+
state, _ = AccountState.objects.get_or_create(user_id=account_id)
|
|
202
|
+
AccountState.objects.filter(pk=state.pk).update(
|
|
203
|
+
session_version=F("session_version") + 1
|
|
204
|
+
)
|
|
205
|
+
state.refresh_from_db()
|
|
206
|
+
return state.session_version
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Admin registrations for standard Django auth models."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, cast
|
|
4
|
+
|
|
5
|
+
from django.contrib import admin
|
|
6
|
+
from django.contrib.auth import get_user_model
|
|
7
|
+
from django.contrib.auth.admin import GroupAdmin as DjangoGroupAdmin
|
|
8
|
+
from django.contrib.auth.models import AbstractUser, Group, Permission
|
|
9
|
+
from rn_forge.django.auth._typing import PermissionAdminBase, UserAdminBase
|
|
10
|
+
|
|
11
|
+
register_model = cast(Any, admin.register)
|
|
12
|
+
|
|
13
|
+
User: type[AbstractUser] = cast(type[AbstractUser], get_user_model())
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@register_model(Permission)
|
|
17
|
+
class PermissionAdmin(PermissionAdminBase):
|
|
18
|
+
list_display = ("name", "content_type", "codename")
|
|
19
|
+
list_filter = ("content_type",)
|
|
20
|
+
search_fields = ("name", "codename")
|
|
21
|
+
ordering = ("content_type", "codename")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@register_model(Group)
|
|
25
|
+
class GroupAdmin(DjangoGroupAdmin):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@register_model(User)
|
|
30
|
+
class UserAdmin(UserAdminBase):
|
|
31
|
+
list_display = (
|
|
32
|
+
"username",
|
|
33
|
+
"email",
|
|
34
|
+
"first_name",
|
|
35
|
+
"last_name",
|
|
36
|
+
"is_staff",
|
|
37
|
+
"is_superuser",
|
|
38
|
+
"is_active",
|
|
39
|
+
)
|
|
40
|
+
list_filter = (
|
|
41
|
+
"is_staff",
|
|
42
|
+
"is_superuser",
|
|
43
|
+
"is_active",
|
|
44
|
+
"groups",
|
|
45
|
+
)
|
|
46
|
+
search_fields = ("username", "email", "first_name", "last_name")
|
|
47
|
+
ordering = ("username",)
|
|
48
|
+
filter_horizontal = ("groups", "user_permissions")
|
|
49
|
+
readonly_fields = (
|
|
50
|
+
"last_login",
|
|
51
|
+
"date_joined",
|
|
52
|
+
)
|
|
53
|
+
fieldsets = (
|
|
54
|
+
(None, {"fields": ("username", "password")}),
|
|
55
|
+
(
|
|
56
|
+
"Personal info",
|
|
57
|
+
{"fields": ("first_name", "last_name", "email")},
|
|
58
|
+
),
|
|
59
|
+
(
|
|
60
|
+
"Permissions",
|
|
61
|
+
{
|
|
62
|
+
"fields": (
|
|
63
|
+
"is_active",
|
|
64
|
+
"is_staff",
|
|
65
|
+
"is_superuser",
|
|
66
|
+
"groups",
|
|
67
|
+
"user_permissions",
|
|
68
|
+
)
|
|
69
|
+
},
|
|
70
|
+
),
|
|
71
|
+
(
|
|
72
|
+
"Important dates",
|
|
73
|
+
{
|
|
74
|
+
"fields": (
|
|
75
|
+
"last_login",
|
|
76
|
+
"date_joined",
|
|
77
|
+
)
|
|
78
|
+
},
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
add_fieldsets = (
|
|
82
|
+
(
|
|
83
|
+
None,
|
|
84
|
+
{
|
|
85
|
+
"classes": ("wide",),
|
|
86
|
+
"fields": (
|
|
87
|
+
"username",
|
|
88
|
+
"email",
|
|
89
|
+
"password1",
|
|
90
|
+
"password2",
|
|
91
|
+
"first_name",
|
|
92
|
+
"last_name",
|
|
93
|
+
"is_active",
|
|
94
|
+
"is_staff",
|
|
95
|
+
"is_superuser",
|
|
96
|
+
),
|
|
97
|
+
},
|
|
98
|
+
),
|
|
99
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Django app configuration for the opinionated rn-forge auth app."""
|
|
2
|
+
|
|
3
|
+
from typing import ClassVar
|
|
4
|
+
|
|
5
|
+
from django.apps import AppConfig
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AuthConfig(AppConfig):
|
|
9
|
+
"""Register the auth app under a stable label for fixtures/admin/tests."""
|
|
10
|
+
|
|
11
|
+
default_auto_field: ClassVar[str] = "django.db.models.BigAutoField" # pyright: ignore[reportIncompatibleVariableOverride]
|
|
12
|
+
name = "rn_forge.django.auth"
|
|
13
|
+
label = "rn_forge_django_auth"
|
|
14
|
+
verbose_name = "rn-forge-django Auth"
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Authorization for Django accounts: context provider and invalidation signals."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Iterable
|
|
6
|
+
from typing import Any, Final, cast
|
|
7
|
+
|
|
8
|
+
from django.contrib.auth import get_user_model
|
|
9
|
+
from django.contrib.auth.models import AbstractUser, Group, Permission
|
|
10
|
+
from django.db.models import Model, Q
|
|
11
|
+
from django.db.models.signals import m2m_changed, post_delete, post_save
|
|
12
|
+
from rn_forge.auth import AuthorizationContext, AuthorizationContextCache
|
|
13
|
+
from rn_forge.django.auth.accounts import account_session_version
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"BYPASS_ROLES",
|
|
17
|
+
"DjangoAuthorizationContextProvider",
|
|
18
|
+
"connect_authorization_signals",
|
|
19
|
+
"permission_keys",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
BYPASS_ROLES: Final = ("superuser", "staff")
|
|
23
|
+
"""Roles that grant every permission: ``superuser`` for ``is_superuser`` and
|
|
24
|
+
``staff`` for ``is_staff``."""
|
|
25
|
+
|
|
26
|
+
_MODEL_ACTIONS: Final[dict[str, tuple[str, ...]]] = {
|
|
27
|
+
"add": ("create",),
|
|
28
|
+
"change": ("update",),
|
|
29
|
+
"delete": ("delete",),
|
|
30
|
+
"view": ("read", "list"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def permission_keys(permission: Permission) -> frozenset[str]:
|
|
35
|
+
"""The dotted permission keys that a Django *permission* grants.
|
|
36
|
+
|
|
37
|
+
Django's default model permissions map to ``<app_label>.<model>.<action>``,
|
|
38
|
+
lowercase: ``add`` to ``create``, ``change`` to ``update``, ``delete`` to
|
|
39
|
+
``delete`` and ``view`` to both ``read`` and ``list``. So
|
|
40
|
+
``inventory.change_stock`` is ``inventory.stock.update``. Any other
|
|
41
|
+
permission, such as a custom ``inventory.adjust_stock``, keeps its
|
|
42
|
+
``<app_label>.<codename>`` as the key.
|
|
43
|
+
"""
|
|
44
|
+
content_type = permission.content_type
|
|
45
|
+
app_label = content_type.app_label
|
|
46
|
+
verb, _, model = permission.codename.partition("_")
|
|
47
|
+
if verb in _MODEL_ACTIONS and model == content_type.model:
|
|
48
|
+
return frozenset(
|
|
49
|
+
f"{app_label}.{model}.{a}".lower() for a in _MODEL_ACTIONS[verb]
|
|
50
|
+
)
|
|
51
|
+
return frozenset({f"{app_label}.{permission.codename}".lower()})
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _keys(permissions: Iterable[Permission]) -> frozenset[str]:
|
|
55
|
+
return frozenset(
|
|
56
|
+
key for permission in permissions for key in permission_keys(permission)
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class DjangoAuthorizationContextProvider:
|
|
61
|
+
"""An :class:`~rn_forge.auth.AuthorizationContextProvider` over Django's auth models.
|
|
62
|
+
|
|
63
|
+
The account ID is the user's primary key as a string. An unknown user, or
|
|
64
|
+
one with ``is_active`` false, resolves to an inactive context with no
|
|
65
|
+
permissions. Roles are the names of the user's groups. Permissions are the
|
|
66
|
+
keys (see :func:`permission_keys`) of the user's own permissions and those
|
|
67
|
+
of their groups.
|
|
68
|
+
|
|
69
|
+
A staff or superuser account additionally has the matching role from
|
|
70
|
+
:data:`BYPASS_ROLES`, and holds the keys of every Django permission and of
|
|
71
|
+
*catalog*, so the bypass shows in the context as a role and a full
|
|
72
|
+
permission set.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
catalog: Permission keys that exist outside Django's permission table,
|
|
76
|
+
such as a viewset's ``orders.read``, which the bypass also grants.
|
|
77
|
+
session_version: Returns a user's session version. Defaults to the
|
|
78
|
+
one :class:`~rn_forge.django.auth.accounts.DjangoAccountStateWriter`
|
|
79
|
+
bumps.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
*,
|
|
85
|
+
catalog: Iterable[str] = (),
|
|
86
|
+
session_version: Callable[[AbstractUser], int] = account_session_version,
|
|
87
|
+
) -> None:
|
|
88
|
+
self._catalog = frozenset(catalog)
|
|
89
|
+
self._session_version = session_version
|
|
90
|
+
|
|
91
|
+
def resolve(self, account_id: str) -> AuthorizationContext:
|
|
92
|
+
"""Return the current context of the user with primary key *account_id*."""
|
|
93
|
+
user_model = cast(type[AbstractUser], get_user_model())
|
|
94
|
+
user = user_model._default_manager.filter(pk=account_id).first()
|
|
95
|
+
if user is None or not user.is_active:
|
|
96
|
+
return AuthorizationContext(active=False, session_version=0)
|
|
97
|
+
|
|
98
|
+
roles = set(user.groups.values_list("name", flat=True))
|
|
99
|
+
if user.is_superuser:
|
|
100
|
+
roles.add("superuser")
|
|
101
|
+
if user.is_staff:
|
|
102
|
+
roles.add("staff")
|
|
103
|
+
|
|
104
|
+
if user.is_superuser or user.is_staff:
|
|
105
|
+
granted = Permission.objects.select_related("content_type")
|
|
106
|
+
else:
|
|
107
|
+
granted = Permission.objects.filter(
|
|
108
|
+
Q(user=user) | Q(group__user=user)
|
|
109
|
+
).select_related("content_type")
|
|
110
|
+
permissions = _keys(granted)
|
|
111
|
+
if user.is_superuser or user.is_staff:
|
|
112
|
+
permissions |= self._catalog
|
|
113
|
+
|
|
114
|
+
return AuthorizationContext(
|
|
115
|
+
active=True,
|
|
116
|
+
session_version=self._session_version(user),
|
|
117
|
+
permissions=permissions,
|
|
118
|
+
roles=frozenset(roles),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def connect_authorization_signals(
|
|
123
|
+
cache: AuthorizationContextCache,
|
|
124
|
+
) -> Callable[[], None]:
|
|
125
|
+
"""Invalidate *cache* when the Django models behind a context change.
|
|
126
|
+
|
|
127
|
+
A change to a user, or to the groups or permissions assigned directly to
|
|
128
|
+
them, invalidates that account. A change to a group or permission, or to
|
|
129
|
+
which permissions a group holds, invalidates every account. These are the
|
|
130
|
+
signals the ``User``, ``Group`` and ``Permission`` viewsets raise.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
A function that disconnects the receivers.
|
|
134
|
+
"""
|
|
135
|
+
user_model = cast(type[Model], get_user_model())
|
|
136
|
+
|
|
137
|
+
def account_changed(instance: Any, **_: Any) -> None:
|
|
138
|
+
cache.invalidate(str(instance.pk))
|
|
139
|
+
|
|
140
|
+
def everyone_changed(**_: Any) -> None:
|
|
141
|
+
cache.invalidate_all()
|
|
142
|
+
|
|
143
|
+
def user_membership_changed(
|
|
144
|
+
instance: Any, action: str, reverse: bool, pk_set: set[Any] | None, **_: Any
|
|
145
|
+
) -> None:
|
|
146
|
+
if not action.startswith("post_"):
|
|
147
|
+
return
|
|
148
|
+
if not reverse:
|
|
149
|
+
cache.invalidate(str(instance.pk))
|
|
150
|
+
elif pk_set is None:
|
|
151
|
+
# A reverse clear does not say which users it touched.
|
|
152
|
+
cache.invalidate_all()
|
|
153
|
+
else:
|
|
154
|
+
for pk in pk_set:
|
|
155
|
+
cache.invalidate(str(pk))
|
|
156
|
+
|
|
157
|
+
def group_permissions_changed(action: str, **_: Any) -> None:
|
|
158
|
+
if action.startswith("post_"):
|
|
159
|
+
cache.invalidate_all()
|
|
160
|
+
|
|
161
|
+
uid = f"rn_forge_django_auth_{id(cache)}"
|
|
162
|
+
user_groups = cast(Any, user_model).groups.through
|
|
163
|
+
user_perms = cast(Any, user_model).user_permissions.through
|
|
164
|
+
receivers: list[tuple[Any, Any, Any]] = [
|
|
165
|
+
(post_save, account_changed, user_model),
|
|
166
|
+
(post_delete, account_changed, user_model),
|
|
167
|
+
(post_save, everyone_changed, Group),
|
|
168
|
+
(post_delete, everyone_changed, Group),
|
|
169
|
+
(post_save, everyone_changed, Permission),
|
|
170
|
+
(post_delete, everyone_changed, Permission),
|
|
171
|
+
(m2m_changed, user_membership_changed, user_groups),
|
|
172
|
+
(m2m_changed, user_membership_changed, user_perms),
|
|
173
|
+
(m2m_changed, group_permissions_changed, Group.permissions.through),
|
|
174
|
+
]
|
|
175
|
+
for signal, receiver, sender in receivers:
|
|
176
|
+
signal.connect(
|
|
177
|
+
receiver,
|
|
178
|
+
sender=sender,
|
|
179
|
+
weak=False,
|
|
180
|
+
dispatch_uid=f"{uid}_{receiver.__name__}_{sender.__name__}",
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def disconnect() -> None:
|
|
184
|
+
for signal, receiver, sender in receivers:
|
|
185
|
+
signal.disconnect(
|
|
186
|
+
receiver,
|
|
187
|
+
sender=sender,
|
|
188
|
+
dispatch_uid=f"{uid}_{receiver.__name__}_{sender.__name__}",
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
return disconnect
|