-
-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathmixins.py
More file actions
338 lines (258 loc) · 9.94 KB
/
mixins.py
File metadata and controls
338 lines (258 loc) · 9.94 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
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 the options in browsable API for serializers
"""
include_shared = False
@property
def _user_attr(self):
raise NotImplementedError()
def filter_fields(self):
user = self.context["request"].user
# superuser can see everything
if user.is_superuser or user.is_anonymous:
return
# non superusers can see only items of organizations they're related to
organization_filter = getattr(user, self._user_attr)
for field in self.fields:
if field == "organization" and not self.fields[field].read_only:
# queryset attribute will not be present if set to read_only
self.fields[field].allow_null = False
self.fields[field].queryset = self.fields[field].queryset.filter(
pk__in=organization_filter
)
continue
conditions = Q(**{self.organization_lookup: organization_filter})
if self.include_shared:
conditions |= Q(organization__isnull=True)
try:
self.fields[field].queryset = self.fields[field].queryset.filter(
conditions
)
except AttributeError:
pass
def get_sensitive_fields(self):
"""
Returns a list of sensitive fields that should be hidden
when the organization is None and the user is not a superuser.
"""
ModelClass = self.Meta.model
return getattr(ModelClass, "sensitive_fields", [])
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# only filter related fields if the serializer
# is being initiated during an HTTP request
if "request" in self.context:
self.filter_fields()
def to_representation(self, data):
rep = super().to_representation(data)
# Handle single object serializers
self.hide_sensitive_fields(rep)
return rep
def hide_sensitive_fields(self, obj):
request = self.context.get("request")
if (
request
and not request.user.is_superuser
and "organization" in obj
and obj["organization"] is None
):
for field in self.get_sensitive_fields():
if field in obj:
del obj[field]
return obj
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,
)