-
-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathmixins.py
More file actions
384 lines (291 loc) · 11.6 KB
/
mixins.py
File metadata and controls
384 lines (291 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import swapper
from django.core.exceptions import ValidationError
from django.db.models import ForeignKey, ManyToManyField, Q
from django_filters import rest_framework as filters
from django_filters.filters import QuerySetRequestMixin as BaseQuerySetRequestMixin
from rest_framework.authentication import SessionAuthentication
from rest_framework.exceptions import NotFound
from rest_framework.permissions import IsAuthenticated
from .authentication import BearerAuthentication
from .permissions import DjangoModelPermissions, IsOrganizationManager
Organization = swapper.load_model("openwisp_users", "Organization")
class OrgLookup:
@property
def org_field(self):
return getattr(self, "organization_field", "organization")
@property
def organization_lookup(self):
return f"{self.org_field}__in"
class SharedObjectsLookup:
@property
def queryset_organization_conditions(self):
conditions = super().queryset_organization_conditions
organizations = getattr(self.request.user, self._user_attr)
# If user has access to any organization, then include shared
# objects in the queryset.
if len(organizations):
conditions |= Q(**{f"{self.org_field}__isnull": True})
return conditions
class FilterByOrganization(OrgLookup):
"""
Filter queryset based on the access to the organization
of the associated model. Use on of the sub-classes
"""
permission_classes = (IsAuthenticated,)
@property
def _user_attr(self):
raise NotImplementedError()
@property
def queryset_organization_conditions(self):
return Q(
**{self.organization_lookup: getattr(self.request.user, self._user_attr)}
)
def get_queryset(self):
qs = super().get_queryset()
if self.request.user.is_superuser:
return qs
return self.get_organization_queryset(qs)
def get_organization_queryset(self, qs):
if self.request.user.is_anonymous:
return
return qs.filter(self.queryset_organization_conditions)
class FilterByOrganizationMembership(FilterByOrganization):
"""
Filter queryset by organizations the user is a member of
"""
_user_attr = "organizations_dict"
class FilterByOrganizationManaged(SharedObjectsLookup, FilterByOrganization):
"""
Filter queryset by organizations managed by user
"""
_user_attr = "organizations_managed"
class FilterByOrganizationOwned(SharedObjectsLookup, FilterByOrganization):
"""
Filter queryset by organizations owned by user
"""
_user_attr = "organizations_owned"
class FilterByParent(OrgLookup):
"""
Filter queryset based on one of the parent objects
"""
permission_classes = (IsAuthenticated,)
@property
def _user_attr(self):
raise NotImplementedError()
def get_queryset(self):
qs = super().get_queryset()
self.assert_parent_exists()
return qs
def assert_parent_exists(self):
parent_queryset = self.get_parent_queryset()
if not self.request.user.is_superuser:
parent_queryset = self.get_organization_queryset(parent_queryset)
try:
assert parent_queryset.exists()
except (AssertionError, ValidationError):
raise NotFound()
def get_organization_queryset(self, qs):
lookup = {self.organization_lookup: getattr(self.request.user, self._user_attr)}
return qs.filter(**lookup)
def get_parent_queryset(self):
raise NotImplementedError()
class FilterByParentMembership(FilterByParent):
"""
Filter queryset based on parent organization membership
"""
_user_attr = "organizations_dict"
class FilterByParentManaged(FilterByParent):
"""
Filter queryset based on parent organizations managed by user
"""
_user_attr = "organizations_managed"
class FilterByParentOwned(FilterByParent):
"""
Filter queryset based on parent organizations owned by user
"""
_user_attr = "organizations_owned"
class FilterSerializerByOrganization(OrgLookup):
"""
Filter serializer related-field querysets based on the organizations the
current user is allowed to access.
"""
include_shared = False
@property
def _user_attr(self):
raise NotImplementedError()
def _get_org_related_fields(self, model):
org_fields = []
for f in model._meta.get_fields():
if getattr(f, "is_relation", False) and getattr(f, "related_model", None):
if f.related_model is Organization:
org_fields.append(f.name)
return org_fields
def filter_fields(self):
request = self.context.get("request")
if not request:
return
user = request.user
# Superusers or anonymous -> no filtering
if user.is_superuser or user.is_anonymous:
return
allowed_orgs = getattr(user, self._user_attr)
# Detect if user has any organizations (used for include_shared visibility)
try:
has_allowed_orgs = bool(allowed_orgs.exists())
except Exception:
try:
has_allowed_orgs = bool(len(allowed_orgs))
except Exception:
has_allowed_orgs = bool(allowed_orgs)
for field_name, field in self.fields.items():
queryset = getattr(field, "queryset", None)
if queryset is None:
continue
model = getattr(queryset, "model", None)
if model is None:
continue
# CASE A: Field points directly to the Organization model
if model is Organization:
try:
qs = queryset.filter(pk__in=allowed_orgs)
if self.include_shared and has_allowed_orgs:
qs = qs | queryset.filter(pk__isnull=True)
field.queryset = qs.distinct()
except Exception:
pass
# Enforce: non-superusers cannot CREATE shared objects
if field_name == "organization" and not user.is_superuser:
try:
field.allow_null = False
field.required = True
except Exception:
pass
continue
# CASE B: Related model — look for org-related fields
org_fields = self._get_org_related_fields(model)
if not org_fields:
continue
# Build: org_field__in = allowed_orgs
conditions = Q()
for org_field in org_fields:
conditions |= Q(**{f"{org_field}__in": allowed_orgs})
# Visibility: include shared objects (organization=None)
if self.include_shared and has_allowed_orgs:
null_conditions = Q()
for org_field in org_fields:
null_conditions |= Q(**{f"{org_field}__isnull": True})
conditions |= null_conditions
else:
# Normal users must NOT see shared objects if include_shared=False
for org_field in org_fields:
queryset = queryset.exclude(**{f"{org_field}__isnull": True})
# Remove nulls entirely if field disallows null
if not getattr(field, "allow_null", False):
for org_field in org_fields:
queryset = queryset.exclude(**{f"{org_field}__isnull": True})
try:
field.queryset = queryset.filter(conditions).distinct()
except Exception:
pass
# If this field is the organization FK on the serializer,
# enforce NO shared creation for non-superusers
if field_name == "organization" and not user.is_superuser:
try:
field.allow_null = False
field.required = True
except Exception:
pass
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "request" in self.context:
self.filter_fields()
class FilterSerializerByOrgMembership(FilterSerializerByOrganization):
"""
Filter serializer by organizations the user is member of
"""
_user_attr = "organizations_dict"
class FilterSerializerByOrgManaged(FilterSerializerByOrganization):
"""
Filter serializer by organizations managed by user
"""
_user_attr = "organizations_managed"
class FilterSerializerByOrgOwned(FilterSerializerByOrganization):
"""
Filter serializer by organizations owned by user
"""
_user_attr = "organizations_owned"
class QuerySetRequestMixin(BaseQuerySetRequestMixin):
def get_queryset(self, request):
user = request.user
queryset = super().get_queryset(request)
# superuser can see everything
if user.is_superuser or user.is_anonymous:
return queryset
# non superusers can see only items
# of organizations they're related to
organization_filter = getattr(user, self._user_attr)
# if field_name organization then just organization_filter
if self._filter_field == "organization":
return queryset.filter(pk__in=organization_filter)
# for field_name other than organization
conditions = Q(**{"organization__in": organization_filter})
return queryset.filter(conditions)
def __init__(self, *args, **kwargs):
self._user_attr = kwargs.pop("user_attr")
self._filter_field = kwargs.pop("filter_field")
super().__init__(*args, **kwargs)
class DjangoOrganizationFilter(filters.ModelChoiceFilter, QuerySetRequestMixin):
pass
class DjangoOrganizationM2MFilter(
filters.ModelMultipleChoiceFilter, QuerySetRequestMixin
):
pass
class FilterDjangoOrganization(filters.FilterSet):
"""
A custom filter set class that applies DjangoOrganizationFilter
to all ModelChoiceFilter & ModelMultipleChoiceFilterfilters.
"""
@classmethod
def filter_for_field(cls, field, name, lookup_expr="exact"):
if isinstance(field, ForeignKey) or isinstance(field, ManyToManyField):
if field.name == "user":
return super().filter_for_field(field, name, lookup_expr)
opts = dict(
queryset=field.remote_field.model.objects.all(),
label=field.verbose_name.capitalize(),
field_name=name,
user_attr=cls._user_attr,
filter_field=field.name,
)
if isinstance(field, ForeignKey):
return DjangoOrganizationFilter(**opts)
if isinstance(field, ManyToManyField):
return DjangoOrganizationM2MFilter(**opts)
return super().filter_for_field(field, name, lookup_expr)
class FilterDjangoByOrgMembership(FilterDjangoOrganization):
"""
Filter django-filters by organizations the user is member of
"""
_user_attr = "organizations_dict"
class FilterDjangoByOrgManaged(FilterDjangoOrganization):
"""
Filter django-filters by organizations managed by user
"""
_user_attr = "organizations_managed"
class FilterDjangoByOrgOwned(FilterDjangoOrganization):
"""
Filter django-filters by organizations owned by user
"""
_user_attr = "organizations_owned"
class ProtectedAPIMixin(object):
"""
Contains authentication and permission classes for API views
"""
authentication_classes = (
BearerAuthentication,
SessionAuthentication,
)
permission_classes = (
IsOrganizationManager,
DjangoModelPermissions,
)