-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdecorator.py
More file actions
443 lines (367 loc) · 16.2 KB
/
Copy pathdecorator.py
File metadata and controls
443 lines (367 loc) · 16.2 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# python imports
import logging
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import AccessMixin
from .models import (
FirstPaediatricAssessment,
MultiaxialDiagnosis,
EpilepsyContext,
Organisation,
Investigations,
Management,
Registration,
Case,
Episode,
Syndrome,
AntiEpilepsyMedicine,
Comorbidity,
Assessment,
Epilepsy12User,
)
from .constants import AUDIT_CENTRE_LEAD_CLINICIAN
from epilepsy12.common_view_functions.sanction_user_access import (
organisation_white_list_for_user,
)
# Logging setup
logger = logging.getLogger(__name__)
model_primary_keys = [
{"id": "case_id", "model": "Case"},
{"id": "registration_id", "model": "Registration"},
{"id": "first_paediatric_assessment", "model": "FirstPaediatricAssessment"},
{"id": "epilepsy_context_id", "model": "EpilepsyContext"},
{"id": "multiaxial_diagnosis_id", "model": "MultiaxialDiagnosis"},
{"id": "episode_id", "model": "Episode"},
{"id": "syndrome_id", "model": "Syndrome"},
{"id": "comorbidity_id", "model": "Comorbidity"},
{"id": "assessment_id", "model": "Assessment"},
{"id": "investigations_id", "model": "Investigations"},
{"id": "management_id", "model": "Management"},
{"id": "antiepilepsy_medicine_id", "model": "AntiEpilepsyMedicine"},
]
def group_required(*group_names):
# decorator receives case_id or registration_id from view and group name(s) as arguments.
# if user is in the list of group_names supplied, access is granted, but only to
# to those users who are either:
# 1. superusers
# 2. RCPCH audit members
# 3. trust level access where their trust is the same as the child
def decorator(view):
def wrapper(request, *args, **kwargs):
user = request.user
if user.is_active and (
user.is_superuser or bool(user.groups.filter(name__in=group_names))
):
# user is in either a trust level or an RCPCH level group but in the correct group otherwise.
if kwargs.get("registration_id") is not None:
registration = Registration.objects.get(
pk=kwargs.get("registration_id")
)
child = registration.case
elif kwargs.get("management_id") is not None:
management = Management.objects.get(pk=kwargs.get("management_id"))
child = management.registration.case
elif kwargs.get("investigations_id") is not None:
investigations = Investigations.objects.get(
pk=kwargs.get("investigations_id")
)
child = investigations.registration.case
elif kwargs.get("first_paediatric_assessment_id") is not None:
first_paediatric_assessment = FirstPaediatricAssessment.objects.get(
pk=kwargs.get("first_paediatric_assessment_id")
)
child = first_paediatric_assessment.registration.case
elif kwargs.get("epilepsy_context_id") is not None:
epilepsy_context = EpilepsyContext.objects.get(
pk=kwargs.get("epilepsy_context_id")
)
child = epilepsy_context.registration.case
elif kwargs.get("multiaxial_diagnosis_id") is not None:
multiaxial_diagnosis = MultiaxialDiagnosis.objects.get(
pk=kwargs.get("multiaxial_diagnosis_id")
)
child = multiaxial_diagnosis.registration.case
elif kwargs.get("episode_id") is not None:
episode = Episode.objects.get(pk=kwargs.get("episode_id"))
child = episode.multiaxial_diagnosis.registration.case
elif kwargs.get("syndrome_id") is not None:
syndrome = Syndrome.objects.get(pk=kwargs.get("syndrome_id"))
child = syndrome.multiaxial_diagnosis.registration.case
elif kwargs.get("comorbidity_id") is not None:
comorbidity = Comorbidity.objects.get(
pk=kwargs.get("comorbidity_id")
)
child = comorbidity.multiaxial_diagnosis.registration.case
elif kwargs.get("antiepilepsy_medicine_id") is not None:
antiepilepsy_medicine = AntiEpilepsyMedicine.objects.get(
pk=kwargs.get("antiepilepsy_medicine_id")
)
child = antiepilepsy_medicine.management.registration.case
elif kwargs.get("case_id") is not None:
case = Case.objects.get(pk=kwargs.get("case_id"))
child = case
# else:
# child = Case.objects.get(pk=kwargs.get('case_id'))
if user.is_rcpch_audit_team_member:
organisation = Organisation.objects.filter(
cases=child,
patient_sites__site_is_actively_involved_in_epilepsy_care=True,
patient_sites__site_is_primary_centre_of_epilepsy_care=True,
active=True,
)
else:
# filter for object where trust (not just organisation) where case is registered is the same as that of user
organisation = Organisation.objects.filter(
cases=child,
patient_sites__site_is_actively_involved_in_epilepsy_care=True,
patient_sites__site_is_primary_centre_of_epilepsy_care=True,
trust=request.user.organisation_employer.trust,
active=True,
)
if organisation.exists() or user.is_rcpch_audit_team_member:
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
else:
raise PermissionDenied()
return wrapper
return decorator
def _user_may_view_this_organisation(request, kwargs):
user = request.user
if kwargs.get("organisation_id") is not None:
organisation_requested = Organisation.objects.get(
pk=kwargs.get("organisation_id")
)
organisation_list = organisation_white_list_for_user(
epilepsy12_user=user
)
if (
(
organisation_requested in organisation_list
and user.is_active
and user.email_confirmed
)
or user.is_superuser
or user.is_rcpch_audit_team_member
):
# user's has an organisation employer in the same trust or LHB as the organisation requested
if kwargs.get("user_type") is not None:
if kwargs.get("user_type") == "rcpch-staff" and not user.is_rcpch_staff:
# this route is for rcpch staff to create new rcpch staff members only
raise PermissionDenied()
# user is allowed
else:
raise PermissionDenied()
else:
# organisation requested does not exist
raise ValueError("Organisation requested does not exist!")
class OrganisationAccessMixin(AccessMixin):
def dispatch(self, request, *args, **kwargs):
# Raises PermissionDenied
_user_may_view_this_organisation(request, kwargs)
return super().dispatch(request, *args, **kwargs)
def user_may_view_this_organisation():
# decorator receives organisation_id.
# access is granted only to users who are either:
# 1. superusers
# 2. Active RCPCH audit members
# 3. Active trust/LHB level users where any trust/LHB they have access to includes the id of the organisation requested
def decorator(view):
def wrapper(request, *args, **kwargs):
_user_may_view_this_organisation(request, kwargs)
return view(request, *args, **kwargs)
return wrapper
return decorator
def user_may_view_organisational_audit(parent_model, parent_type):
def decorator(view):
def wrapper(request, *args, **kwargs):
user = request.user
requested_id = kwargs.get("id")
parent = (
getattr(user.organisation_employer, parent_type)
if user.organisation_employer
else None
)
can_view_parent = parent and parent.id == requested_id
is_lead_clinican = user.role == AUDIT_CENTRE_LEAD_CLINICIAN
if user.is_rcpch_audit_team_member or (
can_view_parent and is_lead_clinican
):
if not parent_model.objects.filter(id=requested_id).exists():
raise Http404
return view(request, *args, **kwargs)
raise PermissionDenied()
return wrapper
return decorator
def lookup_child_if_user_has_permission(request_kwargs, user):
# Guard against users with no active primary employer
if not user.organisation_employer:
return None
via_registration = lambda obj: obj.registration.case
via_multiaxial_dagnosis = lambda obj: obj.multiaxial_diagnosis.registration.case
via_management = lambda obj: obj.management.registration.case
lookup = {
"registration_id": (Registration, lambda reg: reg.case),
"management_id": (Management, via_registration),
"investigations_id": (Investigations, via_registration),
"first_paediatric_assessment_id": (FirstPaediatricAssessment, via_registration),
"epilepsy_context_id": (EpilepsyContext, via_registration),
"multiaxial_diagnosis_id": (MultiaxialDiagnosis, via_registration),
"episode_id": (Episode, via_multiaxial_dagnosis),
"syndrome_id": (Syndrome, via_multiaxial_dagnosis),
"comorbidity_id": (Comorbidity, via_multiaxial_dagnosis),
"antiepilepsy_medicine_id": (AntiEpilepsyMedicine, via_management),
"assessment_id": (Assessment, via_registration),
"case_id": (Case, lambda o: o),
}
for key, (model, via_fn) in lookup.items():
pk = request_kwargs.get(key)
if pk is not None:
obj = model.objects.get(pk=pk)
child = via_fn(obj)
org_filters = {
"cases": child,
"patient_sites__site_is_actively_involved_in_epilepsy_care": True,
"patient_sites__site_is_primary_centre_of_epilepsy_care": True,
# Access is sliced by trust - so members of other organisations in that trust can see data
"trust": user.organisation_employer.trust,
}
if Organisation.objects.filter(**org_filters).exists():
return child
def lookup_user_permissions_on_child(request, request_kwargs):
# Lookup sub object by id and walk backwards to case.
# Access is granted only to users who are either:
# 1. superusers
# 2. Active RCPCH audit members with confirmed email
# 3. Active trust level users with confirmed email where their trust is the same as the child
# Editing is allowed if the cohort is still open or if you are an RCPCH audit member
user = request.user
# Check user is active and has confirmed their email (unless superuser)
if not user.is_superuser and not (user.is_active and user.email_confirmed):
return {
"can_view": False,
"can_edit": False,
}
is_admin = user.is_rcpch_audit_team_member or user.is_rcpch_staff or user.is_superuser
if is_admin:
return {
"can_view": True,
"can_edit": True,
}
child = lookup_child_if_user_has_permission(request_kwargs, request.user)
if child:
return {
"can_view": True,
"can_edit": child.editable(),
}
return {
"can_view": False,
"can_edit": False,
}
def user_may_view_this_child():
def decorator(view):
def wrapper(request, *args, **kwargs):
permissions = lookup_user_permissions_on_child(request, kwargs)
if request.method not in ["GET", "HEAD", "OPTIONS"] and not permissions["can_edit"]:
raise PermissionDenied()
if permissions["can_view"]:
return view(request, permissions["can_edit"], *args, **kwargs)
raise PermissionDenied()
return wrapper
return decorator
def rcpch_full_access_only():
"""
Only permits access to rcpch_audit_team_full_access group members
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
user = request.user
if user.groups.filter(name="epilepsy12_audit_team_full_access").exists():
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
return wrapper
return decorator
def user_can_access_user():
"""
Only permit people from the same organisation of the user being edited to access
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
user_to_edit_id = kwargs["epilepsy12_user_id"]
user_to_edit = Epilepsy12User.objects.get(pk=user_to_edit_id)
if (
request.user.is_rcpch_audit_team_member
or request.user.is_rcpch_staff
or request.user.is_superuser
or request.user.organisation_employer
in organisation_white_list_for_user(user_to_edit)
):
# allow access if user requesting acess is:
# 1. a superuser
# 2. rcpch_autdit_team_member
# 3. rcpch_staff
# 4. not 1-3 but is in the same trust as the user being accessed
return view(request, *args, **kwargs)
else:
raise PermissionDenied()
return wrapper
return decorator
def login_and_otp_required():
"""
Must have verified via 2FA
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
# Then, ensure 2fa verified
user = request.user
# Bypass 2fa if local dev, with warning message
if settings.DEBUG and user.is_authenticated:
logger.warning(
"User %s has bypassed 2FA for %s as settings.DEBUG is %s",
user,
view,
settings.DEBUG,
)
return view(request, *args, **kwargs)
# Prevent unverified users
if not user.is_verified():
user_list = user.__dict__
epilepsy12_user = user_list["_wrapped"]
logger.info(
"User %s is unverified. Tried accessing %s",
epilepsy12_user,
view.__qualname__,
)
raise PermissionDenied()
return view(request, *args, **kwargs)
return login_required(wrapper)
return decorator
class LoginAndOTPRequiredMixin(AccessMixin):
def dispatch(self, request, *args, **kwargs):
user = request.user
# Check if the user is authenticated
if not user.is_authenticated:
return self.handle_no_permission()
# Bypass 2fa if local dev, with warning message
if settings.DEBUG and user.is_authenticated:
logger.warning(
"User %s has bypassed 2FA for %s as settings.DEBUG is %s",
user,
self.__class__.__name__,
settings.DEBUG,
)
return super().dispatch(request, *args, **kwargs)
# Prevent unverified users
if not user.is_verified():
user_list = user.__dict__
epilepsy12_user = user_list["_wrapped"]
logger.info(
"User %s is unverified. Tried accessing %s",
epilepsy12_user,
self.__class__.__name__,
)
raise PermissionDenied()
return super().dispatch(request, *args, **kwargs)