-
Notifications
You must be signed in to change notification settings - Fork 356
Expand file tree
/
Copy pathviews.py
More file actions
1062 lines (865 loc) · 38 KB
/
views.py
File metadata and controls
1062 lines (865 loc) · 38 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
from datetime import datetime
from enum import Enum
import pytz
from django.db import transaction
from django.contrib import messages
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.exceptions import PermissionDenied, ValidationError
from django.db.models import F, Case, When, IntegerField
from django.http import HttpResponse
from django.shortcuts import redirect, reverse, get_object_or_404
from django.urls import NoReverseMatch
from django.urls import reverse_lazy
from django.utils import timezone
from django.views.generic import (
View,
FormView,
ListView,
TemplateView
)
from django.core.paginator import Paginator, InvalidPage
from admin.base.forms import GuidForm
from admin.base.utils import change_embargo_date
from admin.base.views import GuidView
from admin.nodes.forms import AddSystemTagForm, RegistrationDateForm
from admin.notifications.views import delete_selected_notifications
from api.caching.tasks import update_storage_usage_cache
from api.share.utils import update_share
from framework import status
from osf.exceptions import NodeStateError, RegistrationStuckError
from osf.management.commands.change_node_region import _update_schema_meta
from osf.models import (
Guid,
OSFUser,
NodeLog,
AbstractNode,
Registration,
RegistrationProvider,
RegistrationApproval,
SpamStatus,
TrashedFile
)
from osf.models.sanctions import Embargo
from osf.models.admin_log_entry import (
update_admin_log,
NODE_REMOVED,
NODE_RESTORED,
CONTRIBUTOR_REMOVED,
CONFIRM_SPAM,
CONFIRM_HAM,
UNFLAG_SPAM,
REINDEX_SHARE,
REINDEX_ELASTIC,
)
from osf.utils.permissions import ADMIN, API_CONTRIBUTOR_PERMISSIONS
from scripts.approve_registrations import approve_past_pendings
from website import settings, search
from website.archiver.tasks import force_archive
class NodeMixin(PermissionRequiredMixin):
def get_object(self):
return AbstractNode.objects.filter(
guids___id=self.kwargs['guid']
).annotate(
guid=F('guids___id'),
public_cap=Case(
When(
custom_storage_usage_limit_public=None,
then=settings.STORAGE_LIMIT_PUBLIC,
),
When(
custom_storage_usage_limit_public__gt=0,
then=F('custom_storage_usage_limit_public'),
),
output_field=IntegerField()
),
private_cap=Case(
When(
custom_storage_usage_limit_private=None,
then=settings.STORAGE_LIMIT_PRIVATE,
),
When(
custom_storage_usage_limit_private__gt=0,
then=F('custom_storage_usage_limit_private'),
),
output_field=IntegerField()
)
).get()
def get_success_url(self):
return reverse('nodes:node', kwargs={'guid': self.kwargs['guid']})
class RegistrationUpdateDateView(NodeMixin, View):
permission_required = 'osf.change_node'
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
form = RegistrationDateForm(request.POST)
if form.is_valid():
last_date = node.registered_date
new_date = form.cleaned_data['registered_date']
node.registered_date = new_date
node.created = new_date
node.save()
node.add_log(
action=NodeLog.REGISTRATION_DATE_UPDATED,
auth=request,
params={
'last_date': str(last_date),
'new_date': str(new_date)
},
log_date=timezone.now(),
should_hide=False,
)
messages.success(request, 'Registration date updated successfully.')
else:
messages.error(request, 'Please enter a valid date.')
return redirect(self.get_success_url())
class NodeView(NodeMixin, GuidView):
""" Allows authorized users to view node info.
"""
template_name = 'nodes/node.html'
permission_required = 'osf.view_node'
raise_exception = True
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
node = self.get_object()
if isinstance(node, Registration):
context['registration_date_form'] = RegistrationDateForm(initial={'registered_date': node.registered_date})
children = node.get_nodes(is_node_link=False)
# Annotate guid because django templates prohibit accessing attributes that start with underscores
children = AbstractNode.objects.filter(
id__in=[child.id for child in children]
).prefetch_related('guids').annotate(guid=F('guids___id'))
context.update({
'SPAM_STATUS': SpamStatus,
'STORAGE_LIMITS': settings.StorageLimits,
'node': node,
# to edit contributors we should have guid as django prohibits _id usage as it starts with an underscore
'annotated_contributors': node.contributor_set.prefetch_related('user__guids').annotate(
guid=F('user__guids___id')),
'children': children,
'permissions': API_CONTRIBUTOR_PERMISSIONS,
'has_update_permission': self.request.user.has_perm('osf.change_node'),
})
return context
class NodeRemoveNotificationView(View):
def post(self, request, *args, **kwargs):
selected_ids = request.POST.getlist('selected_notifications')
if selected_ids:
delete_selected_notifications(selected_ids)
messages.success(request, 'Selected notifications were successfully deleted.')
else:
messages.error(request, 'No notifications selected for deletion.')
return redirect('nodes:node', guid=kwargs.get('guid'))
class NodeUpdateModerationStateView(View):
def post(self, request, *args, **kwargs):
guid = kwargs.get('guid')
node = AbstractNode.load(guid)
node.update_moderation_state()
messages.success(request, 'Moderation state successfully updated.')
return redirect('nodes:node', guid=kwargs.get('guid'))
class NodeSearchView(PermissionRequiredMixin, FormView):
""" Allows authorized users to search for a node by it's guid.
"""
template_name = 'nodes/search.html'
permission_required = 'osf.view_node'
raise_exception = True
form_class = GuidForm
success_url = reverse_lazy('nodes:search')
def form_valid(self, form):
guid = form.cleaned_data['guid']
if guid:
try:
return redirect(reverse('nodes:node', kwargs={'guid': guid}))
except NoReverseMatch as e:
messages.error(self.request, str(e))
return super().form_valid(form)
class NodeRemoveContributorView(NodeMixin, View):
""" Allows authorized users to remove contributors from nodes.
"""
permission_required = ('osf.view_node', 'osf.change_node')
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
user = OSFUser.objects.get(id=self.kwargs.get('user_id'))
if node.has_permission(user, ADMIN) and not node._get_admin_contributors_query(node._contributors.all(),
require_active=False).exclude(
user=user).exists():
messages.error(self.request, 'Must be at least one admin on this node.')
return redirect(self.get_success_url())
if node.remove_contributor(user, None, log=False, _force=True):
update_admin_log(
user_id=self.request.user.id,
object_id=node.pk,
object_repr='Contributor',
message=f'User {user.pk} removed from {node.__class__.__name__.lower()} {node.pk}.',
action_flag=CONTRIBUTOR_REMOVED
)
# Log invisibly on the OSF.
self.add_contributor_removed_log(node, user)
return redirect(self.get_success_url())
def add_contributor_removed_log(self, node, user):
NodeLog(
action=NodeLog.CONTRIB_REMOVED,
user=None,
params={
'project': node.parent_id,
'node': node.pk,
'contributors': user.pk
},
date=timezone.now(),
should_hide=True,
).save()
class NodeUpdatePermissionsView(NodeMixin, View):
permission_required = ('osf.view_node', 'osf.change_node')
raise_exception = True
redirect_view = NodeRemoveContributorView
def post(self, request, *args, **kwargs):
data = dict(request.POST)
contributor_id_to_remove = data.get('remove-user')
resource = self.get_object()
if contributor_id_to_remove:
contributor_id = contributor_id_to_remove[0]
# html renders form into form incorrectly,
# so this view handles contributors deletion and permissions update
return self.redirect_view(
request=request,
kwargs={'guid': resource.guid, 'user_id': contributor_id}
).post(request, user_id=contributor_id)
new_emails_to_add = data.get('new-emails', [])
new_permissions_to_add = data.get('new-permissions', [])
new_permission_indexes_to_remove = []
for email, permission in zip(new_emails_to_add, new_permissions_to_add):
contributor_user = OSFUser.objects.filter(emails__address=email.lower()).first()
if not contributor_user:
new_permission_indexes_to_remove.append(new_emails_to_add.index(email))
messages.error(self.request, f'Email {email} is not registered in OSF.')
continue
elif resource.is_contributor(contributor_user):
new_permission_indexes_to_remove.append(new_emails_to_add.index(email))
messages.error(self.request, f'User with email {email} is already a contributor.')
continue
resource.add_contributor_registered_or_not(
auth=request,
user_id=contributor_user._id,
permissions=permission,
notification_type=None
)
messages.success(self.request, f'User with email {email} was successfully added.')
# should remove permissions of invalid emails because
# admin can make all existing contributors non admins
# and enter an invalid email with the only admin permission
for permission_index in new_permission_indexes_to_remove:
new_permissions_to_add.pop(permission_index)
updated_permissions = data.get('updated-permissions', [])
all_permissions = updated_permissions + new_permissions_to_add
has_admin = list(filter(lambda permission: ADMIN in permission, all_permissions))
if not has_admin:
messages.error(self.request, 'Must be at least one admin on this node.')
return redirect(self.get_success_url())
for contributor_permission in updated_permissions:
guid, permission = contributor_permission.split('-')
user = OSFUser.load(guid)
resource.update_contributor(
user,
permission,
resource.get_visible(user),
request,
save=True,
skip_permission=True
)
return redirect(self.get_success_url())
class NodeDeleteView(NodeMixin, View):
""" Allows authorized users to mark nodes as deleted.
"""
permission_required = ('osf.view_node', 'osf.delete_node')
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
if node.is_deleted:
node.is_deleted = False
node.deleted_date = None
node.deleted = None
update_admin_log(
user_id=self.request.user.id,
object_id=node.pk,
object_repr='Node',
message=f'Node {node.pk} restored.',
action_flag=NODE_RESTORED
)
NodeLog(
action=NodeLog.NODE_CREATED,
user=None,
params={
'project': node.parent_id,
},
date=timezone.now(),
should_hide=True,
).save()
else:
node.is_deleted = True
node.deleted = timezone.now()
node.deleted_date = node.deleted
update_admin_log(
user_id=self.request.user.id,
object_id=node.pk,
object_repr='Node',
message=f'Node {node.pk} removed.',
action_flag=NODE_REMOVED
)
NodeLog(
action=NodeLog.NODE_REMOVED,
user=None,
params={
'project': node.parent_id,
},
date=timezone.now(),
should_hide=True,
).save()
node.save()
return redirect(self.get_success_url())
class AdminNodeLogView(NodeMixin, ListView):
""" Allows authorized users to view node logs.
"""
template_name = 'nodes/node_logs.html'
paginate_by = 10
paginate_orphans = 1
ordering = 'date'
permission_required = 'osf.view_node'
raise_exception = True
def get_queryset(self):
return self.get_object().logs.order_by('created')
def get_context_data(self, **kwargs):
query_set = self.get_queryset()
page_size = self.get_paginate_by(query_set)
paginator, page, query_set, is_paginated = self.paginate_queryset(
query_set, page_size)
return {
'logs': query_set,
'page': page,
}
class AdminNodeSchemaResponseView(NodeMixin, ListView):
""" Allows authorized users to view schema response info.
"""
template_name = 'schema_response/schema_response_list.html'
paginate_by = 10
paginate_orphans = 1
ordering = 'date'
permission_required = 'osf.view_schema_response'
raise_exception = True
def get_queryset(self):
return self.get_object().schema_responses.all()
def get_context_data(self, **kwargs):
return {'schema_responses': self.get_queryset()}
class RegistrationListView(PermissionRequiredMixin, ListView):
""" Allow authorized users to view the list of registrations of a node.
"""
template_name = 'nodes/registration_list.html'
paginate_by = 10
paginate_orphans = 1
ordering = 'created'
permission_required = 'osf.view_registration'
raise_exception = True
def get_queryset(self):
# Django template does not like attributes with underscores for some reason, so we annotate.
return Registration.objects.all().annotate(guid=F('guids___id')).order_by(self.ordering)
def get_context_data(self, **kwargs):
query_set = self.get_queryset()
page_size = self.get_paginate_by(query_set)
paginator, page, query_set, is_paginated = self.paginate_queryset(query_set, page_size)
return {
'nodes': query_set,
'page': page,
}
class StuckRegistrationListView(RegistrationListView):
""" Allows authorized users to view a list of registrations that have been archiving files for more than 24 hours.
"""
def get_queryset(self):
# Django template does not like attributes with underscores for some reason, so we annotate.
return Registration.find_failed_registrations().annotate(guid=F('guids___id'))
class RegistrationBacklogListView(RegistrationListView):
""" List view that filters by registrations the haven't been archived at archive.org/
"""
def get_queryset(self):
# Django template does not like attributes with underscores for some reason, so we annotate.
return Registration.find_ia_backlog().annotate(guid=F('guids___id'))
class DoiBacklogListView(RegistrationListView):
""" Allows authorized users to view a list of registrations that have not yet been assigned a doi.
"""
def get_queryset(self):
# Django template does not like attributes with underscores for some reason, so we annotate.
return Registration.find_doi_backlog().annotate(guid=F('guids___id'))
class ApprovalBacklogListView(RegistrationListView):
""" Allows authorized users to view a list of registrations that have not yet been approved.
"""
template_name = 'nodes/registration_approval_list.html'
permission_required = 'osf.view_registrationapproval'
def get_queryset(self):
# Django template does not like attributes with underscores for some reason, so we annotate.
return RegistrationApproval.find_approval_backlog()
def get_context_data(self, **kwargs):
queryset = self.get_queryset()
page_size = self.get_paginate_by(queryset)
paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
return {
'queryset': queryset,
'page': page,
}
class EmbargoReportView(PermissionRequiredMixin, TemplateView):
"""Report view for inspecting current and overdue embargoed registrations.
Shows:
- pending embargoes that should have been activated
- active embargoes that are past their end date
- upcoming active embargoes
"""
template_name = 'nodes/embargo_report.html'
permission_required = 'osf.view_registration'
raise_exception = True
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
pending_embargoes = Embargo.objects.pending_embargoes().select_related('initiated_by')
active_embargoes = Embargo.objects.active_embargoes().select_related('initiated_by')
pending_overdue_embargoes = [
embargo for embargo in pending_embargoes
if embargo.should_be_embargoed
]
overdue_embargoes = [
embargo for embargo in active_embargoes
if embargo.should_be_completed
]
upcoming_queryset = active_embargoes.filter(
end_date__gte=timezone.now(),
).order_by('end_date')
page_number = self.request.GET.get('page') or 1
paginator = Paginator(upcoming_queryset, 10)
try:
upcoming_page = paginator.page(page_number)
except InvalidPage:
upcoming_page = paginator.page(1)
context.update({
'now': timezone.now(),
'pending_overdue_embargoes': pending_overdue_embargoes,
'overdue_embargoes': overdue_embargoes,
'upcoming_embargoes': upcoming_page.object_list,
'upcoming_page': upcoming_page,
})
return context
class ConfirmApproveBacklogView(RegistrationListView):
template_name = 'nodes/registration_approval_list.html'
permission_required = 'osf.view_registrationapproval'
def get_success_url(self):
return reverse('nodes:approval-backlog-list')
def post(self, request, *args, **kwargs):
data = dict(request.POST)
data.pop('csrfmiddlewaretoken', None)
approvals = RegistrationApproval.objects.filter(_id__in=list(data.keys()))
approve_past_pendings(approvals, dry_run=False)
return redirect(self.get_success_url())
class RegistrationUpdateEmbargoView(NodeMixin, View):
""" Allows authorized users to update the embargo of a registration.
"""
permission_required = ('osf.change_node')
raise_exception = True
def post(self, request, *args, **kwargs):
end_date = request.POST.get('date')
user = request.user
registration = self.get_object()
try:
end_date = pytz.utc.localize(datetime.strptime(end_date, '%m/%d/%Y'))
change_embargo_date(registration, user, end_date)
except ValueError:
return HttpResponse('Please enter a valid date.', status=400)
except ValidationError as e:
return HttpResponse(e, status=400)
except PermissionDenied as e:
return HttpResponse(e, status=403)
return redirect(self.get_success_url())
class RegistrationChangeProviderView(NodeMixin, View):
""" Allows authorized users to update provider of a registration.
"""
permission_required = ('osf.change_node')
def post(self, request, *args, **kwargs):
provider_id = int(request.POST.get('provider_id'))
provider = get_object_or_404(RegistrationProvider, pk=provider_id)
registration = self.get_object()
try:
provider.validate_schema(registration.registration_schema)
registration.provider = provider
registration.save()
except ValidationError as exc:
messages.error(request, str(exc))
else:
messages.success(request, 'Provider successfully changed.')
return redirect(self.get_success_url())
class NodeSpamList(PermissionRequiredMixin, ListView):
""" Allows authorized users to view a list of nodes that have a particular spam status.
"""
SPAM_STATE = SpamStatus.UNKNOWN
paginate_by = 25
paginate_orphans = 1
ordering = 'created'
permission_required = 'osf.view_spam'
raise_exception = True
def get_queryset(self):
return AbstractNode.objects.filter(
spam_status=self.SPAM_STATE
).order_by(
self.ordering
).annotate(guid=F('guids___id'))
def get_context_data(self, **kwargs):
query_set = self.get_queryset()
page_size = self.get_paginate_by(query_set)
paginator, page, query_set, is_paginated = self.paginate_queryset(query_set, page_size)
return {'nodes': query_set, 'page': page}
class NodeFlaggedSpamList(NodeSpamList, View):
""" Allows authorized users to mark users flagged as spam as either spam or ham, or they can simply remove the flag.
"""
template_name = 'nodes/flagged_spam_list.html'
SPAM_STATE = SpamStatus.FLAGGED
def post(self, request, *args, **kwargs):
if not request.user.has_perm('osf.mark_spam'):
raise PermissionDenied("You don't have permission to update this user's spam status.")
data = dict(request.POST)
action = data.pop('action')[0]
data.pop('csrfmiddlewaretoken', None)
nodes = AbstractNode.objects.filter(id__in=list(data.keys()))
if action == 'spam':
for node in nodes:
try:
node.confirm_spam(save=True)
update_admin_log(
user_id=self.request.user.id,
object_id=node.id,
object_repr='Node',
message=f'Confirmed SPAM: {node._id}',
action_flag=CONFIRM_SPAM
)
except NodeStateError as e:
messages.error(self.request, e)
if action == 'ham':
for node in nodes:
node.confirm_ham(save=True)
update_admin_log(
user_id=self.request.user.id,
object_id=node.id,
object_repr='User',
message=f'Confirmed HAM: {node._id}',
action_flag=CONFIRM_HAM
)
if action == 'unflag':
for node in nodes:
node.spam_status = None
node.save()
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Confirmed Unflagged: {node._id}',
action_flag=UNFLAG_SPAM
)
for node in nodes:
if node.get_identifier_value('doi'):
node.request_identifier_update(category='doi')
return redirect('nodes:flagged-spam')
class NodeKnownSpamList(NodeSpamList):
""" Allows authorized users to view a list of users that have a spam status of being spam.
"""
template_name = 'nodes/known_spam_list.html'
SPAM_STATE = SpamStatus.SPAM
class NodeKnownHamList(NodeSpamList):
""" Allows authorized users to view a list of users that have a spam status of being ham (non-spam).
"""
template_name = 'nodes/known_spam_list.html'
SPAM_STATE = SpamStatus.HAM
class NodeConfirmSpamView(NodeMixin, View):
""" Allows authorized users to mark a particular node as spam.
"""
permission_required = 'osf.mark_spam'
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
node.confirm_spam(save=True)
if node.get_identifier_value('doi'):
node.request_identifier_update(category='doi')
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Confirmed SPAM: {node._id}',
action_flag=CONFIRM_SPAM
)
return redirect(self.get_success_url())
class NodeConfirmHamView(NodeMixin, View):
""" Allows authorized users to mark a particular node as ham.
"""
permission_required = 'osf.mark_spam'
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
node.confirm_ham(save=True)
if node.get_identifier_value('doi'):
node.request_identifier_update(category='doi')
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Confirmed HAM: {node._id}',
action_flag=CONFIRM_HAM
)
return redirect(self.get_success_url())
class NodeConfirmUnflagView(NodeMixin, View):
""" Allows authorized users to remove the spam flag from a node.
"""
permission_required = 'osf.mark_spam'
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
node.spam_status = None
node.save()
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Confirmed Unflagged: {node._id}',
action_flag=UNFLAG_SPAM
)
return redirect(self.get_success_url())
class NodeReindexShare(NodeMixin, View):
""" Allows an authorized user to reindex a node in SHARE.
"""
permission_required = 'osf.mark_spam'
raise_exception = True
def post(self, request, *args, **kwargs):
node = self.get_object()
update_share(node)
messages.success(
request,
'Reindex request has been sent to SHARE. '
'Changes typically appear in OSF Search within about 5 minutes, '
'subject to background queue load and SHARE availability.'
)
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Node Reindexed (SHARE): {node._id}',
action_flag=REINDEX_SHARE
)
return redirect(self.get_success_url())
class NodeReindexElastic(NodeMixin, View):
""" Allows an authorized user to reindex a node in ElasticSearch.
"""
permission_required = 'osf.mark_spam'
def post(self, request, *args, **kwargs):
node = self.get_object()
search.search.update_node(node, bulk=False, async_update=False)
update_admin_log(
user_id=self.request.user.id,
object_id=node._id,
object_repr='Node',
message=f'Node Reindexed (Elastic): {node._id}',
action_flag=REINDEX_ELASTIC
)
return redirect(self.get_success_url())
class NodeModifyStorageUsage(NodeMixin, View):
""" Allows an authorized user to view a node's storage usage info and set their public/private storage cap.
"""
permission_required = 'osf.change_node'
def post(self, request, *args, **kwargs):
node = self.get_object()
new_private_cap = request.POST.get('private-cap-input')
new_public_cap = request.POST.get('public-cap-input')
node_private_cap = node.custom_storage_usage_limit_private or settings.STORAGE_LIMIT_PRIVATE
node_public_cap = node.custom_storage_usage_limit_public or settings.STORAGE_LIMIT_PUBLIC
if float(new_private_cap) != node_private_cap:
node.custom_storage_usage_limit_private = new_private_cap
if float(new_public_cap) != node_public_cap:
node.custom_storage_usage_limit_public = new_public_cap
node.save()
return redirect(self.get_success_url())
class NodeRecalculateStorage(NodeMixin, View):
""" Allows an authorized user to manually set a node's storage cache by recalculating the value.
"""
permission_required = 'osf.change_node'
def post(self, request, *args, **kwargs):
node = self.get_object()
update_storage_usage_cache(node.id, node._id)
return redirect(self.get_success_url())
class NodeMakePrivate(NodeMixin, View):
""" Allows an authorized user to manually make a public node private.
"""
permission_required = 'osf.change_node'
def post(self, request, *args, **kwargs):
node = self.get_object()
node.is_public = False
# After set permissions callback
for addon in node.get_addons():
message = addon.after_set_privacy(node, 'private')
if message:
status.push_status_message(message, kind='info', trust=False)
if node.get_identifier_value('doi'):
node.request_identifier_update(category='doi')
node.save()
return redirect(self.get_success_url())
class NodeMakePublic(NodeMixin, View):
""" Allows an authorized user to manually make a public node private.
"""
permission_required = 'osf.change_node'
def post(self, request, *args, **kwargs):
node = self.get_object()
try:
node.set_privacy('public')
except NodeStateError as e:
messages.error(request, str(e))
return redirect(self.get_success_url())
class NodeRemoveFileView(NodeMixin, View):
""" Allows an authorized user to remove file from node.
"""
permission_required = 'osf.change_node'
def post(self, request, *args, **kwargs):
def _remove_file_from_schema_response_blocks(registration, removed_file_id):
file_input_keys = registration.registration_schema.schema_blocks.filter(
block_type='file-input'
).values_list('registration_response_key', flat=True)
for schema_response in registration.schema_responses.all():
for block in schema_response.response_blocks.filter(schema_key__in=file_input_keys):
if not block.response:
continue
block.response = [entry for entry in block.response if entry.get('file_id') not in removed_file_id]
block.save()
node = self.get_object()
guid_id = request.POST.get('remove-file-guid', '').strip()
guid = Guid.load(guid_id)
# delete file from registration and metadata and keep it for original project
if guid and (file := guid.referent) and (file.target == node) and not isinstance(file, TrashedFile):
with transaction.atomic():
file.delete()
_update_schema_meta(file.target)
_remove_file_from_schema_response_blocks(node, [file._id, file.copied_from._id])
return redirect(self.get_success_url())
class RemoveStuckRegistrationsView(NodeMixin, View):
""" Allows an authorized user to remove a registrations if it's stuck in the archiving process.
"""
permission_required = ('osf.view_node', 'osf.change_node')
def post(self, request, *args, **kwargs):
stuck_reg = self.get_object()
if Registration.find_failed_registrations().filter(id=stuck_reg.id).exists():
stuck_reg.delete_registration_tree(save=True)
messages.success(request, 'The registration has been deleted')
else:
messages.error(request, 'This registration may not technically be stuck,'
' if the problem persists get a developer to fix it.')
return redirect(self.get_success_url())
class CheckArchiveStatusRegistrationsView(NodeMixin, View):
"""Allows an authorized user to check a registration archive status.
"""
permission_required = ('osf.view_node', 'osf.change_node')
def get(self, request, *args, **kwargs):
# Prevents circular imports that cause admin app to hang at startup
from osf.management.commands.force_archive import check, DEFAULT_PERMISSIBLE_ADDONS
registration = self.get_object()
if registration.archived:
messages.success(request, f"Registration {registration._id} is archived.")
return redirect(self.get_success_url())
addons = set(DEFAULT_PERMISSIBLE_ADDONS)
for reg in registration.node_and_primary_descendants():
addons.update(reg.registered_from.get_addon_names())
try:
archive_status = check(registration, permissible_addons=addons, verify_addons=False)
messages.success(request, archive_status)
except RegistrationStuckError as exc:
messages.error(request, str(exc))
return redirect(self.get_success_url())
class CollisionMode(Enum):
NONE: str = 'none'
SKIP: str = 'skip'
DELETE: str = 'delete'
class ForceArchiveRegistrationsView(NodeMixin, View):
"""Allows an authorized user to force archive registration.
"""
permission_required = ('osf.view_node', 'osf.change_node')
def post(self, request, *args, **kwargs):
# Prevents circular imports that cause admin app to hang at startup
from osf.management.commands.force_archive import verify, DEFAULT_PERMISSIBLE_ADDONS
from osf.models.admin_log_entry import update_admin_log, MANUAL_ARCHIVE_RESTART
registration = self.get_object()
force_archive_params = request.POST
collision_mode = force_archive_params.get('collision_mode', CollisionMode.NONE.value)
delete_collision = CollisionMode.DELETE.value == collision_mode
skip_collision = CollisionMode.SKIP.value == collision_mode
allow_unconfigured = force_archive_params.get('allow_unconfigured', False)
addons = set(DEFAULT_PERMISSIBLE_ADDONS)
for reg in registration.node_and_primary_descendants():
addons.update(reg.registered_from.get_addon_names())
# No need to verify addons during force archive,
# because we fetched all permissible addons above
verify_addons = False
if force_archive_params.get('dry_mode', False):
# For dry mode, verify synchronously to provide immediate feedback
try:
verify(registration, permissible_addons=addons, verify_addons=verify_addons, raise_error=True)
messages.success(request, f"Registration {registration._id} can be archived.")
except ValidationError as exc:
messages.error(request, str(exc))
return redirect(self.get_success_url())
else:
try:
update_admin_log(
user_id=request.user.id,
object_id=registration.pk,
object_repr=str(registration),
message=f'Manual archive restart initiated for registration {registration._id}',
action_flag=MANUAL_ARCHIVE_RESTART
)
# For actual archiving, skip synchronous verification to avoid 502 timeouts
# Verification will be performed asynchronously in the task
force_archive_task = force_archive.delay(
str(registration._id),
permissible_addons=list(addons),
allow_unconfigured=allow_unconfigured,