-
Notifications
You must be signed in to change notification settings - Fork 336
/
Copy pathserializers.py
2022 lines (1693 loc) · 76.1 KB
/
serializers.py
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
from django.db import connection
from packaging.version import Version
from api.base.exceptions import (
Conflict, EndpointNotImplementedError,
InvalidModelValueError,
)
from api.base.serializers import (
VersionedDateTimeField, HideIfRegistration, IDField,
JSONAPISerializer, LinksField,
NodeFileHyperLinkField, RelationshipField,
ShowIfVersion, TargetTypeField, TypeField,
WaterbutlerLink, BaseAPISerializer,
HideIfWikiDisabled, ShowIfAdminScopeOrAnonymous,
ValuesListField, TargetField,
)
from api.base.settings import ADDONS_FOLDER_CONFIGURABLE
from api.base.utils import (
absolute_reverse, get_object_or_error,
get_user_auth, is_truthy,
)
from api.base.versioning import get_kebab_snake_case_field
from api.institutions.utils import update_institutions
from api.taxonomies.serializers import TaxonomizableSerializerMixin
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from framework.auth.core import Auth
from framework.exceptions import PermissionsError
from osf.models import Tag
from rest_framework import serializers as ser
from rest_framework import exceptions
from addons.base.exceptions import InvalidAuthError, InvalidFolderError
from addons.osfstorage.models import Region
from osf.exceptions import NodeStateError
from osf.models import (
Comment, DraftRegistration, ExternalAccount,
RegistrationSchema, AbstractNode, PrivateLink, Preprint,
RegistrationProvider, OSFGroup, NodeLicense, DraftNode,
Registration, Node,
)
from website.project import new_private_link
from website.project.model import NodeUpdateError
from osf.utils import permissions as osf_permissions
class RegistrationProviderRelationshipField(RelationshipField):
def get_object(self, _id):
return RegistrationProvider.load(_id)
def to_internal_value(self, data):
return self.get_object(data)
class RegionRelationshipField(RelationshipField):
def to_internal_value(self, data):
try:
region_id = Region.objects.filter(_id=data).values_list('id', flat=True).get()
except Region.DoesNotExist:
raise exceptions.ValidationError(detail=f'Region {data} is invalid.')
return region_id
class NodeTagField(ser.Field):
def to_representation(self, obj):
if obj is not None:
return obj.name
return None
def to_internal_value(self, data):
return data
def get_or_add_license_to_serializer_context(serializer, node):
"""
Returns license, and adds license to serializer context with format
serializer.context['licenses'] = {<node_id>: <NodeLicenseRecord object>}
Used for both node_license field and license relationship.
Prevents license from having to be fetched 2x per node.
"""
license_context = serializer.context.get('licenses', {})
if license_context and node._id in license_context:
return license_context.get(node._id)
else:
license = node.license
if license_context:
license_context[node._id] = license
else:
serializer.context['licenses'] = {node._id: license}
return license
class NodeLicenseSerializer(BaseAPISerializer):
copyright_holders = ser.ListField(allow_empty=True, required=False)
year = ser.CharField(allow_blank=True, required=False)
class Meta:
type_ = 'node_licenses'
def get_attribute(self, instance):
"""
Returns node license and caches license in serializer context for optimization purposes.
"""
return get_or_add_license_to_serializer_context(self, instance)
class NodeLicenseRelationshipField(RelationshipField):
def __init__(self, **kwargs):
# HACK: because of persistent name confusion on 'license', set `source='*'`
# and always put the internal value at `validated_data['license_type']`
super().__init__(source='*', **kwargs)
def lookup_attribute(self, obj, lookup_field):
"""
Returns node license id and caches license in serializer context for optimization purposes.
"""
license = get_or_add_license_to_serializer_context(self, obj)
return license.node_license._id if getattr(license, 'node_license', None) else None
def to_internal_value(self, license_id):
node_license = NodeLicense.load(license_id)
if node_license:
return {'license_type': node_license}
raise exceptions.NotFound('Unable to find specified license.')
class NodeCitationSerializer(JSONAPISerializer):
non_anonymized_fields = [
'doi',
'id',
'links',
'publisher',
'title',
'type',
]
id = IDField(read_only=True)
title = ser.CharField(allow_blank=True, read_only=True)
author = ser.ListField(read_only=True)
publisher = ser.CharField(allow_blank=True, read_only=True)
type = ser.CharField(allow_blank=True, read_only=True)
doi = ser.CharField(allow_blank=True, read_only=True)
links = LinksField({'self': 'get_absolute_url'})
def get_absolute_url(self, obj):
return obj['URL']
class Meta:
type_ = 'node-citation'
class NodeCitationStyleSerializer(JSONAPISerializer):
id = ser.CharField(read_only=True)
citation = ser.CharField(allow_blank=True, read_only=True)
def get_absolute_url(self, obj):
return obj['URL']
class Meta:
type_ = 'styled-citations'
def get_license_details(node, validated_data):
if node:
license = node.license if isinstance(node, Preprint) else node.node_license
else:
license = None
if ('license_type' not in validated_data and not (license and license.node_license.license_id)):
raise exceptions.ValidationError(detail='License ID must be provided for a Node License.')
license_id = license.node_license.license_id if license else None
license_year = license.year if license else None
license_holders = license.copyright_holders if license else []
if 'license' in validated_data:
license_year = validated_data['license'].get('year', license_year)
license_holders = validated_data['license'].get('copyright_holders', license_holders)
if 'license_type' in validated_data:
license_id = validated_data['license_type'].license_id
return {
'id': license_id,
'year': license_year,
'copyrightHolders': license_holders,
}
class NodeSerializer(TaxonomizableSerializerMixin, JSONAPISerializer):
# TODO: If we have to redo this implementation in any of the other serializers, subclass ChoiceField and make it
# handle blank choices properly. Currently DRF ChoiceFields ignore blank options, which is incorrect in this
# instance
filterable_fields = frozenset([
'id',
'title',
'description',
'public',
'tags',
'category',
'date_created',
'date_modified',
'root',
'parent',
'contributors',
'preprint',
'subjects',
'reviews_state',
])
# If you add a field to this serializer, be sure to add to this
# list if it doesn't expose user data
non_anonymized_fields = [
'access_requests_enabled',
'analytics_key',
'category',
'children',
'collection',
'comments',
'current_user_is_contributor',
'current_user_is_contributor_or_group_member',
'current_user_permissions',
'date_created',
'date_modified',
'description',
'draft_registrations',
'files',
'fork',
'forked_from',
'id',
'license',
'linked_by_nodes',
'linked_by_registrations',
'linked_nodes',
'linked_registrations',
'links',
'logs',
'node_links',
'parent',
'preprint',
'preprints',
'public',
'region',
'registration',
'root',
'settings',
'storage',
'subjects',
'tags',
'template_from',
'template_node',
'title',
'type',
'view_only_links',
'wiki_enabled',
'wikis',
]
id = IDField(source='_id', read_only=True)
type = TypeField()
category_choices = list(settings.NODE_CATEGORY_MAP.items())
category_choices_string = ', '.join([f"'{choice[0]}'" for choice in category_choices])
title = ser.CharField(required=True)
description = ser.CharField(required=False, allow_blank=True, allow_null=True)
category = ser.ChoiceField(choices=category_choices, help_text='Choices: ' + category_choices_string)
custom_citation = ser.CharField(allow_blank=True, required=False)
date_created = VersionedDateTimeField(source='created', read_only=True)
date_modified = VersionedDateTimeField(source='last_logged', read_only=True)
registration = ser.BooleanField(read_only=True, source='is_registration')
preprint = ser.SerializerMethodField()
fork = ser.BooleanField(read_only=True, source='is_fork')
collection = ser.BooleanField(read_only=True, source='is_collection')
tags = ValuesListField(attr_name='name', child=ser.CharField(), required=False)
access_requests_enabled = ShowIfVersion(ser.BooleanField(read_only=False, required=False), min_version='2.0', max_version='2.8')
node_license = NodeLicenseSerializer(required=False, source='license')
analytics_key = ShowIfAdminScopeOrAnonymous(ser.CharField(read_only=True, source='keenio_read_key'))
template_from = ser.CharField(
required=False, allow_blank=False, allow_null=False,
help_text='Specify a node id for a node you would like to use as a template for the '
'new node. Templating is like forking, except that you do not copy the '
'files, only the project structure. Some information is changed on the top '
'level project by submitting the appropriate fields in the request body, '
'and some information will not change. By default, the description will '
'be cleared and the project will be made private.',
)
current_user_can_comment = ser.SerializerMethodField(help_text='Whether the current user is allowed to post comments')
current_user_permissions = ser.SerializerMethodField(
help_text='List of strings representing the permissions '
'for the current user on this node. As of version 2.11, this field will only return the permissions '
'explicitly assigned to the current user, and will not automatically return read for all public nodes',
)
current_user_is_contributor = ser.SerializerMethodField(
help_text='Whether the current user is a contributor on this node.',
)
current_user_is_contributor_or_group_member = ser.SerializerMethodField(
help_text='Whether the current user is a contributor or group member on this node.',
)
wiki_enabled = ser.SerializerMethodField(help_text='Whether the wiki addon is enabled')
# Public is only write-able by admins--see update method
public = ser.BooleanField(
source='is_public', required=False,
help_text='Nodes that are made public will give read-only access '
'to everyone. Private nodes require explicit read '
'permission. Write and admin access are the same for '
'public and private nodes. Administrators on a parent '
'node have implicit read permissions for all child nodes',
)
links = LinksField({'html': 'get_absolute_html_url'})
# TODO: When we have osf_permissions.ADMIN permissions, make this writable for admins
license = NodeLicenseRelationshipField(
related_view='licenses:license-detail',
related_view_kwargs={'license_id': '<license.node_license._id>'},
read_only=False,
)
children = RelationshipField(
related_view='nodes:node-children',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_node_count'},
)
comments = RelationshipField(
related_view='nodes:node-comments',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'unread': 'get_unread_comments_count'},
filter={'target': '<_id>'},
)
contributors = RelationshipField(
related_view='nodes:node-contributors',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_contrib_count'},
)
bibliographic_contributors = RelationshipField(
related_view='nodes:node-bibliographic-contributors',
related_view_kwargs={'node_id': '<_id>'},
)
implicit_contributors = RelationshipField(
related_view='nodes:node-implicit-contributors',
related_view_kwargs={'node_id': '<_id>'},
help_text='This feature is experimental and being tested. It may be deprecated.',
)
files = RelationshipField(
related_view='nodes:node-storage-providers',
related_view_kwargs={'node_id': '<_id>'},
)
settings = RelationshipField(
related_view='nodes:node-settings',
related_view_kwargs={'node_id': '<_id>'},
)
wikis = HideIfWikiDisabled(
RelationshipField(
related_view='nodes:node-wikis',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_wiki_page_count'},
),
)
forked_from = RelationshipField(
related_view=lambda node: (
'registrations:registration-detail'
if getattr(node.forked_from, 'is_registration', False)
else 'nodes:node-detail'
),
related_view_kwargs={'node_id': '<forked_from_guid>'},
)
template_node = RelationshipField(
related_view='nodes:node-detail',
related_view_kwargs={'node_id': '<template_node._id>'},
)
forks = RelationshipField(
related_view='nodes:node-forks',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_forks_count'},
)
groups = RelationshipField(
related_view='nodes:node-groups',
related_view_kwargs={'node_id': '<_id>'},
)
node_links = ShowIfVersion(
RelationshipField(
related_view='nodes:node-pointers',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_pointers_count'},
help_text='This feature is deprecated as of version 2.1. Use linked_nodes instead.',
), min_version='2.0', max_version='2.0',
)
linked_by_nodes = RelationshipField(
related_view='nodes:node-linked-by-nodes',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_linked_by_nodes_count'},
)
linked_by_registrations = RelationshipField(
related_view='nodes:node-linked-by-registrations',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_linked_by_registrations_count'},
)
parent = RelationshipField(
related_view='nodes:node-detail',
related_view_kwargs={'node_id': '<parent_id>'},
source='parent_node',
)
identifiers = RelationshipField(
related_view='nodes:identifier-list',
related_view_kwargs={'node_id': '<_id>'},
)
affiliated_institutions = RelationshipField(
related_view='nodes:node-institutions',
related_view_kwargs={'node_id': '<_id>'},
self_view='nodes:node-relationships-institutions',
self_view_kwargs={'node_id': '<_id>'},
read_only=False,
required=False,
)
draft_registrations = HideIfRegistration(
RelationshipField(
related_view='nodes:node-draft-registrations',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_draft_registration_count'},
),
)
registrations = HideIfRegistration(
RelationshipField(
related_view='nodes:node-registrations',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_registration_count'},
),
)
region = RegionRelationshipField(
related_view='regions:region-detail',
related_view_kwargs={'region_id': 'get_region_id'},
read_only=False,
)
root = RelationshipField(
related_view='nodes:node-detail',
related_view_kwargs={'node_id': '<root._id>'},
)
logs = RelationshipField(
related_view='nodes:node-logs',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_logs_count'},
)
linked_nodes = RelationshipField(
related_view='nodes:linked-nodes',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_node_links_count'},
self_view='nodes:node-pointer-relationship',
self_view_kwargs={'node_id': '<_id>'},
self_meta={'count': 'get_node_links_count'},
)
linked_registrations = RelationshipField(
related_view='nodes:linked-registrations',
related_view_kwargs={'node_id': '<_id>'},
related_meta={'count': 'get_registration_links_count'},
self_view='nodes:node-registration-pointer-relationship',
self_view_kwargs={'node_id': '<_id>'},
self_meta={'count': 'get_node_links_count'},
)
view_only_links = RelationshipField(
related_view='nodes:node-view-only-links',
related_view_kwargs={'node_id': '<_id>'},
)
citation = RelationshipField(
related_view='nodes:node-citation',
related_view_kwargs={'node_id': '<_id>'},
)
preprints = HideIfRegistration(
RelationshipField(
related_view='nodes:node-preprints',
related_view_kwargs={'node_id': '<_id>'},
),
)
storage = RelationshipField(
related_view='nodes:node-storage',
related_view_kwargs={'node_id': '<_id>'},
)
cedar_metadata_records = RelationshipField(
related_view='nodes:node-cedar-metadata-records-list',
related_view_kwargs={'node_id': '<_id>'},
)
subjects_acceptable = HideIfRegistration(
RelationshipField(
related_view='subjects:subject-list',
related_view_kwargs={},
read_only=True,
),
)
@property
def subjects_related_view(self):
# Overrides TaxonomizableSerializerMixin
return 'nodes:node-subjects'
@property
def subjects_view_kwargs(self):
# Overrides TaxonomizableSerializerMixin
return {'node_id': '<_id>'}
@property
def subjects_self_view(self):
# Overrides TaxonomizableSerializerMixin
return 'nodes:node-relationships-subjects'
def get_current_user_permissions(self, obj):
"""
Returns the logged-in user's permissions to the
current node. Implicit admin factored in.
Can have contributor or group member permissions.
"""
user = self.context['request'].user
request_version = self.context['request'].version
default_perm = [osf_permissions.READ] if Version(request_version) < Version('2.11') else []
# View only link users should always get `READ` permissions regardless of other permissions
if Auth(private_key=self.context['request'].query_params.get('view_only')).private_link:
return [osf_permissions.READ]
if user.is_anonymous:
return default_perm
if hasattr(obj, 'has_admin'):
user_perms = []
if obj.has_admin:
user_perms = [osf_permissions.ADMIN, osf_permissions.WRITE, osf_permissions.READ]
elif obj.has_write:
user_perms = [osf_permissions.WRITE, osf_permissions.READ]
elif obj.has_read:
user_perms = [osf_permissions.READ]
else:
user_perms = obj.get_permissions(user)[::-1]
user_perms = user_perms or default_perm
if not user_perms and user in getattr(obj, 'parent_admin_users', []):
user_perms = [osf_permissions.READ]
return user_perms
def get_current_user_can_comment(self, obj):
user = self.context['request'].user
auth = Auth(user if not user.is_anonymous else None)
if hasattr(obj, 'has_read'):
if obj.comment_level == 'public':
return auth.logged_in and (
obj.is_public or
(auth.user and obj.has_read)
)
return obj.has_read or False
else:
return obj.can_comment(auth)
def get_preprint(self, obj):
# Whether the node has supplemental material for a preprint the user can view
if hasattr(obj, 'has_viewable_preprints'):
# if queryset has been annotated with "has_viewable_preprints", use this value
return obj.has_viewable_preprints
else:
user = self.context['request'].user
return Preprint.objects.can_view(base_queryset=obj.preprints, user=user).exists()
def get_current_user_is_contributor(self, obj):
# Returns whether user is a contributor (does not include group members)
if hasattr(obj, 'user_is_contrib'):
return obj.user_is_contrib
user = self.context['request'].user
if user.is_anonymous:
return False
return obj.is_contributor(user)
def get_current_user_is_contributor_or_group_member(self, obj):
# Returns whether user is a contributor -or- a group member
if hasattr(obj, 'has_read'):
return obj.has_read
user = self.context['request'].user
if user.is_anonymous:
return False
return obj.is_contributor_or_group_member(user)
class Meta:
type_ = 'nodes'
def get_absolute_url(self, obj):
return obj.get_absolute_url()
# TODO: See if we can get the count filters into the filter rather than the serializer.
def get_logs_count(self, obj):
return obj.logs.count()
def get_node_count(self, obj):
"""
Returns the count of a node's direct children that the user has permission to view.
Implict admin and group membership are factored in when determining perms.
"""
auth = get_user_auth(self.context['request'])
user_id = getattr(auth.user, 'id', None)
with connection.cursor() as cursor:
cursor.execute(
"""
WITH RECURSIVE parents AS (
SELECT parent_id, child_id
FROM osf_noderelation
WHERE child_id = %s AND is_node_link IS FALSE
UNION ALL
SELECT osf_noderelation.parent_id, parents.parent_id AS child_id
FROM parents JOIN osf_noderelation ON parents.PARENT_ID = osf_noderelation.child_id
WHERE osf_noderelation.is_node_link IS FALSE
), has_admin AS (SELECT EXISTS(
SELECT P.codename
FROM auth_permission AS P
INNER JOIN osf_nodegroupobjectpermission AS G ON (P.id = G.permission_id)
INNER JOIN osf_osfuser_groups AS UG ON (G.group_id = UG.group_id)
WHERE (P.codename = 'admin_node'
AND (G.content_object_id IN (
SELECT parent_id
FROM parents
) OR G.content_object_id = %s)
AND UG.osfuser_id = %s)
))
SELECT COUNT(DISTINCT child_id)
FROM
osf_noderelation
JOIN osf_abstractnode ON osf_noderelation.child_id = osf_abstractnode.id
LEFT JOIN osf_privatelink_nodes ON osf_abstractnode.id = osf_privatelink_nodes.abstractnode_id
LEFT JOIN osf_privatelink ON osf_privatelink_nodes.privatelink_id = osf_privatelink.id
WHERE parent_id = %s AND is_node_link IS FALSE
AND osf_abstractnode.is_deleted IS FALSE
AND (
osf_abstractnode.is_public
OR (SELECT exists from has_admin) = TRUE
OR (SELECT EXISTS(
SELECT P.codename
FROM auth_permission AS P
INNER JOIN osf_nodegroupobjectpermission AS G ON (P.id = G.permission_id)
INNER JOIN osf_osfuser_groups AS UG ON (G.group_id = UG.group_id)
WHERE (P.codename = 'read_node'
AND G.content_object_id = osf_abstractnode.id
AND UG.osfuser_id = %s)
)
)
OR (osf_privatelink.key = %s AND osf_privatelink.is_deleted = FALSE)
);
""", [obj.id, obj.id, user_id, obj.id, user_id, auth.private_key],
)
return int(cursor.fetchone()[0])
def get_contrib_count(self, obj):
return len(obj.contributors)
def get_registration_count(self, obj):
auth = get_user_auth(self.context['request'])
registrations = [node for node in obj.registrations_all if node.can_view(auth)]
return len(registrations)
def get_draft_registration_count(self, obj):
auth = get_user_auth(self.context['request'])
if obj.has_permission(auth.user, osf_permissions.ADMIN):
return obj.draft_registrations_active.count()
def get_pointers_count(self, obj):
return obj.linked_nodes.count()
def get_wiki_page_count(self, obj):
return obj.wikis.filter(deleted__isnull=True).count()
def get_node_links_count(self, obj):
auth = get_user_auth(self.context['request'])
linked_nodes = obj.linked_nodes.filter(is_deleted=False).exclude(type='osf.collection').exclude(type='osf.registration')
return linked_nodes.can_view(auth.user, auth.private_link).count()
def get_registration_links_count(self, obj):
auth = get_user_auth(self.context['request'])
linked_registrations = obj.linked_nodes.filter(is_deleted=False, type='osf.registration').exclude(type='osf.collection')
return linked_registrations.can_view(auth.user, auth.private_link).count()
def get_linked_by_nodes_count(self, obj):
return obj._parents.filter(is_node_link=True, parent__is_deleted=False, parent__type='osf.node').count()
def get_linked_by_registrations_count(self, obj):
return obj._parents.filter(is_node_link=True, parent__type='osf.registration', parent__retraction__isnull=True).count()
def get_forks_count(self, obj):
return obj.forks.exclude(type='osf.registration').exclude(is_deleted=True).count()
def get_unread_comments_count(self, obj):
user = get_user_auth(self.context['request']).user
node_comments = Comment.find_n_unread(user=user, node=obj, page='node')
return {
'node': node_comments,
}
def get_region_id(self, obj):
try:
# use the annotated value if possible
region_id = obj.region
except AttributeError:
# use computed property if region annotation does not exist
# i.e. after creating a node
region_id = obj.osfstorage_region._id
return region_id
def get_wiki_enabled(self, obj):
return obj.has_wiki_addon if hasattr(obj, 'has_wiki_addon') else obj.has_addon('wiki')
def create(self, validated_data):
request = self.context['request']
user = request.user
Node = apps.get_model('osf.Node')
tag_instances = []
affiliated_institutions = None
region_id = None
license_details = None
if 'affiliated_institutions' in validated_data:
affiliated_institutions = validated_data.pop('affiliated_institutions')
if 'region' in validated_data:
region_id = validated_data.pop('region')
if 'license_type' in validated_data or 'license' in validated_data:
try:
license_details = get_license_details(None, validated_data)
except ValidationError as e:
raise InvalidModelValueError(detail=str(e.messages[0]))
validated_data.pop('license', None)
validated_data.pop('license_type', None)
if 'tags' in validated_data:
tags = validated_data.pop('tags')
for tag in tags:
tag_instance, created = Tag.objects.get_or_create(name=tag, defaults=dict(system=False))
tag_instances.append(tag_instance)
if 'template_from' in validated_data:
template_from = validated_data.pop('template_from')
template_node = Node.load(template_from)
if template_node is None:
raise exceptions.NotFound
if not template_node.has_permission(user, osf_permissions.READ, check_parent=False):
raise exceptions.PermissionDenied
validated_data.pop('creator')
changed_data = {template_from: validated_data}
node = template_node.use_as_template(auth=get_user_auth(request), changes=changed_data)
else:
node = Node(**validated_data)
try:
node.save()
except ValidationError as e:
raise InvalidModelValueError(detail=e.messages[0])
if affiliated_institutions:
new_institutions = [{'_id': institution} for institution in affiliated_institutions]
update_institutions(node, new_institutions, user, post=True)
node.save()
if len(tag_instances):
for tag in tag_instances:
node.tags.add(tag)
if is_truthy(request.GET.get('inherit_contributors')) and validated_data['parent'].has_permission(user, osf_permissions.WRITE):
auth = get_user_auth(request)
parent = validated_data['parent']
contributors = []
for contributor in parent.contributor_set.exclude(user=user):
contributors.append({
'user': contributor.user,
'permissions': contributor.permission,
'visible': contributor.visible,
})
if not contributor.user.is_registered:
try:
node.add_unregistered_contributor(
fullname=contributor.user.fullname, email=contributor.user.email, auth=auth,
permissions=contributor.permission, existing_user=contributor.user,
)
except ValidationError as e:
raise InvalidModelValueError(detail=list(e)[0])
node.add_contributors(contributors, auth=auth, log=True, save=True)
for group in parent.osf_groups:
if group.is_manager(user):
node.add_osf_group(group, group.get_permission_to_node(parent), auth=auth)
if is_truthy(request.GET.get('inherit_subjects')) and validated_data['parent'].has_permission(user, osf_permissions.WRITE):
parent = validated_data['parent']
node.subjects.add(parent.subjects.all())
node.save()
if license_details:
try:
node.set_node_license(
{
'id': license_details.get('id') if license_details.get('id') else 'NONE',
'year': license_details.get('year'),
'copyrightHolders': license_details.get('copyrightHolders') or license_details.get('copyright_holders', []),
},
auth=get_user_auth(request),
save=True,
)
except ValidationError as e:
raise InvalidModelValueError(detail=str(e.message))
if not region_id:
region_id = self.context.get('region_id')
if region_id:
node_settings = node.get_addon('osfstorage')
node_settings.region_id = region_id
node_settings.save()
return node
def update(self, node, validated_data):
"""Update instance with the validated data. Requires
the request to be in the serializer context.
"""
assert isinstance(node, AbstractNode), 'node must be a Node'
user = self.context['request'].user
auth = get_user_auth(self.context['request'])
if validated_data:
if 'custom_citation' in validated_data:
node.update_custom_citation(validated_data.pop('custom_citation'), auth)
if 'tags' in validated_data:
new_tags = set(validated_data.pop('tags', []))
node.update_tags(new_tags, auth=auth)
if 'region' in validated_data:
validated_data.pop('region')
if 'license_type' in validated_data or 'license' in validated_data:
license_details = get_license_details(node, validated_data)
validated_data['node_license'] = license_details
if 'affiliated_institutions' in validated_data:
institutions_list = validated_data.pop('affiliated_institutions')
new_institutions = [{'_id': institution} for institution in institutions_list]
update_institutions(node, new_institutions, user)
node.save()
if 'subjects' in validated_data:
subjects = validated_data.pop('subjects', None)
self.update_subjects(node, subjects, auth)
try:
node.update(validated_data, auth=auth)
except ValidationError as e:
raise InvalidModelValueError(detail=e.message)
except PermissionsError:
raise exceptions.PermissionDenied
except NodeUpdateError as e:
raise exceptions.ValidationError(detail=e.reason)
except NodeStateError as e:
raise InvalidModelValueError(detail=str(e))
return node
class NodeAddonSettingsSerializerBase(JSONAPISerializer):
class Meta:
@staticmethod
def get_type(request):
return get_kebab_snake_case_field(request.version, 'node-addons')
id = ser.CharField(source='config.short_name', read_only=True)
node_has_auth = ser.BooleanField(source='has_auth', read_only=True)
configured = ser.BooleanField(read_only=True)
external_account_id = ser.CharField(source='external_account._id', required=False, allow_null=True)
folder_id = ser.CharField(required=False, allow_null=True)
folder_path = ser.CharField(required=False, allow_null=True)
# Forward-specific
label = ser.CharField(required=False, allow_blank=True)
url = ser.URLField(required=False, allow_blank=True)
links = LinksField({
'self': 'get_absolute_url',
})
def get_absolute_url(self, obj):
kwargs = self.context['request'].parser_context['kwargs']
if 'provider' not in kwargs or (obj and obj.config.short_name != kwargs.get('provider')):
kwargs.update({'provider': obj.config.short_name})
return absolute_reverse(
'nodes:node-addon-detail',
kwargs=kwargs,
)
def create(self, validated_data):
auth = Auth(self.context['request'].user)
node = self.context['view'].get_node()
addon = self.context['request'].parser_context['kwargs']['provider']
return node.get_or_add_addon(addon, auth=auth)
class ForwardNodeAddonSettingsSerializer(NodeAddonSettingsSerializerBase):
def update(self, instance, validated_data):
request = self.context['request']
user = request.user
auth = Auth(user)
set_url = 'url' in validated_data
set_label = 'label' in validated_data
url_changed = False
url = validated_data.get('url')
label = validated_data.get('label')
if set_url and not url and label:
raise exceptions.ValidationError(detail='Cannot set label without url')
if not instance:
node = self.context['view'].get_node()
instance = node.get_or_add_addon('forward', auth)
if instance and instance.url:
# url required, label optional
if set_url and not url:
instance.reset()
elif set_url and url:
instance.url = url
url_changed = True
if set_label:
instance.label = label
elif instance and not instance.url:
instance.url = url
instance.label = label
url_changed = True
try:
instance.save(request=request)
except ValidationError as e:
raise exceptions.ValidationError(detail=str(e))
if url_changed:
# add log here because forward architecture isn't great
# TODO [OSF-6678]: clean this up
instance.owner.add_log(
action='forward_url_changed',
params=dict(
node=instance.owner._id,
project=instance.owner.parent_id,
forward_url=instance.url,
),
auth=auth,
save=True,
)
return instance
class NodeAddonSettingsSerializer(NodeAddonSettingsSerializerBase):
def check_for_update_errors(self, node_settings, folder_info, external_account_id):
if (not node_settings.has_auth and folder_info and not external_account_id):
raise Conflict('Cannot set folder without authorization')
def get_account_info(self, data):
try:
external_account_id = data['external_account']['_id']
set_account = True
except KeyError:
external_account_id = None
set_account = False
return set_account, external_account_id
def get_folder_info(self, data, addon_name):
try:
folder_info = data['folder_id']
set_folder = True
except KeyError:
folder_info = None
set_folder = False
if addon_name == 'googledrive':
folder_id = folder_info
try:
folder_path = data['folder_path']
except KeyError:
folder_path = None