django-clearance 0.1.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.
- clearance/__init__.py +0 -0
- clearance/actions.py +237 -0
- clearance/admin/__init__.py +0 -0
- clearance/admin/actions.py +188 -0
- clearance/admin/apps.py +22 -0
- clearance/admin/checks.py +41 -0
- clearance/admin/discovery.py +39 -0
- clearance/admin/options.py +327 -0
- clearance/admin/protection.py +91 -0
- clearance/admin/scopes.py +272 -0
- clearance/admin/sites.py +73 -0
- clearance/admin/standing.py +261 -0
- clearance/admin/views.py +384 -0
- clearance/apps.py +50 -0
- clearance/backends.py +51 -0
- clearance/checks.py +286 -0
- clearance/conf.py +74 -0
- clearance/declared.py +520 -0
- clearance/decorators.py +59 -0
- clearance/discovery.py +189 -0
- clearance/drf/__init__.py +0 -0
- clearance/drf/checks.py +93 -0
- clearance/drf/discovery.py +58 -0
- clearance/drf/permissions.py +167 -0
- clearance/drf/serializers.py +121 -0
- clearance/drf/viewsets.py +50 -0
- clearance/fields.py +191 -0
- clearance/forms.py +97 -0
- clearance/grants.py +139 -0
- clearance/health.py +242 -0
- clearance/labels.py +70 -0
- clearance/limits.py +64 -0
- clearance/locale/fa/LC_MESSAGES/django.mo +0 -0
- clearance/locale/fa/LC_MESSAGES/django.po +601 -0
- clearance/management/__init__.py +0 -0
- clearance/management/commands/__init__.py +0 -0
- clearance/management/commands/clearance_check.py +34 -0
- clearance/management/commands/clearance_sync.py +72 -0
- clearance/migrations/0001_initial.py +168 -0
- clearance/migrations/0002_scoperule.py +66 -0
- clearance/migrations/0003_protectedfield.py +49 -0
- clearance/migrations/0004_statusaction.py +56 -0
- clearance/migrations/0005_declared.py +47 -0
- clearance/migrations/0006_rows_not_json.py +224 -0
- clearance/migrations/__init__.py +0 -0
- clearance/models.py +597 -0
- clearance/permissions.py +394 -0
- clearance/policies.py +261 -0
- clearance/protocols.py +38 -0
- clearance/py.typed +0 -0
- clearance/querysets.py +281 -0
- clearance/registry.py +103 -0
- clearance/roles/__init__.py +0 -0
- clearance/roles/admin.py +9 -0
- clearance/roles/apps.py +35 -0
- clearance/roles/checks.py +70 -0
- clearance/roles/declared.py +168 -0
- clearance/roles/limits.py +36 -0
- clearance/roles/locale/fa/LC_MESSAGES/django.mo +0 -0
- clearance/roles/locale/fa/LC_MESSAGES/django.po +188 -0
- clearance/roles/migrations/0001_initial.py +170 -0
- clearance/roles/migrations/__init__.py +0 -0
- clearance/roles/models.py +93 -0
- clearance/roles/pages.py +211 -0
- clearance/roles/resolvers.py +109 -0
- clearance/roles/services.py +288 -0
- clearance/roles/signals.py +17 -0
- clearance/roles/templates/clearance/roles/role.html +60 -0
- clearance/roles/templates/clearance/roles/role_add.html +16 -0
- clearance/roles/templates/clearance/roles/role_delete.html +11 -0
- clearance/roles/templates/clearance/roles/roles.html +24 -0
- clearance/rules.py +327 -0
- clearance/safety.py +186 -0
- clearance/services.py +688 -0
- clearance/signals.py +42 -0
- clearance/static/clearance/admin.css +17 -0
- clearance/static/clearance/rules.js +51 -0
- clearance/templates/clearance/admin/action.html +44 -0
- clearance/templates/clearance/admin/action_delete.html +11 -0
- clearance/templates/clearance/admin/actions.html +41 -0
- clearance/templates/clearance/admin/base.html +12 -0
- clearance/templates/clearance/admin/bundle.html +48 -0
- clearance/templates/clearance/admin/bundle_delete.html +12 -0
- clearance/templates/clearance/admin/bundles.html +22 -0
- clearance/templates/clearance/admin/cell.html +5 -0
- clearance/templates/clearance/admin/fields.html +17 -0
- clearance/templates/clearance/admin/fields_of.html +23 -0
- clearance/templates/clearance/admin/overview.html +24 -0
- clearance/templates/clearance/admin/people.html +25 -0
- clearance/templates/clearance/admin/permissions.html +20 -0
- clearance/templates/clearance/admin/person.html +73 -0
- clearance/templates/clearance/admin/scope.html +52 -0
- clearance/templates/clearance/admin/scope_delete.html +15 -0
- clearance/templates/clearance/admin/scopes.html +28 -0
- clearance/templatetags/__init__.py +0 -0
- clearance/templatetags/clearance.py +18 -0
- clearance/translations/__init__.py +0 -0
- clearance/translations/admin.py +9 -0
- clearance/translations/apps.py +33 -0
- clearance/translations/checks.py +38 -0
- clearance/translations/labels.py +73 -0
- clearance/translations/locale/fa/LC_MESSAGES/django.mo +0 -0
- clearance/translations/locale/fa/LC_MESSAGES/django.po +54 -0
- clearance/translations/migrations/0001_initial.py +55 -0
- clearance/translations/migrations/__init__.py +0 -0
- clearance/translations/models.py +34 -0
- clearance/translations/pages.py +92 -0
- clearance/translations/services.py +68 -0
- clearance/translations/signals.py +6 -0
- clearance/translations/templates/clearance/translations/names.html +23 -0
- clearance/views.py +249 -0
- clearance/writes.py +53 -0
- django_clearance-0.1.0.dist-info/METADATA +139 -0
- django_clearance-0.1.0.dist-info/RECORD +116 -0
- django_clearance-0.1.0.dist-info/WHEEL +4 -0
- django_clearance-0.1.0.dist-info/licenses/LICENSE +28 -0
clearance/__init__.py
ADDED
|
File without changes
|
clearance/actions.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Actions beyond view, create, edit and delete - the two kinds there are.
|
|
3
|
+
|
|
4
|
+
**A status action writes values.** Approving an order sets its status to
|
|
5
|
+
*approved* or *rejected*; nothing else does. Declared in code
|
|
6
|
+
(``build_permissions(status_actions=...)``) or made in the database
|
|
7
|
+
(``AccessService.create_status_action``), it **claims** its values: only
|
|
8
|
+
somebody allowed the action - its permission, the row within its scope, and
|
|
9
|
+
the row's current value among its ``from`` - writes them. A value no action
|
|
10
|
+
claims is written by whoever may write the row; several actions may claim
|
|
11
|
+
one field::
|
|
12
|
+
|
|
13
|
+
writable_values(user, Order, 'status', order) # {'pending', 'cancelled'}
|
|
14
|
+
|
|
15
|
+
The other kind - an action that does something new, found in the code - is
|
|
16
|
+
``clearance.discovery``'s.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from types import MappingProxyType
|
|
22
|
+
from typing import Any, Final
|
|
23
|
+
|
|
24
|
+
from django.core.exceptions import FieldDoesNotExist, ValidationError
|
|
25
|
+
from django.db import models
|
|
26
|
+
from django.db.models import Model
|
|
27
|
+
|
|
28
|
+
from clearance.fields import ModelKey, model_key, writable_fields
|
|
29
|
+
from clearance.grants import KEPT_PREFIX
|
|
30
|
+
from clearance.models import StatusAction, StatusActionValue
|
|
31
|
+
from clearance.permissions import (
|
|
32
|
+
DEFAULT_ACTIONS,
|
|
33
|
+
declared_status_actions,
|
|
34
|
+
is_action_name,
|
|
35
|
+
)
|
|
36
|
+
from clearance.protocols import User
|
|
37
|
+
from clearance.registry import registry
|
|
38
|
+
|
|
39
|
+
#: The actions every model has: never a status action, never found.
|
|
40
|
+
STANDARD_ACTIONS: Final = frozenset({*DEFAULT_ACTIONS, 'list'})
|
|
41
|
+
|
|
42
|
+
#: Where the status actions are kept on a user object once read.
|
|
43
|
+
_CACHE_ATTRIBUTE = f'{KEPT_PREFIX}status_actions'
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---------------------------------------------------------------------- status actions
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Transition:
|
|
51
|
+
"""One status action: the values of one field it claims, and where from."""
|
|
52
|
+
|
|
53
|
+
model: type[Model]
|
|
54
|
+
code: str
|
|
55
|
+
field: str
|
|
56
|
+
to: frozenset[Any]
|
|
57
|
+
start: frozenset[Any]
|
|
58
|
+
|
|
59
|
+
def starts_from(self, current: object) -> bool:
|
|
60
|
+
"""Whether it may write from ``current``: from anywhere when ``from`` is empty."""
|
|
61
|
+
return not self.start or current in self.start
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def values_of(model: type[Model], field: str) -> frozenset[Any] | None:
|
|
65
|
+
"""Every value ``model.field`` can hold - its choices, or yes and no - or ``None``."""
|
|
66
|
+
found = model._meta.get_field(field)
|
|
67
|
+
|
|
68
|
+
if isinstance(found, models.BooleanField):
|
|
69
|
+
return frozenset({True, False})
|
|
70
|
+
|
|
71
|
+
if getattr(found, 'choices', None):
|
|
72
|
+
return frozenset(value for value, _ in found.flatchoices) # type: ignore[union-attr]
|
|
73
|
+
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def status_action_problems(
|
|
78
|
+
model: type[Model], code: str, field: str, to: Sequence[object], start: Sequence[object]
|
|
79
|
+
) -> list[str]:
|
|
80
|
+
"""What is wrong with a status action, said in full - for a refusal and for E015."""
|
|
81
|
+
problems = []
|
|
82
|
+
|
|
83
|
+
if not is_action_name(code):
|
|
84
|
+
problems.append(f'{code!r} is not an action: use lowercase words joined by underscores.')
|
|
85
|
+
elif code in STANDARD_ACTIONS:
|
|
86
|
+
problems.append(f'{code!r} is an action every model has already.')
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
every = values_of(model, field)
|
|
90
|
+
except FieldDoesNotExist:
|
|
91
|
+
return [*problems, f'{model.__name__} has no field {field!r}.']
|
|
92
|
+
|
|
93
|
+
if every is None:
|
|
94
|
+
return [*problems, f'{model.__name__}.{field} has no choices, and is not yes or no.']
|
|
95
|
+
|
|
96
|
+
if not to:
|
|
97
|
+
problems.append('It writes no value.')
|
|
98
|
+
|
|
99
|
+
for value in (*to, *start):
|
|
100
|
+
if clean_value(model, field, value) not in every:
|
|
101
|
+
problems.append(f'{value!r} is not one of the values of {model.__name__}.{field}.')
|
|
102
|
+
|
|
103
|
+
return problems
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def transition(
|
|
107
|
+
model: type[Model], code: str, field: str, to: Iterable[object], start: Iterable[object]
|
|
108
|
+
) -> Transition:
|
|
109
|
+
"""A status action, its values in the field's own types."""
|
|
110
|
+
return Transition(
|
|
111
|
+
model,
|
|
112
|
+
code,
|
|
113
|
+
field,
|
|
114
|
+
frozenset(clean_value(model, field, value) for value in to),
|
|
115
|
+
frozenset(clean_value(model, field, value) for value in start),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class StatusActions:
|
|
120
|
+
"""Every status action as it stands: declared in code, or made in the database."""
|
|
121
|
+
|
|
122
|
+
def __init__(self, stored: Mapping[ModelKey, tuple[Transition, ...]]) -> None:
|
|
123
|
+
self._stored = MappingProxyType(dict(stored))
|
|
124
|
+
|
|
125
|
+
@classmethod
|
|
126
|
+
def load(cls) -> 'StatusActions':
|
|
127
|
+
"""
|
|
128
|
+
What the database holds, read in one query - of the values, each with its
|
|
129
|
+
action: an action that writes no value has nothing to claim.
|
|
130
|
+
"""
|
|
131
|
+
values: dict[StatusAction, dict[str, list[str]]] = {}
|
|
132
|
+
|
|
133
|
+
for value in StatusActionValue.objects.select_related('action__content_type'):
|
|
134
|
+
ends = values.setdefault(
|
|
135
|
+
value.action, {StatusActionValue.TO: [], StatusActionValue.FROM: []}
|
|
136
|
+
)
|
|
137
|
+
ends[value.end].append(value.value)
|
|
138
|
+
|
|
139
|
+
stored: dict[ModelKey, list[Transition]] = {}
|
|
140
|
+
|
|
141
|
+
for row, ends in values.items():
|
|
142
|
+
model = row.content_type.model_class()
|
|
143
|
+
|
|
144
|
+
if model is None or _missing(model, row.field):
|
|
145
|
+
continue # nothing left to write - clearance_check lists it
|
|
146
|
+
|
|
147
|
+
found = transition(
|
|
148
|
+
model, row.code, row.field, ends[StatusActionValue.TO], ends[StatusActionValue.FROM]
|
|
149
|
+
)
|
|
150
|
+
stored.setdefault(model_key(model), []).append(found)
|
|
151
|
+
|
|
152
|
+
return cls({key: tuple(found) for key, found in stored.items()})
|
|
153
|
+
|
|
154
|
+
def of(self, model: type[Model]) -> tuple[Transition, ...]:
|
|
155
|
+
declared = tuple(
|
|
156
|
+
transition(model, code, spec['field'], spec['to'], spec['from'])
|
|
157
|
+
for code, spec in declared_status_actions(model).items()
|
|
158
|
+
if not _missing(model, spec['field'])
|
|
159
|
+
)
|
|
160
|
+
return (*declared, *self._stored.get(model_key(model), ()))
|
|
161
|
+
|
|
162
|
+
def on(self, model: type[Model], field: str) -> tuple[Transition, ...]:
|
|
163
|
+
return tuple(found for found in self.of(model) if found.field == field)
|
|
164
|
+
|
|
165
|
+
def fields(self, model: type[Model]) -> frozenset[str]:
|
|
166
|
+
"""The fields of ``model`` some status action writes."""
|
|
167
|
+
return frozenset(found.field for found in self.of(model))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def status_actions_of(user: object) -> StatusActions:
|
|
171
|
+
"""The status actions, read once for ``user``'s request and kept on them."""
|
|
172
|
+
cached: StatusActions | None = getattr(user, _CACHE_ATTRIBUTE, None)
|
|
173
|
+
|
|
174
|
+
if cached is None:
|
|
175
|
+
cached = StatusActions.load()
|
|
176
|
+
setattr(user, _CACHE_ATTRIBUTE, cached)
|
|
177
|
+
|
|
178
|
+
return cached
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def writable_values(
|
|
182
|
+
user: User, model: type[Model], field: str, obj: Model | None = None
|
|
183
|
+
) -> frozenset[Any]:
|
|
184
|
+
"""
|
|
185
|
+
The values of ``field`` ``user`` may write to ``obj`` - or to a new row.
|
|
186
|
+
|
|
187
|
+
Nothing when they may not write the field; every value for the superuser.
|
|
188
|
+
Otherwise every value no status action claims, the value the row holds
|
|
189
|
+
already - keeping it is no change - and the values of every action
|
|
190
|
+
claiming them that they are allowed, from where the row stands.
|
|
191
|
+
"""
|
|
192
|
+
every = values_of(model, field)
|
|
193
|
+
|
|
194
|
+
if every is None:
|
|
195
|
+
raise ValueError(f'{model.__name__}.{field} has no values to choose from.')
|
|
196
|
+
|
|
197
|
+
if field not in writable_fields(user, model):
|
|
198
|
+
return frozenset()
|
|
199
|
+
|
|
200
|
+
transitions = status_actions_of(user).on(model, field)
|
|
201
|
+
|
|
202
|
+
if not transitions or (getattr(user, 'is_superuser', False) and user.is_active):
|
|
203
|
+
return every
|
|
204
|
+
|
|
205
|
+
saved = obj if obj is not None and obj.pk is not None else None
|
|
206
|
+
current = getattr(saved, field) if saved is not None else _default(model, field)
|
|
207
|
+
policy = registry.policy_for(model)
|
|
208
|
+
claimed = frozenset().union(*(found.to for found in transitions))
|
|
209
|
+
allowed = {
|
|
210
|
+
code
|
|
211
|
+
for code in dict.fromkeys(found.code for found in transitions)
|
|
212
|
+
if policy.allows(user, code, saved)
|
|
213
|
+
}
|
|
214
|
+
given = frozenset().union(
|
|
215
|
+
*(found.to for found in transitions if found.code in allowed and found.starts_from(current))
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
return (every - claimed) | given | (every & {current})
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def clean_value(model: type[Model], field: str, value: object) -> object:
|
|
222
|
+
"""``value`` as the field holds it - ``'1'`` is ``1`` for a number - or as it was."""
|
|
223
|
+
try:
|
|
224
|
+
return model._meta.get_field(field).to_python(value) # type: ignore[union-attr]
|
|
225
|
+
except ValidationError:
|
|
226
|
+
return value
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _default(model: type[Model], field: str) -> object:
|
|
230
|
+
return model._meta.get_field(field).get_default() # type: ignore[union-attr]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _missing(model: type[Model], field: str) -> bool:
|
|
234
|
+
try:
|
|
235
|
+
return values_of(model, field) is None
|
|
236
|
+
except FieldDoesNotExist:
|
|
237
|
+
return True
|
|
File without changes
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The actions pages: status actions - made here, declared in code or in the
|
|
3
|
+
``ACCESS`` file - the actions found in the code, and permissions nothing
|
|
4
|
+
checks any more.
|
|
5
|
+
|
|
6
|
+
A status action is made in two steps: its model, then its field - a field
|
|
7
|
+
with choices, or yes or no - so the values it may claim can be offered as
|
|
8
|
+
checkboxes rather than typed. Every change goes through ``AccessService``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from django.contrib import messages
|
|
14
|
+
from django.core.exceptions import FieldDoesNotExist, ValidationError
|
|
15
|
+
from django.http import HttpRequest, HttpResponse
|
|
16
|
+
from django.shortcuts import get_object_or_404
|
|
17
|
+
from django.urls import URLPattern, path
|
|
18
|
+
from django.utils.translation import gettext as _
|
|
19
|
+
|
|
20
|
+
from clearance.actions import StatusActions, clean_value, values_of
|
|
21
|
+
from clearance.admin.views import PageSet
|
|
22
|
+
from clearance.discovery import find_actions
|
|
23
|
+
from clearance.fields import field_names
|
|
24
|
+
from clearance.health import findings
|
|
25
|
+
from clearance.models import Declared, StatusAction
|
|
26
|
+
from clearance.permissions import declared_status_actions
|
|
27
|
+
from clearance.protocols import user_of
|
|
28
|
+
from clearance.safety import AccessRefused
|
|
29
|
+
from clearance.services import AccessService, status_key
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ActionPages(PageSet):
|
|
33
|
+
def get_urls(self) -> list[URLPattern]:
|
|
34
|
+
wrap = self.site.admin_view
|
|
35
|
+
return [
|
|
36
|
+
path('actions/', wrap(self.actions), name='clearance_actions'),
|
|
37
|
+
path('actions/add/', wrap(self.status_action), name='clearance_action_add'),
|
|
38
|
+
path('actions/<int:pk>/', wrap(self.status_action), name='clearance_action'),
|
|
39
|
+
path(
|
|
40
|
+
'actions/<int:pk>/delete/', wrap(self.delete_action), name='clearance_action_delete'
|
|
41
|
+
),
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
def menu(self, request: HttpRequest) -> list[dict[str, Any]]:
|
|
45
|
+
return [
|
|
46
|
+
{
|
|
47
|
+
'name': _('Actions'),
|
|
48
|
+
'object_name': 'StatusAction',
|
|
49
|
+
'admin_url': self.url('clearance_actions'),
|
|
50
|
+
'add_url': None,
|
|
51
|
+
'view_only': not self.may(request, 'edit'),
|
|
52
|
+
}
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
# ------------------------------------------------------------------ pages
|
|
56
|
+
|
|
57
|
+
def actions(self, request: HttpRequest) -> HttpResponse:
|
|
58
|
+
self.require(request, 'view')
|
|
59
|
+
made = (
|
|
60
|
+
StatusAction.objects.select_related('content_type')
|
|
61
|
+
.with_values()
|
|
62
|
+
.order_by('content_type', 'code')
|
|
63
|
+
)
|
|
64
|
+
declared = Declared.keys('status_action')
|
|
65
|
+
in_code = [
|
|
66
|
+
(model._meta.label, code, spec)
|
|
67
|
+
for label, _words in self.models()
|
|
68
|
+
for model in [self.model_named(label)]
|
|
69
|
+
for code, spec in declared_status_actions(model).items()
|
|
70
|
+
]
|
|
71
|
+
return self.render(
|
|
72
|
+
request,
|
|
73
|
+
'actions',
|
|
74
|
+
_('Actions'),
|
|
75
|
+
made=[(row, status_key(row) in declared) for row in made],
|
|
76
|
+
in_code=in_code,
|
|
77
|
+
found=sorted(find_actions(), key=lambda action: action.permission),
|
|
78
|
+
gone=[f for f in findings() if f.code == 'unaccounted_permission'],
|
|
79
|
+
models=self.models(),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def status_action(self, request: HttpRequest, pk: int | None = None) -> HttpResponse:
|
|
83
|
+
self.require(request, 'view')
|
|
84
|
+
row = get_object_or_404(StatusAction, pk=pk) if pk is not None else None
|
|
85
|
+
model = (
|
|
86
|
+
row.content_type.model_class()
|
|
87
|
+
if row is not None
|
|
88
|
+
else self.model_named(request.GET.get('model', ''))
|
|
89
|
+
)
|
|
90
|
+
assert model is not None # a status action's model is never deleted from under it
|
|
91
|
+
field = row.field if row is not None else request.GET.get('field', '')
|
|
92
|
+
errors: list[str] = []
|
|
93
|
+
|
|
94
|
+
if request.method == 'POST':
|
|
95
|
+
try:
|
|
96
|
+
row = self._save(request, model, row, field)
|
|
97
|
+
except (AccessRefused, ValidationError) as error:
|
|
98
|
+
errors = (
|
|
99
|
+
list(error.messages) if isinstance(error, ValidationError) else [str(error)]
|
|
100
|
+
)
|
|
101
|
+
else:
|
|
102
|
+
messages.success(request, _('The status action was saved.'))
|
|
103
|
+
return self.redirect('clearance_action', row.pk)
|
|
104
|
+
|
|
105
|
+
values = _values(model, field)
|
|
106
|
+
declared = row is not None and Declared.holds('status_action', status_key(row))
|
|
107
|
+
return self.render(
|
|
108
|
+
request,
|
|
109
|
+
'action',
|
|
110
|
+
row.name if row is not None else _('Add a status action'),
|
|
111
|
+
row=row,
|
|
112
|
+
model_label=model._meta.label,
|
|
113
|
+
model_words=model._meta.verbose_name_plural,
|
|
114
|
+
field=field,
|
|
115
|
+
fields=[name for name in field_names(model) if _values(model, name)],
|
|
116
|
+
values=values,
|
|
117
|
+
to={*map(str, row.to_values)} if row is not None else set(),
|
|
118
|
+
start={*map(str, row.from_values)} if row is not None else set(),
|
|
119
|
+
errors=errors,
|
|
120
|
+
declared=declared,
|
|
121
|
+
claimed_elsewhere=_claimed(model, field, row),
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def delete_action(self, request: HttpRequest, pk: int) -> HttpResponse:
|
|
125
|
+
self.require(request, 'view')
|
|
126
|
+
row = get_object_or_404(StatusAction, pk=pk)
|
|
127
|
+
|
|
128
|
+
if request.method == 'POST':
|
|
129
|
+
try:
|
|
130
|
+
AccessService(actor=user_of(request)).delete_status_action(row)
|
|
131
|
+
except (AccessRefused, ValidationError) as error:
|
|
132
|
+
for message in (
|
|
133
|
+
error.messages if isinstance(error, ValidationError) else [str(error)]
|
|
134
|
+
):
|
|
135
|
+
messages.error(request, message)
|
|
136
|
+
return self.redirect('clearance_action', pk)
|
|
137
|
+
|
|
138
|
+
messages.success(request, _('The status action was deleted.'))
|
|
139
|
+
return self.redirect('clearance_actions')
|
|
140
|
+
|
|
141
|
+
return self.render(
|
|
142
|
+
request, 'action_delete', _('Delete %(name)s') % {'name': row.name}, row=row
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------------ helpers
|
|
146
|
+
|
|
147
|
+
@staticmethod
|
|
148
|
+
def _save(
|
|
149
|
+
request: HttpRequest, model: Any, row: StatusAction | None, field: str
|
|
150
|
+
) -> StatusAction:
|
|
151
|
+
access, data = AccessService(actor=user_of(request)), request.POST
|
|
152
|
+
to = [clean_value(model, field, value) for value in data.getlist('to')]
|
|
153
|
+
start = [clean_value(model, field, value) for value in data.getlist('from')]
|
|
154
|
+
name = data.get('name', '').strip()
|
|
155
|
+
|
|
156
|
+
if row is None:
|
|
157
|
+
code = data.get('code', '').strip()
|
|
158
|
+
return access.create_status_action(model, code, name or code, field, to, start)
|
|
159
|
+
|
|
160
|
+
return access.change_status_action(row, name=name or row.name, to=to, start=start)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _values(model: Any, field: str) -> list[tuple[str, str]]:
|
|
164
|
+
"""``(value, how it reads)`` for every value ``field`` holds - none when it has no choices."""
|
|
165
|
+
try:
|
|
166
|
+
found = values_of(model, field) if field else None
|
|
167
|
+
except FieldDoesNotExist:
|
|
168
|
+
return []
|
|
169
|
+
|
|
170
|
+
if found is None:
|
|
171
|
+
return []
|
|
172
|
+
|
|
173
|
+
choices = dict(getattr(model._meta.get_field(field), 'flatchoices', ()) or ())
|
|
174
|
+
return sorted((str(value), str(choices.get(value, value))) for value in found)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _claimed(model: Any, field: str, row: StatusAction | None) -> list[str]:
|
|
178
|
+
"""The other actions on the same field, to show what each value is claimed by already."""
|
|
179
|
+
if not field:
|
|
180
|
+
return []
|
|
181
|
+
|
|
182
|
+
others = StatusActions.load().on(model, field)
|
|
183
|
+
own = row.code if row is not None else None
|
|
184
|
+
return sorted(
|
|
185
|
+
f'{found.code}: {", ".join(sorted(map(str, found.to)))}'
|
|
186
|
+
for found in others
|
|
187
|
+
if found.code != own
|
|
188
|
+
)
|
clearance/admin/apps.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Django's admin, with the library's site as the default one.
|
|
3
|
+
|
|
4
|
+
Named in ``INSTALLED_APPS`` in place of ``'django.contrib.admin'``. Django's
|
|
5
|
+
own page for groups is taken away: a bundle is a group, and that page wrote
|
|
6
|
+
round every safety rule - the bundle pages write through ``AccessService``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.contrib.admin.apps import AdminConfig
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ClearanceAdminConfig(AdminConfig):
|
|
13
|
+
default_site = 'clearance.admin.sites.ClearanceAdminSite'
|
|
14
|
+
|
|
15
|
+
def ready(self) -> None:
|
|
16
|
+
super().ready()
|
|
17
|
+
|
|
18
|
+
from django.contrib import admin
|
|
19
|
+
from django.contrib.auth.models import Group
|
|
20
|
+
|
|
21
|
+
if admin.site.is_registered(Group):
|
|
22
|
+
admin.site.unregister(Group)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The admin site, checked at start-up - registered when Django's admin is installed.
|
|
3
|
+
|
|
4
|
+
================== =========================================================
|
|
5
|
+
``clearance.E016`` an admin site is not the library's: its pages would not
|
|
6
|
+
ask the policies, and would show every protected field
|
|
7
|
+
================== =========================================================
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from django.contrib.admin import AdminSite
|
|
14
|
+
from django.contrib.admin.sites import all_sites
|
|
15
|
+
from django.core.checks import CheckMessage, Error
|
|
16
|
+
|
|
17
|
+
from clearance.admin.sites import ClearanceAdminSite
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def admin_site_errors(sites: Iterable[AdminSite]) -> list[CheckMessage]:
|
|
21
|
+
"""E016: every admin site is the library's, or one of its subclasses."""
|
|
22
|
+
return [
|
|
23
|
+
Error(
|
|
24
|
+
f"The admin site {site.name!r} is {type(site).__name__}, not the library's: its "
|
|
25
|
+
f'pages would not ask the policies, and would show every protected field.',
|
|
26
|
+
hint="Put 'clearance.admin.apps.ClearanceAdminConfig' in INSTALLED_APPS in place "
|
|
27
|
+
"of 'django.contrib.admin', and subclass ClearanceAdminSite for a site of your own.",
|
|
28
|
+
obj=site,
|
|
29
|
+
id='clearance.E016',
|
|
30
|
+
)
|
|
31
|
+
for site in sites
|
|
32
|
+
if not isinstance(site, ClearanceAdminSite)
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_admin_sites(app_configs: Any = None, **kwargs: Any) -> list[CheckMessage]:
|
|
37
|
+
return admin_site_errors(sorted(all_sites, key=lambda site: site.name))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
#: Every admin site check, registered by the app when Django's admin is installed.
|
|
41
|
+
CHECKS = (check_admin_sites,)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The actions the admin site offers, found on every ``ModelAdmin`` registered.
|
|
3
|
+
|
|
4
|
+
An action the project wrote - ``actions = ['export_excel']`` - is decided by
|
|
5
|
+
its permission, ``<codename>_export_excel``, made on migrate. One that names
|
|
6
|
+
Django's own permissions (``@admin.action(permissions=['change'])``) is
|
|
7
|
+
Django's to decide, and ``delete_selected`` is the model's ``delete``:
|
|
8
|
+
neither is found, so no permission is made that nothing checks.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from collections.abc import Iterator
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from django.contrib.admin.sites import all_sites
|
|
15
|
+
|
|
16
|
+
from clearance.admin.options import action_func, action_name
|
|
17
|
+
from clearance.discovery import ActionFinder, FoundAction
|
|
18
|
+
from clearance.registry import registry
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AdminActionFinder(ActionFinder):
|
|
22
|
+
"""The actions of every ``ModelAdmin`` on every admin site."""
|
|
23
|
+
|
|
24
|
+
def find(self) -> Iterator[FoundAction]:
|
|
25
|
+
for site in list(all_sites):
|
|
26
|
+
for model, model_admin in site._registry.items():
|
|
27
|
+
policy = registry.policy_for(model)
|
|
28
|
+
admin_class = type(model_admin)
|
|
29
|
+
|
|
30
|
+
guarded: Any = model_admin # _get_base_actions: Django's, before any request
|
|
31
|
+
|
|
32
|
+
for action in guarded._get_base_actions():
|
|
33
|
+
func, name = action_func(action), action_name(action)
|
|
34
|
+
|
|
35
|
+
if name == 'delete_selected' or getattr(func, 'allowed_permissions', None):
|
|
36
|
+
continue
|
|
37
|
+
|
|
38
|
+
origin = f'{admin_class.__module__}.{admin_class.__qualname__}.{name}'
|
|
39
|
+
yield FoundAction(policy, name, origin)
|