-
Notifications
You must be signed in to change notification settings - Fork 321
/
sanctions.py
1005 lines (838 loc) · 39 KB
/
sanctions.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.apps import apps
from django.utils import timezone
from django.conf import settings
from django.db import models
from osf.utils.fields import NonNaiveDateTimeField
from framework.auth import Auth
from framework.exceptions import PermissionsError
from website import settings as osf_settings
from website import mails
from osf.exceptions import (
InvalidSanctionRejectionToken,
InvalidSanctionApprovalToken,
NodeStateError,
)
from .base import BaseModel, ObjectIDMixin
from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField
from osf.utils import tokens
from osf.utils.machines import ApprovalsMachine
from osf.utils.workflows import ApprovalStates, SanctionTypes
VIEW_PROJECT_URL_TEMPLATE = osf_settings.DOMAIN + '{node_id}/'
class Sanction(ObjectIDMixin, BaseModel):
"""Sanction class is a generic way to track approval states"""
# Neither approved not cancelled
UNAPPROVED = ApprovalStates.UNAPPROVED.db_name
# Has approval
APPROVED = ApprovalStates.APPROVED.db_name
# Rejected by at least one contributor
REJECTED = ApprovalStates.REJECTED.db_name
# Embargo has been completed
COMPLETED = ApprovalStates.COMPLETED.db_name
# Approved by admins but pending moderator approval/rejection
PENDING_MODERATION = ApprovalStates.PENDING_MODERATION.db_name
# Rejected by a moderator
MODERATOR_REJECTED = ApprovalStates.MODERATOR_REJECTED.db_name
SANCTION_TYPE = SanctionTypes.UNDEFINED
DISPLAY_NAME = 'Sanction'
# SHORT_NAME must correspond with the associated foreign field to query against,
# e.g. Node.find_one(Q(sanction.SHORT_NAME, 'eq', sanction))
SHORT_NAME = 'sanction'
ACTION_NOT_AUTHORIZED_MESSAGE = 'This user is not authorized to {ACTION} this {DISPLAY_NAME}'
APPROVAL_INVALID_TOKEN_MESSAGE = 'Invalid approval token provided for this {DISPLAY_NAME}.'
REJECTION_INVALID_TOKEN_MESSAGE = 'Invalid rejection token provided for this {DISPLAY_NAME}.'
# Controls whether or not the Sanction needs unanimous approval or just a single approval
ANY = 'any'
UNANIMOUS = 'unanimous'
mode = UNANIMOUS
# Sanction subclasses must have an initiated_by field
# initiated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
# Expanded: Dictionary field mapping admin IDs their approval status and relevant tokens:
# {
# 'b3k97': {
# 'has_approved': False,
# 'approval_token': 'Pew7wj1Puf7DENUPFPnXSwa1rf3xPN',
# 'rejection_token': 'TwozClTFOic2PYxHDStby94bCQMwJy'}
# }
approval_state = DateTimeAwareJSONField(default=dict, blank=True)
# Expiration date-- Sanctions in the UNAPPROVED state that are older than their end_date
# are automatically made ACTIVE by a daily cron job
# Use end_date=None for a non-expiring Sanction
end_date = NonNaiveDateTimeField(null=True, blank=True, default=None)
initiation_date = NonNaiveDateTimeField(default=timezone.now, null=True, blank=True)
state = models.CharField(choices=ApprovalStates.char_field_choices(),
default=UNAPPROVED,
max_length=255)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.approvals_machine = ApprovalsMachine(
model=self,
state_property_name='approval_stage',
active_state=self.approval_stage
)
def __str__(self):
return f'<{self.__class__.__name__}(end_date={self.end_date!r}) with _id {self._id!r}>'
@property
def is_pending_approval(self):
'''The sanction is awaiting admin approval.'''
return self.approval_stage is ApprovalStates.UNAPPROVED
@property
def is_approved(self):
'''The sanction has received all required admin and moderator approvals.'''
return self.approval_stage is ApprovalStates.APPROVED
@property
def is_rejected(self):
'''The sanction has been rejected by either an admin or a moderator.'''
rejected_states = [
ApprovalStates.REJECTED, ApprovalStates.MODERATOR_REJECTED
]
return self.approval_stage in rejected_states
@property
def is_moderated(self):
return self.target_registration.is_moderated
@property
def approval_stage(self):
return ApprovalStates.from_db_name(self.state)
@approval_stage.setter
def approval_stage(self, state):
self.state = state.db_name
@property
def target_registration(self):
return self._get_registration()
@property
def revisable(self):
'''Controls state machine flow on a 'reject' trigger.
True -> IN_PROGRESS
False -> [MODERATOR_]REJECTED
Sanctions do not represent a revisable entity, so return False
'''
return False
# The Sanction object will also inherit the following functions from the SanctionStateMachine:
#
# approve(self, user, token)
# accept(self, user, token)
# reject(self, user, token)
#
# Overriding these functions will divorce the offending Sanction class from that trigger's
# functionality on the state machine.
def _get_registration(self):
"""Get the Registration that is waiting on this sanction."""
raise NotImplementedError('Sanction subclasses must implement a #_get_registration method')
def _on_approve(self, event_data):
"""Callback for individual admin approval of a sanction.
Invoked by state machine as the last step of an 'approve' trigger
:param EventData event_data: An EventData object from transitions.core
contains information about the active state transition and arbitrary args and kwargs
"""
raise NotImplementedError(
'Sanction subclasses must implement an #_on_approve method')
def _on_reject(self, event_data):
"""Callback for rejection of a Sanction.
Invoked by state machine as the last step of a 'reject' trigger
:param EventData event_data: An EventData object from transitions.core
contains information about the active state transition and arbitrary args and kwargs
"""
raise NotImplementedError(
'Sanction subclasses must implement an #_on_reject method')
def _on_complete(self, user):
"""Callback for when a Sanction is fully approved.
Invoked by state machine as the last step of an 'accept' trigger
:param EventData event_data: An EventData object from transitions.core
contains information about the active state transition and arbitrary args and kwargs
"""
raise NotImplementedError(
'Sanction subclasses must implement an #_on_complete method')
def forcibly_reject(self):
self.state = Sanction.REJECTED
def _save_transition(self, event_data):
"""Record the effects of a state transition in the database."""
self.save()
new_state = event_data.transition.dest
# No need to update registration state with no sanction state change
if new_state is None:
return
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
comment = event_data.kwargs.get('comment', '')
self.target_registration.update_moderation_state(initiated_by=user, comment=comment)
class Meta:
abstract = True
class TokenApprovableSanction(Sanction):
def _validate_authorizer(self, user):
"""Subclasses may choose to provide extra restrictions on who can be an authorizer
:return Boolean: True if user is allowed to be an authorizer else False
"""
return True
def _verify_user_role(self, user, action):
'''Confirm that user is allowed to act on the sanction in its current approval_stage.'''
if self.approval_stage is ApprovalStates.UNAPPROVED:
# Allow user is None when UNAPPROVED to support timed
# sanction expiration from within OSF via the 'accept' trigger
if user is None or user._id in self.approval_state:
return True
return False
required_permission = f'{action}_submissions'
if self.approval_stage is ApprovalStates.PENDING_MODERATION:
return user.has_perm(required_permission, self.target_registration.provider)
return False
def _validate_trigger(self, event_data):
'''Verify that an approve/accept/reject call meets all preconditions.'''
action = event_data.event.name
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
# Allow certain 'accept' calls with no user for OSF admin use
if not user and action != 'accept':
raise ValueError('All state trigger functions must specify a user')
if not self._verify_user_role(user, action):
raise PermissionsError(self.ACTION_NOT_AUTHORIZED_MESSAGE.format(
ACTION=action, DISPLAY_NAME=self.DISPLAY_NAME))
# Moderator auth is validated by API, no token to check
# user is None and no prior exception -> OSF-internal accept call
if self.approval_stage is ApprovalStates.PENDING_MODERATION or user is None:
return True
token = event_data.kwargs.get('token')
if token is None:
try:
token = event_data.args[1]
except IndexError:
raise ValueError('Admin actions require a token')
if action == 'approve' and self.approval_state[user._id]['approval_token'] != token:
raise InvalidSanctionApprovalToken(
self.APPROVAL_INVALID_TOKEN_MESSAGE.format(DISPLAY_NAME=self.DISPLAY_NAME))
elif action == 'reject' and self.approval_state[user._id]['rejection_token'] != token:
raise InvalidSanctionRejectionToken(
self.REJECTION_INVALID_TOKEN_MESSAGE.format(DISPLAY_NAME=self.DISPLAY_NAME))
return True
def add_authorizer(self, user, node, approved=False, save=False):
"""Add an admin user to this Sanction's approval state.
:param User user: User to add.
:param Node registration: The pending registration node.
:param bool approved: Whether `user` has approved.
:param bool save: Whether to save this object.
"""
valid = self._validate_authorizer(user)
if not valid or user._id in self.approval_state:
return False
self.approval_state[user._id] = {
'has_approved': approved,
'node_id': node._id,
'approval_token': tokens.encode({
'user_id': user.id,
'sanction_id': self._id,
'action': 'approve_{}'.format(self.SHORT_NAME)
}),
'rejection_token': tokens.encode({
'user_id': user.id,
'sanction_id': self._id,
'action': 'reject_{}'.format(self.SHORT_NAME)
})
}
if save:
self.save()
return True
def remove_authorizer(self, user, save=False):
"""Remove a user as an authorizer
:param User user:
:return Boolean: True if user is removed else False
"""
if user._id not in self.approval_state:
return False
del self.approval_state[user._id]
if save:
self.save()
return True
def _on_approve(self, event_data):
"""Callback from #approve state machine trigger.
Calls #accept trigger under either of two conditions:
- mode is ANY and the Sanction has not already been cancelled
- mode is UNANIMOUS and all users have given approval
"""
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
self.approval_state[user._id]['has_approved'] = True
if self.mode == self.ANY or all(
authorizer['has_approved']
for authorizer in self.approval_state.values()):
self.accept(*event_data.args, **event_data.kwargs) # state machine trigger
def token_for_user(self, user, method):
"""
:param str method: 'approval' | 'rejection'
"""
try:
user_state = self.approval_state[user._id]
except KeyError:
raise PermissionsError(self.APPROVAL_NOT_AUTHORIZED_MESSAGE.format(
DISPLAY_NAME=self.DISPLAY_NAME))
return user_state['{0}_token'.format(method)]
def _notify_authorizer(self, user, node):
pass
def _notify_non_authorizer(self, user, node):
pass
def ask(self, group):
pass
class Meta:
abstract = True
class EmailApprovableSanction(TokenApprovableSanction):
AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = None
NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = None
VIEW_URL_TEMPLATE = ''
APPROVE_URL_TEMPLATE = ''
REJECT_URL_TEMPLATE = ''
# A flag to conditionally run a callback on complete
notify_initiator_on_complete = models.BooleanField(default=False)
# Store a persistant copy of urls for use when needed outside of a request context.
# This field gets automagically updated whenever models approval_state is modified
# and the model is saved
# {
# 'abcde': {
# 'approve': [APPROVAL_URL],
# 'reject': [REJECT_URL],
# }
# }
stashed_urls = DateTimeAwareJSONField(default=dict, blank=True)
@property
def should_suppress_emails(self):
return self._get_registration().external_registration
@staticmethod
def _format_or_empty(template, context):
if context:
return template.format(**context)
return ''
def _view_url(self, user_id, node):
return self._format_or_empty(self.VIEW_URL_TEMPLATE,
self._view_url_context(user_id, node))
def _view_url_context(self, user_id, node):
return None
def _approval_url(self, user_id):
return self._format_or_empty(self.APPROVE_URL_TEMPLATE,
self._approval_url_context(user_id))
def _approval_url_context(self, user_id):
return None
def _rejection_url(self, user_id):
return self._format_or_empty(self.REJECT_URL_TEMPLATE,
self._rejection_url_context(user_id))
def _rejection_url_context(self, user_id):
return None
def _send_approval_request_email(self, user, template, context):
mails.send_mail(user.username, template, user=user, can_change_preferences=False, **context)
def _email_template_context(self, user, node, is_authorizer=False):
return {}
def _notify_authorizer(self, authorizer, node):
context = self._email_template_context(authorizer,
node,
is_authorizer=True)
if self.AUTHORIZER_NOTIFY_EMAIL_TEMPLATE:
self._send_approval_request_email(
authorizer, self.AUTHORIZER_NOTIFY_EMAIL_TEMPLATE, context)
else:
raise NotImplementedError()
def _notify_non_authorizer(self, user, node):
context = self._email_template_context(user, node)
if self.NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE:
self._send_approval_request_email(
user, self.NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE, context)
else:
raise NotImplementedError
def ask(self, group):
"""
:param list group: List of (user, node) tuples containing contributors to notify about the
sanction.
"""
if self.should_suppress_emails:
return
for contrib, node in group:
if contrib._id in self.approval_state:
self._notify_authorizer(contrib, node)
else:
self._notify_non_authorizer(contrib, node)
def add_authorizer(self, user, node, **kwargs):
super(EmailApprovableSanction, self).add_authorizer(user, node,
**kwargs)
self.stashed_urls[user._id] = {
'view': self._view_url(user._id, node),
'approve': self._approval_url(user._id),
'reject': self._rejection_url(user._id)
}
self.save()
def _notify_initiator(self):
raise NotImplementedError
def _on_complete(self, event_data):
if self.notify_initiator_on_complete and not self.should_suppress_emails:
self._notify_initiator()
class Meta:
abstract = True
class SanctionCallbackMixin(object):
def _notify_initiator(self):
raise NotImplementedError()
def _email_template_context(self, user, node, is_authorizer=False, urls=None):
return {}
class Embargo(SanctionCallbackMixin, EmailApprovableSanction):
"""Embargo object for registrations waiting to go public."""
SANCTION_TYPE = SanctionTypes.EMBARGO
DISPLAY_NAME = 'Embargo'
SHORT_NAME = 'embargo'
AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_EMBARGO_ADMIN
NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_EMBARGO_NON_ADMIN
VIEW_URL_TEMPLATE = VIEW_PROJECT_URL_TEMPLATE
APPROVE_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
REJECT_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
initiated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
for_existing_registration = models.BooleanField(default=False)
@property
def is_completed(self):
return self.state == self.COMPLETED
@property
def is_deleted(self):
if self.target_registration:
return self.target_registration.is_deleted
else: # Embargo is orphaned, so consider it deleted
return True
@property
def embargo_end_date(self):
if self.state == self.APPROVED:
return self.end_date
return False
# NOTE(hrybacki): Old, private registrations are grandfathered and do not
# require to be made public or embargoed. This field differentiates them
# from new registrations entering into an embargo field which should not
# show up in any search related fields.
@property
def pending_registration(self):
return not self.for_existing_registration and self.is_pending_approval
def _get_registration(self):
return self.registrations.first()
def _view_url_context(self, user_id, node):
registration = node or self._get_registration()
return {'node_id': registration._id}
def _approval_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
approval_token = user_approval_state.get('approval_token')
if approval_token:
registration = self._get_registration()
node_id = user_approval_state.get('node_id', registration._id)
return {'node_id': node_id, 'token': approval_token}
def _rejection_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
rejection_token = user_approval_state.get('rejection_token')
if rejection_token:
Registration = apps.get_model('osf.Registration')
root_registration = self._get_registration()
node_id = user_approval_state.get('node_id', root_registration._id)
registration = Registration.load(node_id)
return {
'node_id': registration.registered_from._id,
'token': rejection_token,
}
def _email_template_context(self,
user,
node,
is_authorizer=False,
urls=None):
context = super(Embargo, self)._email_template_context(
user,
node,
is_authorizer=is_authorizer)
urls = urls or self.stashed_urls.get(user._id, {})
registration_link = urls.get('view', self._view_url(user._id, node))
approval_time_span = osf_settings.EMBARGO_PENDING_TIME.days * 24
if is_authorizer:
approval_link = urls.get('approve', '')
disapproval_link = urls.get('reject', '')
registration = self._get_registration()
context.update({
'is_initiator': self.initiated_by == user,
'initiated_by': self.initiated_by.fullname,
'approval_link': approval_link,
'project_name': registration.title,
'disapproval_link': disapproval_link,
'registration_link': registration_link,
'embargo_end_date': self.end_date,
'approval_time_span': approval_time_span,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
})
else:
context.update({
'initiated_by': self.initiated_by.fullname,
'registration_link': registration_link,
'embargo_end_date': self.end_date,
'approval_time_span': approval_time_span,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
})
return context
def _on_reject(self, event_data):
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
NodeLog = apps.get_model('osf.NodeLog')
parent_registration = self.target_registration
parent_registration.registered_from.add_log(
action=NodeLog.EMBARGO_CANCELLED,
params={
'node': parent_registration.registered_from._id,
'registration': parent_registration._id,
'embargo_id': self._id,
},
auth=Auth(user) if user else Auth(self.initiated_by))
# Remove backref to parent project if embargo was for a new registration
if not self.for_existing_registration:
parent_registration.delete_registration_tree(save=True)
parent_registration.registered_from = None
# Delete parent registration if it was created at the time the embargo was initiated
if not self.for_existing_registration:
parent_registration.is_deleted = True
parent_registration.deleted = timezone.now()
parent_registration.save()
def disapprove_embargo(self, user, token):
"""Cancels retraction if user is admin and token verifies."""
self.reject(user=user, token=token)
def _on_complete(self, event_data):
NodeLog = apps.get_model('osf.NodeLog')
parent_registration = self.target_registration
if parent_registration.is_spammy:
raise NodeStateError('Cannot complete a spammy registration.')
super()._on_complete(event_data)
parent_registration.registered_from.add_log(
action=NodeLog.EMBARGO_APPROVED,
params={
'node': parent_registration.registered_from._id,
'registration': parent_registration._id,
'embargo_id': self._id,
},
auth=Auth(self.initiated_by), )
# Make placeholder identifiers for all Registrations to allow resources to be added
# This Identifier will be grabbed and populated when the Registration is made public
for registration in parent_registration.node_and_primary_descendants():
registration.set_identifier_value(category='doi', value=None)
self.save()
def approve_embargo(self, user, token):
"""Add user to approval list if user is admin and token verifies."""
self.approve(user=user, token=token)
def mark_as_completed(self):
# Plucked from embargo_registrations script
# self.state = Sanction.COMPLETED
self.to_COMPLETED()
class Retraction(EmailApprovableSanction):
"""
Retraction object for public registrations.
Externally (specifically in user-facing language) retractions should be referred to as "Withdrawals", i.e.
"Retract Registration" -> "Withdraw Registration", "Retracted" -> "Withdrawn", etc.
"""
SANCTION_TYPE = SanctionTypes.RETRACTION
DISPLAY_NAME = 'Retraction'
SHORT_NAME = 'retraction'
AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_RETRACTION_ADMIN
NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_RETRACTION_NON_ADMIN
VIEW_URL_TEMPLATE = VIEW_PROJECT_URL_TEMPLATE
APPROVE_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
REJECT_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
initiated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
justification = models.CharField(max_length=2048, null=True, blank=True)
date_retracted = NonNaiveDateTimeField(null=True, blank=True)
def _get_registration(self):
Registration = apps.get_model('osf.Registration')
parent_registration = Registration.objects.get(retraction=self)
return parent_registration
def _view_url_context(self, user_id, node):
registration = self.registrations.first() or node
return {
'node_id': registration._id
}
def _approval_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
approval_token = user_approval_state.get('approval_token')
if approval_token:
root_registration = self.registrations.first()
node_id = user_approval_state.get('node_id', root_registration._id)
return {
'node_id': node_id,
'token': approval_token,
}
def _rejection_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
rejection_token = user_approval_state.get('rejection_token')
if rejection_token:
Registration = apps.get_model('osf.Registration')
node_id = user_approval_state.get('node_id', None)
registration = Registration.objects.select_related(
'registered_from'
).get(
guids___id=node_id, guids___id__isnull=False
) if node_id else self.registrations.first()
return {
'node_id': registration.registered_from._id,
'token': rejection_token,
}
def _email_template_context(self, user, node, is_authorizer=False, urls=None):
urls = urls or self.stashed_urls.get(user._id, {})
registration_link = urls.get('view', self._view_url(user._id, node))
approval_time_span = osf_settings.RETRACTION_PENDING_TIME.days * 24
if is_authorizer:
approval_link = urls.get('approve', '')
disapproval_link = urls.get('reject', '')
return {
'is_initiator': self.initiated_by == user,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'initiated_by': self.initiated_by.fullname,
'project_name': self.registrations.filter().values_list('title', flat=True).get(),
'registration_link': registration_link,
'approval_link': approval_link,
'disapproval_link': disapproval_link,
'approval_time_span': approval_time_span,
}
else:
return {
'initiated_by': self.initiated_by.fullname,
'registration_link': registration_link,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'approval_time_span': approval_time_span,
}
def _on_reject(self, event_data):
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
NodeLog = apps.get_model('osf.NodeLog')
parent_registration = self.target_registration
parent_registration.registered_from.add_log(
action=NodeLog.RETRACTION_CANCELLED,
params={
'node': parent_registration.registered_from._id,
'registration': parent_registration._id,
'retraction_id': self._id,
},
auth=Auth(user),
save=True,
)
def _on_complete(self, event_data):
super()._on_complete(event_data)
self.date_retracted = timezone.now()
registration = self.target_registration
registration.withdraw()
self.save()
def approve_retraction(self, user, token):
'''Test function'''
self.approve(user=user, token=token)
def disapprove_retraction(self, user, token):
'''Test function'''
self.reject(user=user, token=token)
class RegistrationApproval(SanctionCallbackMixin, EmailApprovableSanction):
SANCTION_TYPE = SanctionTypes.REGISTRATION_APPROVAL
DISPLAY_NAME = 'Approval'
SHORT_NAME = 'registration_approval'
AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_REGISTRATION_ADMIN
NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_REGISTRATION_NON_ADMIN
VIEW_URL_TEMPLATE = VIEW_PROJECT_URL_TEMPLATE
APPROVE_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
REJECT_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
initiated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
def _get_registration(self):
return self.registrations.first()
def _view_url_context(self, user_id, node):
user_approval_state = self.approval_state.get(user_id, {})
node_id = user_approval_state.get('node_id', node._id)
return {
'node_id': node_id
}
def _approval_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
approval_token = user_approval_state.get('approval_token')
if approval_token:
registration = self._get_registration()
node_id = user_approval_state.get('node_id', registration._id)
return {
'node_id': node_id,
'token': approval_token,
}
def _rejection_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
rejection_token = self.approval_state.get(user_id, {}).get('rejection_token')
if rejection_token:
Registration = apps.get_model('osf.Registration')
root_registration = self._get_registration()
node_id = user_approval_state.get('node_id', root_registration._id)
registration = Registration.load(node_id)
return {
'node_id': registration.registered_from._id,
'token': rejection_token,
}
def _email_template_context(self, user, node, is_authorizer=False, urls=None):
context = super(RegistrationApproval, self)._email_template_context(user, node, is_authorizer, urls)
urls = urls or self.stashed_urls.get(user._id, {})
registration_link = urls.get('view', self._view_url(user._id, node))
approval_time_span = osf_settings.REGISTRATION_APPROVAL_TIME.days * 24
if is_authorizer:
approval_link = urls.get('approve', '')
disapproval_link = urls.get('reject', '')
registration = self._get_registration()
context.update({
'is_initiator': self.initiated_by == user,
'initiated_by': self.initiated_by.fullname,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'registration_link': registration_link,
'approval_link': approval_link,
'disapproval_link': disapproval_link,
'approval_time_span': approval_time_span,
'project_name': registration.title,
})
else:
context.update({
'initiated_by': self.initiated_by.fullname,
'registration_link': registration_link,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'approval_time_span': approval_time_span,
})
return context
def _add_success_logs(self, node, user):
NodeLog = apps.get_model('osf.NodeLog')
src = node.registered_from
src.add_log(
action=NodeLog.PROJECT_REGISTERED,
params={
'parent_node': src.parent_node._id if src.parent_node else None,
'node': src._primary_key,
'registration': node._primary_key,
},
auth=Auth(user),
save=False
)
src.save()
def _on_complete(self, event_data):
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
NodeLog = apps.get_model('osf.NodeLog')
registration = self._get_registration()
if registration.is_spammy:
raise NodeStateError('Cannot approve a spammy registration')
super()._on_complete(event_data)
self.save()
registered_from = registration.registered_from
# Pass auth=None because the registration initiator may not be
# an admin on components (component admins had the opportunity
# to disapprove the registration by this point)
registration.set_privacy('public', auth=None, log=False)
for child in registration.get_descendants_recursive(primary_only=True):
child.set_privacy('public', auth=None, log=False)
# Accounts for system actions where no `User` performs the final approval
auth = Auth(user) if user else None
registered_from.add_log(
action=NodeLog.REGISTRATION_APPROVAL_APPROVED,
params={
'node': registered_from._id,
'registration': registration._id,
'registration_approval_id': self._id,
},
auth=auth,
)
for node in registration.root.node_and_primary_descendants():
self._add_success_logs(node, user)
node.update_search() # update search if public
self.save()
def _on_reject(self, event_data):
user = event_data.kwargs.get('user')
if user is None and event_data.args:
user = event_data.args[0]
NodeLog = apps.get_model('osf.NodeLog')
registered_from = self.target_registration.registered_from
self.target_registration.delete_registration_tree(save=True)
registered_from.add_log(
action=NodeLog.REGISTRATION_APPROVAL_CANCELLED,
params={
'node': registered_from._id,
'registration': self.target_registration._id,
'registration_approval_id': self._id,
},
auth=Auth(user),
)
class EmbargoTerminationApproval(EmailApprovableSanction):
SANCTION_TYPE = SanctionTypes.EMBARGO_TERMINATION_APPROVAL
DISPLAY_NAME = 'Embargo Termination Request'
SHORT_NAME = 'embargo_termination_approval'
AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_EMBARGO_TERMINATION_ADMIN
NON_AUTHORIZER_NOTIFY_EMAIL_TEMPLATE = mails.PENDING_EMBARGO_TERMINATION_NON_ADMIN
VIEW_URL_TEMPLATE = VIEW_PROJECT_URL_TEMPLATE
APPROVE_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
REJECT_URL_TEMPLATE = osf_settings.DOMAIN + 'token_action/{node_id}/?token={token}'
embargoed_registration = models.ForeignKey('Registration', null=True, blank=True, on_delete=models.CASCADE)
initiated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
@property
def is_moderated(self):
return False # Embargo Termination never requires Moderator Approval
def _get_registration(self):
return self.embargoed_registration
def _view_url_context(self, user_id, node):
registration = node or self._get_registration()
return {
'node_id': registration._id
}
def _approval_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
approval_token = user_approval_state.get('approval_token')
if approval_token:
registration = self._get_registration()
node_id = user_approval_state.get('node_id', registration._id)
return {
'node_id': node_id,
'token': approval_token,
}
def _rejection_url_context(self, user_id):
user_approval_state = self.approval_state.get(user_id, {})
rejection_token = user_approval_state.get('rejection_token')
if rejection_token:
root_registration = self._get_registration()
node_id = user_approval_state.get('node_id', root_registration._id)
return {
'node_id': node_id,
'token': rejection_token,
}
def _email_template_context(self, user, node, is_authorizer=False, urls=None):
context = super(EmbargoTerminationApproval, self)._email_template_context(
user,
node,
is_authorizer=is_authorizer
)
urls = urls or self.stashed_urls.get(user._id, {})
registration_link = urls.get('view', self._view_url(user._id, node))
approval_time_span = osf_settings.EMBARGO_TERMINATION_PENDING_TIME.days * 24
if is_authorizer:
approval_link = urls.get('approve', '')
disapproval_link = urls.get('reject', '')
registration = self._get_registration()
context.update({
'is_initiator': self.initiated_by == user,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'initiated_by': self.initiated_by.fullname,
'approval_link': approval_link,
'project_name': registration.title,
'disapproval_link': disapproval_link,
'registration_link': registration_link,
'embargo_end_date': self.end_date,
'approval_time_span': approval_time_span,
})
else:
context.update({
'initiated_by': self.initiated_by.fullname,
'project_name': self.target_registration.title,
'registration_link': registration_link,
'embargo_end_date': self.end_date,
'is_moderated': self.is_moderated,
'reviewable': self._get_registration(),
'approval_time_span': approval_time_span,
})
return context
def _on_complete(self, event_data):
super()._on_complete(event_data)
if self.target_registration.is_embargoed: # if the embargo expires normally, this is noop.
self.target_registration.terminate_embargo(forced=True)