-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpermission_utils.py
More file actions
2119 lines (1778 loc) · 73 KB
/
permission_utils.py
File metadata and controls
2119 lines (1778 loc) · 73 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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Permission-related utilities; defines functions to vary content access & render behaviour."""
from functools import wraps
from django.db import connection
from django.http import HttpRequest
from django.conf import settings
from rest_framework import status as RestHttpStatus
from django.db.models import Q, Model
from django.contrib.auth import get_user_model
from rest_framework.request import Request
from django.core.exceptions import PermissionDenied
from rest_framework.exceptions import APIException, MethodNotAllowed, NotAuthenticated
from rest_framework.permissions import BasePermission, SAFE_METHODS
from django.contrib.auth.models import Group
import inspect
from ..models.Organisation import Organisation, OrganisationAuthority, OrganisationMembership
from . import model_utils, gen_utils
from ..models.Brand import Brand
from ..models.Concept import Concept
from ..models.Template import Template
from ..models.GenericEntity import GenericEntity
from ..models.PublishedConcept import PublishedConcept
from ..models.PublishedGenericEntity import PublishedGenericEntity
from ..models.Organisation import Organisation, OrganisationAuthority
from .constants import (
APPROVAL_STATUS, DELETION_QUERY,
ORGANISATION_ROLES, GROUP_PERMISSIONS, WORLD_ACCESS_PERMISSIONS
)
User = get_user_model()
'''Permission decorators'''
def redirect_readonly(fn):
"""
Method decorator to raise 403 if we're on the read only site to avoid insert / update methods via UI
Args:
fn (Callable): the view `Callable` to wrap
Returns:
A (Callable) decorator
Raises:
PermissionDenied
Example:
```py
from clinicalcode.entity_utils import permission_utils
@permission_utils.redirect_readonly
def some_view_func(request):
pass
```
"""
@wraps(fn)
def wrap(request, *args, **kwargs):
if settings.CLL_READ_ONLY:
raise PermissionDenied('ERR_403_GATEWAY')
return fn(request, *args, **kwargs)
return wrap
def brand_admin_required(fn):
"""
Method decorator to raise a 403 if a view isn't accessed by a Brand Administrator
.. Note::
Brand administration privileges are checked by comparing the user against the current brand (per request middleware).
Args:
fn (Callable): the view `Callable` to wrap
Returns:
A (Callable) decorator
Raises:
PermissionDenied
Example:
```py
from django.utils.decorators import method_decorator
from clinicalcode.entity_utils import permission_utils
@method_decorator([permission_utils.brand_admin_required, *other_decorators])
def some_view_func(request):
pass
# Or...
@permission_utils.brand_admin_required
def some_view_func(request):
pass
```
"""
@wraps(fn)
def wrap(request, *args, **kwargs):
user = request.user if hasattr(request, 'user') and request.user.is_authenticated else None
brand = request.BRAND_OBJECT if hasattr(request, 'BRAND_OBJECT') else None
if user is None:
raise PermissionDenied
if not user.is_superuser:
if not isinstance(brand, Brand) or brand.id is None:
raise PermissionDenied
administrable = user.administered_brands \
.filter(id=brand.id, is_administrable=True) \
.exists()
if not administrable:
raise PermissionDenied
return fn(request, *args, **kwargs)
return wrap
'''REST Permission Classes'''
class IsReadOnlyRequest(BasePermission):
"""
Ensures that a request is one of `GET`, `HEAD`, or `OPTIONS`.
Raises:
MethodNotAllowed (405)
Example:
```py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import decorators
from clinicalcode.entity_utils import permission_utils
@schema(None)
class SomeEndpoint(APIView):
permission_classes = [permission_utils.IsReadOnlyRequest]
def get(self, request):
return Response({ 'message': 'Hello, world!' })
```
"""
ERR_STATUS_CODE = RestHttpStatus.HTTP_405_METHOD_NOT_ALLOWED
ERR_REQUEST_MSG = (
'Method Not Allowed: ' + \
'Expected read only method of type `GET`, `HEAD`, `OPTIONS` but got `%s`'
)
def has_permission(self, request, view):
method = request.method
if not method in SAFE_METHODS:
raise MethodNotAllowed(
method=method,
detail=self.ERR_REQUEST_MSG % method,
code=self.ERR_STATUS_CODE
)
return True
class IsReadOnlyOrNotGateway(BasePermission):
"""
Ensures that a request is either (a) read-only or (b) not being made from a TRE read-only site.
.. Note::
- A request must be one of `GET`, `HEAD`, or `OPTIONS` to be considered `ReadOnly`;
- TRE read-only sites are declared as such by the deployment environment variables.
Raises:
MethodNotAllowed (405)
Example:
```py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import decorators
from clinicalcode.entity_utils import permission_utils
@schema(None)
class SomeEndpoint(APIView):
permission_classes = [permission_utils.IsReadOnlyOrNotGateway]
def get(self, request):
return Response({ 'message': 'Hello, world!' })
```
"""
ERR_STATUS_CODE = RestHttpStatus.HTTP_405_METHOD_NOT_ALLOWED
ERR_REQUEST_MSG = (
'Method Not Allowed: ' + \
'Only methods of type `GET`, `HEAD`, `OPTIONS` are accessible from the ReadOnly site, ' + \
'request of type `%s` is not allowed.'
)
def has_permission(self, request, view):
method = request.method
if not request.method in SAFE_METHODS and settings.CLL_READ_ONLY:
raise MethodNotAllowed(
method=method,
detail=self.ERR_REQUEST_MSG % method,
code=self.ERR_STATUS_CODE
)
return True
class IsNotGateway(BasePermission):
"""
Ensures that a request is either not being made from a TRE read-only site.
.. Note::
- TRE read-only sites are declared as such by the deployment environment variables.
Raises:
MethodNotAllowed (405)
Example:
```py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import decorators
from clinicalcode.entity_utils import permission_utils
@schema(None)
class SomeEndpoint(APIView):
permission_classes = [permission_utils.IsNotGateway]
def get(self, request):
return Response({ 'message': 'Hello, world!' })
```
"""
ERR_STATUS_CODE = RestHttpStatus.HTTP_405_METHOD_NOT_ALLOWED
ERR_REQUEST_MSG = (
'Method Not Allowed: ' + \
'Not accessible from the TRE ReadOnly site, ' + \
'request of type `%s` is not allowed.'
)
def has_permission(self, request, view):
method = request.method
if settings.CLL_READ_ONLY:
raise MethodNotAllowed(
method=method,
detail=self.ERR_REQUEST_MSG % method,
code=self.ERR_STATUS_CODE
)
return True
class IsBrandAdmin(BasePermission):
"""
Ensures that the request user is authorised as a Brand Administrator for the request's Brand context.
.. Note::
Requests made by superusers will always granted regardless of Brand context.
Raises:
| Error | Status | Reason |
|----------------|--------|--------------------------------------------------------------------------------|
| Unauthorised | 401 | If the request user is anonymous/hasn't supplied auth token |
| Forbidden | 403 | If the request user is _not_ a known Brand Administrator |
| Not Acceptable | 406 | If the request user is attempting to access the Dashboard for an unknown Brand |
Example:
```py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import decorators
from clinicalcode.entity_utils import permission_utils
@schema(None)
class SomeEndpoint(APIView):
permission_classes = [permission_utils.IsBrandAdmin]
def get(self, request):
return Response({ 'message': 'Hello, world!' })
```
"""
def has_permission(self, request, view):
user = request.user if hasattr(request, 'user') and not request.user.is_anonymous else None
if user is None:
raise NotAuthenticated
if user.is_superuser:
return True
brand = request.BRAND_OBJECT if hasattr(request, 'BRAND_OBJECT') else None
if not isinstance(brand, Brand) or brand.id is None:
raise APIException(detail='Could not resolve Brand context', code=RestHttpStatus.HTTP_406_NOT_ACCEPTABLE)
administrable = user.administered_brands \
.filter(id=brand.id, is_administrable=True) \
.exists()
if not administrable:
raise PermissionDenied
return True
'''Render helpers'''
def should_render_template(template=None, **kwargs):
"""
Method to det. whether a template should be renderable based on its `hide_on_create` property.
Args:
template {model}: optional parameter to check a model instance directly
**kwargs (any): params to use when querying the template model
Returns:
A boolean reflecting the renderable status of a template model
"""
if template is None:
if len(kwargs.keys()) < 1:
return False
template = Template.objects.filter(**kwargs)
if template.exists():
template = template.first()
if not isinstance(template, Template) or not hasattr(template, 'hide_on_create'):
return False
return not template.hide_on_create
'''Status helpers'''
def is_member(user, group_name):
"""
Checks if a User instance is a member of a group
"""
return user.groups.filter(name__iexact=group_name).exists()
def is_requestor_brand_admin(request=None):
"""Evaluates a request, the brand context, and the assoc. user (if any) to determine whether the user can access the Brand Administration panel"""
if not isinstance(request, (Request, HttpRequest)):
return False
user = request.user if hasattr(request, 'user') and not request.user.is_anonymous else None
if user is None:
return False
brand = request.BRAND_OBJECT if hasattr(request, 'BRAND_OBJECT') else None
if not isinstance(brand, Brand) or brand.id is None or not brand.is_administrable:
return False
if user.is_superuser:
return True
administrable = user.administered_brands \
.filter(id=brand.id, is_administrable=True) \
.exists()
return administrable
def get_brand_related_users(req_brand=None):
"""
Resolves users associated with a specific Brand context
Args:
req_brand (str|int|Brand|Request|HttpRequest): either (a) the name/id of the Brand, (b) the Brand object itself, or (c) the HTTP request assoc. with this operation
Returns:
A (QuerySet) containing the users assoc. with this request/brand context
"""
if isinstance(req_brand, (Request, HttpRequest)):
brand = model_utils.try_get_brand(req_brand)
elif isinstance(req_brand, str) and not gen_utils.is_empty_string(req_brand):
brand = model_utils.try_get_instance(Brand, name__iexact=req_brand)
elif isinstance(req_brand, int) and req_brand >= 0:
brand = model_utils.try_get_instance(Brand, pk=req_brand)
elif isinstance(req_brand, Brand) and (inspect.isclass(req_brand) and issubclass(req_brand, Brand)):
brand = req_brand
records = None
if brand is not None:
vis_rules = brand.get_vis_rules()
if isinstance(vis_rules, dict):
allow_null = vis_rules.get('allow_null')
allowed_brands = vis_rules.get('ids')
if isinstance(allowed_brands, list) and isinstance(allow_null, bool) and allow_null:
records = User.objects.filter(Q(accessible_brands__id__isnull=True) | Q(accessible_brands__id__in=allowed_brands))
elif isinstance(allowed_brands, list):
records = User.objects.filter(accessible_brands__id__in=allowed_brands)
elif isinstance(allow_null, bool) and allow_null:
records = User.objects.filter(Q(accessible_brands__id__isnull=True) | Q(accessible_brands__id__in=[brand.id]))
if records is None:
records = User.objects.filter(accessible_brands__id=brand.id)
return records if records is not None else User.objects.all()
def has_member_org_access(user, slug, min_permission):
"""
Checks if a user has access to an organisation.
Min_permissions relates to the organisation role, e.g.
min_permission=1 means the user has to be an editor or above.
"""
if user and not user.is_anonymous:
if not gen_utils.is_empty_string(slug):
organisation = Organisation.objects.filter(slug=slug)
if organisation.exists():
organisation = organisation.first()
if organisation.owner == user:
return True
membership = user.organisationmembership_set \
.filter(organisation__id=organisation.id)
if membership.exists():
return membership.first().role >= min_permission
return False
def has_member_access(user, entity, min_permission):
"""
Checks if a user has access to an entity via its organisation
membership. Min_permissions relates to the organisation role, e.g.
min_permission=1 means the user has to be an editor or above.
"""
try:
org = entity.organisation
except Organisation.DoesNotExist:
org = None
if org:
if org.owner == user:
return True
if user and not user.is_anonymous:
membership = user.organisationmembership_set \
.filter(organisation__id=org.id)
if membership.exists():
return membership.first().role >= min_permission
return False
def get_organisation_role(user, organisation):
if organisation.owner == user:
return ORGANISATION_ROLES.ADMIN
org_membership = model_utils.try_get_instance(OrganisationMembership, user_id=user.id, organisation_id=organisation.id)
if org_membership is None:
return None
if org_membership.role in ORGANISATION_ROLES:
return ORGANISATION_ROLES(org_membership.role)
return -1
def has_org_member(user, organisation):
if organisation.owner == user:
return True
org_membership = model_utils.try_get_instance(OrganisationMembership, user_id=user.id, organisation_id=organisation.id)
return org_membership is not None and org_membership.role in ORGANISATION_ROLES
def has_org_authority(request, organisation):
if not has_org_member(request.user, organisation):
return False
brand = model_utils.try_get_brand(request)
authorities = list(OrganisationAuthority.objects.filter(organisation_id=organisation.id).values('can_post','can_moderate','brand_id'))
requested_authority = None
if brand is not None:
requested_authority = next(
({**authority, 'org_user_managed': brand.org_user_managed} for authority in authorities if brand.id == authority['brand_id']),
None
)
if requested_authority is None:
return {'org_user_managed': False, 'can_moderate': False, 'can_post': False}
return requested_authority
def get_organisation(request, entity_id=None, default=None):
if entity_id is None:
return None
entity = model_utils.try_get_instance(GenericEntity, id=entity_id)
try:
org = entity.organisation
except Organisation.DoesNotExist:
org = default
return org
def is_org_managed(request, brand_id=None):
if brand_id is not None:
brand = model_utils.try_get_instance(Brand, id=brand_id)
else:
brand = model_utils.try_get_brand(request)
return brand.org_user_managed if brand is not None else False
def is_publish_status(entity, status):
"""
Checks the publication status of an entity
"""
history_id = getattr(entity, 'history_id', None)
if history_id is None:
history_id = entity.history.latest().history_id
approval_status = model_utils.get_entity_approval_status(
entity.id, history_id
)
if approval_status:
return approval_status in status
return False
'''General permissions'''
def was_archived(entity_id):
"""
Checks whether an entity was ever archived:
- Archive status is derived from the top-most entity, i.e. the latest version
- We assume that the instance was deleted in cases where the instance does
not exist within the database
Args:
entity_id (integer): The ID of the entity
Returns:
A (boolean) that describes the archived state of an entity
"""
entity = model_utils.try_get_instance(GenericEntity, id=entity_id)
if entity is None:
return True
return True if entity.is_deleted else False
def get_user_groups(request):
"""
Get the groups related to the requesting user
"""
user = request.user
if not user or user.is_anonymous:
return []
if user.is_superuser:
return list(Group.objects.all().exclude(name='ReadOnlyUsers').values('id', 'name'))
return list(user.groups.all().exclude(name='ReadOnlyUsers').values('id', 'name'))
def get_user_organisations(request, min_role_permission=ORGANISATION_ROLES.EDITOR):
"""
Get the organisations related to the requesting user
"""
user = request.user
if not user or user.is_anonymous:
return []
if user.is_superuser:
return list(Organisation.objects.all().values('id', 'name'))
current_brand = model_utils.try_get_brand(request)
current_brand = current_brand if current_brand and current_brand.org_user_managed else None
with connection.cursor() as cursor:
if current_brand is None:
cursor.execute(
'''
select org.id, org.slug, org.name
from public.clinicalcode_organisation org
join public.clinicalcode_organisationmembership mem
on org.id = mem.organisation_id
where org.owner_id = %(user_id)s
or (mem.user_id = %(user_id)s and mem.role >= %(role_enum)s)
''',
params={
'user_id': user.id,
'role_enum': min_role_permission
}
)
else:
cursor.execute(
'''
select org.id, org.slug, org.name
from public.clinicalcode_organisation org
join public.clinicalcode_organisationmembership mem
on org.id = mem.organisation_id
join public.clinicalcode_organisationauthority aut
on org.id = aut.organisation_id
and aut.brand_id = %(brand)s
where (org.owner_id = %(user_id)s or (mem.user_id = %(user_id)s and mem.role >= %(role_enum)s))
and aut.can_post = true
''',
params={
'user_id': user.id,
'role_enum': min_role_permission,
'brand': current_brand.id
}
)
columns = [col[0] for col in cursor.description]
results = [dict(zip(columns, row)) for row in cursor.fetchall()]
return results
def user_has_create_context(request=None):
if request is None or settings.CLL_READ_ONLY:
return False
user = request.user
if user is None or user.is_anonymous or user.is_superuser:
return True
brand = model_utils.try_get_brand(request)
if brand is not None and brand.org_user_managed:
user_orgs = get_user_organisations(
request, min_role_permission=ORGANISATION_ROLES.EDITOR
)
if not user_orgs or len(user_orgs) < 1:
return False
return True
def get_moderation_entities(
request,
status=None
):
"""
Returns entities with moderation status of specified status
Args:
request (RequestContext): HTTP context
status (List): List of integers representing status
Returns:
List of all entities with specified moderation status
"""
entities = GenericEntity.history.all() \
.order_by('id', '-history_id') \
.distinct('id')
entities = entities.filter(Q(publish_status__in=status))
current_brand = model_utils.try_get_brand(request)
current_brand = current_brand if current_brand and current_brand.org_user_managed else None
if current_brand is not None:
entities = entities.filter(
Q(brands__overlap=[current_brand.id])
)
return entities
def get_editable_entities(
request,
only_deleted=False,
consider_brand=True
):
"""
Tries to get all the entities that are editable by a specific user
Args:
request (RequestContext): HTTP context
only_deleted (boolean): Whether to only show deleted phenotypes or not
Returns:
List of all editable entities
"""
user = request.user
if not user or user.is_anonymous:
return None
brand = model_utils.try_get_brand(request) if consider_brand else None
if brand:
brand_sql = 'and %(brand)s = any(live.brands)'
else:
brand_sql = ''
if only_deleted:
delete_sql = 'and live.is_deleted = true'
else:
delete_sql = 'and (live.is_deleted is null or live.is_deleted = false)'
sql = '''
with entity as (
select distinct on (id) *
from public.clinicalcode_historicalgenericentity entity
order by id, history_id desc
)
select entity.id,
entity.name,
entity.history_id,
entity.updated,
entity.publish_status,
live.is_deleted as was_deleted,
organisation.name as group_name,
uac.username as owner_name
from entity
join public.clinicalcode_genericentity live
on live.id = entity.id
join public.auth_user uac
on uac.id = entity.owner_id
left join public.clinicalcode_organisation organisation
on organisation.id = live.organisation_id
left join public.clinicalcode_organisationmembership membership
on membership.organisation_id = organisation.id
where (live.owner_id = %(user_id)s
or organisation.owner_id = %(user_id)s
or (membership.user_id = %(user_id)s AND membership.role >= %(role_enum)s))
{brand}
{delete}
group by entity.id, entity.name, entity.history_id,
entity.updated, entity.publish_status,
live.is_deleted, organisation.name, uac.username
'''.format(
brand=brand_sql,
delete=delete_sql
)
with connection.cursor() as cursor:
cursor.execute(
sql,
params={
'user_id': user.id,
'role_enum': ORGANISATION_ROLES.EDITOR,
'brand': brand.id if brand else None
}
)
columns = [col[0] for col in cursor.description]
results = [dict(zip(columns, row)) for row in cursor.fetchall()]
return results
def get_accessible_entity_history(
request,
entity_id,
entity_history_id,
):
"""
Attempts to get the accessible history of an entity
Args:
request (RequestContext): the HTTPRequest
entity_id (string): some entity to resolve
entity_history_id (integer): the entity's history id
Returns:
A dict containing historical entity data
"""
if not isinstance(entity_id, str) or not isinstance(entity_history_id, int) or isinstance(model_utils.get_entity_id(entity_id), bool):
return None
user = request.user
is_superuser = user.is_superuser if user is not None else False
query_params = { 'pk': entity_id, 'hid': entity_history_id }
brand_clause = ''
brand = model_utils.try_get_brand(request)
if brand is not None:
brand_clause = 'and live.brands && %(brand_ids)s'
query_params.update({ 'brand_ids': [brand.id] })
data = f'''
with
pub_data as (
select
case
when t0.is_last_approved = 1 then true
else false
end as is_last_approved,
case
when t0.is_latest_pending_version = 1 then true
else false
end as is_latest_pending_version,
t0.published_ids,
t0.objects
from (
select
t0.entity_id,
max(
case
when t0.approval_status = {APPROVAL_STATUS.APPROVED.value} then 1
else 0
end
) as is_last_approved,
max(
case
when t0.entity_history_id = %(hid)s and t0.approval_status = {APPROVAL_STATUS.PENDING.value} then 1
else 0
end
) as is_latest_pending_version,
array_agg(case when t0.approval_status = {APPROVAL_STATUS.APPROVED.value} then t0.entity_history_id end) as published_ids,
json_agg(
json_build_object(
'status', t0.approval_status,
'entity_history_id', t0.entity_history_id,
'publish_date', t0.modified,
'approval_status_label', (
case
when t0.approval_status = {APPROVAL_STATUS.REQUESTED.value} then 'REQUESTED'
when t0.approval_status = {APPROVAL_STATUS.PENDING.value} then 'PENDING'
when t0.approval_status = {APPROVAL_STATUS.APPROVED.value} then 'APPROVED'
when t0.approval_status = {APPROVAL_STATUS.REJECTED.value} then 'REJECTED'
else ''
end
)
)
) as objects
from public.clinicalcode_publishedgenericentity as t0
where t0.entity_id = %(pk)s
group by t0.entity_id
) as t0
),
ent_data as (
select *
from (
select t.id, max(t.history_id) as history_id
from public.clinicalcode_historicalgenericentity as t
group by t.id
) as t0
where t0.id = %(pk)s
)'''
# Anon user query
# i.e. only published phenotypes
if not user or user.is_anonymous:
sql = f'''
{data},
historical_entities as (
select
pd.obj->>'approval_status_label'::text as approval_status_label,
to_char(cast(pd.obj->>'publish_date' as timestamptz), 'YYYY-MM-DD HH24:MI') as publish_date,
t0.id,
to_char(t0.history_date, 'YYYY-MM-DD HH24:MI') as history_date,
t0.history_id,
t0.name,
uau.username as updated_by,
cau.username as created_by,
oau.username as owner
from public.clinicalcode_historicalgenericentity as t0
join pub_data as pub
on t0.history_id = any(pub.published_ids)
join public.clinicalcode_genericentity as live
on live.id = t0.id
left join public.auth_user as uau
on t0.updated_by_id = uau.id
left join public.auth_user as cau
on t0.created_by_id = cau.id
left join public.auth_user as oau
on t0.owner_id = oau.id
left join (select json_array_elements(objects::json) as obj from pub_data pd) as pd
on t0.history_id = (pd.obj->>'entity_history_id')::int
where t0.id = %(pk)s
{brand_clause}
)
select t0.history_id as latest_history_id, t1.*, t2.*
from ent_data as t0
left join pub_data as t1
on true
left join (
select json_agg(row_to_json(t.*) order by t.history_id desc) as entities
from (
select *, row_number() over(partition by id, history_id) as rn
from historical_entities
) as t
where rn = 1
) as t2
on true
'''
with connection.cursor() as cursor:
cursor.execute(sql, query_params)
columns = [col[0] for col in cursor.description]
results = cursor.fetchone()
return dict(zip(columns, results)) if results else None
# Non-anon user
# i.e. dependent on user role
clauses = 'true'
if not is_superuser:
org_view_clause = ''
if brand is not None and brand.org_user_managed:
user_orgs = get_user_organisations(request, min_role_permission=ORGANISATION_ROLES.MEMBER)
if user_orgs and len(user_orgs) >= 1:
org_view_clause = f'''
or t0.world_access = {WORLD_ACCESS_PERMISSIONS.VIEW.value}
'''
clauses = f'''
(live.owner_id = %(user_id)s
or org.owner_id = %(user_id)s
or (mem.user_id = %(user_id)s AND mem.role >= %(role_enum)s)
{org_view_clause})
'''
query_params.update({
'user_id': user.id,
'role_enum': ORGANISATION_ROLES.MEMBER
})
pub_status = [APPROVAL_STATUS.APPROVED.value]
if is_member(user, 'Moderators'):
pub_status += [
APPROVAL_STATUS.REQUESTED.value,
APPROVAL_STATUS.PENDING.value,
APPROVAL_STATUS.REJECTED.value
]
if len(pub_status) > 1:
clauses += f'''
or t0.publish_status = any(%(pub_status)s)
'''
query_params.update({ 'pub_status': pub_status })
else:
clauses += f'''
or t0.publish_status = {APPROVAL_STATUS.APPROVED.value}
'''
sql = f'''
{data},
historical_entities as (
select
coalesce(pd.obj->>'approval_status_label'::text, '') as approval_status_label,
to_char(cast(pd.obj->>'publish_date' as timestamptz), 'YYYY-MM-DD HH24:MI') as publish_date,
t0.id,
to_char(t0.history_date, 'YYYY-MM-DD HH24:MI') as history_date,
t0.history_id,
t0.name,
uau.username as updated_by,
cau.username as created_by,
oau.username as owner
from public.clinicalcode_historicalgenericentity as t0
left join public.auth_user as uau
on t0.updated_by_id = uau.id
left join public.auth_user as cau
on t0.created_by_id = cau.id
left join public.auth_user as oau
on t0.owner_id = oau.id
left join (select json_array_elements(objects::json) as obj from pub_data pd) as pd
on t0.history_id = (pd.obj->>'entity_history_id')::int
join public.clinicalcode_genericentity live
on live.id = t0.id
left join public.clinicalcode_organisation org
on org.id = live.organisation_id
left join public.clinicalcode_organisationmembership mem
on mem.organisation_id = org.id
where t0.id = %(pk)s
and ({clauses})
{brand_clause}
)
select t0.history_id as latest_history_id, t1.*, t2.*
from ent_data as t0
left join pub_data as t1
on true
left join (
select json_agg(row_to_json(t.*) order by t.history_id desc) as entities
from (
select *, row_number() over(partition by id, history_id) as rn
from historical_entities
) as t
where rn = 1
) as t2
on true
'''
with connection.cursor() as cursor:
cursor.execute(sql, query_params)
columns = [col[0] for col in cursor.description]
results = cursor.fetchone()
return dict(zip(columns, results)) if results else None
def get_accessible_entities(
request,
consider_user_perms=True,
deletion_query=DELETION_QUERY.ACTIVE,
status=[APPROVAL_STATUS.APPROVED],
min_group_permission=ORGANISATION_ROLES.MEMBER,
consider_brand=True,
raw_query=False,
pk=None
):
"""
Tries to get all the entities that are accessible to a specific user
Args:
request (RequestContext): the HTTPRequest
consider_user_perms (boolean): Whether to consider user perms i.e. superuser, moderation status etc
deletion_query (enum): Specifies how deleted entities should be handled
status (list): A list of publication statuses to consider
group_permissions (list): A list of which group permissions to consider
consider_brand (boolean): Whether to consider the request Brand (only applies to Moderators, Non-Auth'd and Auth'd accounts)
raw_query (boolean): Specifies whether this func should return a RawQuerySet (defaults to `False`)
pk (string): optionally specify some pk to filter
Returns:
(Raw)QuerySet of accessible entities
"""
user = request.user
query_params = { }
# Build brand query
brand = model_utils.try_get_brand(request) if consider_brand else None
brand_clause = ''
if consider_brand and brand is not None:
brand_clause = 'and live_entity.brands && %(brand_ids)s'