-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathviews.py
More file actions
1502 lines (1240 loc) · 56 KB
/
views.py
File metadata and controls
1502 lines (1240 loc) · 56 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
import pytz
from urllib.parse import urlencode
from django.apps import apps
from django.db import IntegrityError
from django.db.models import F
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect
from guardian.shortcuts import get_objects_for_user
from rest_framework.throttling import UserRateThrottle
from api.addons.views import AddonSettingsMixin
from api.base import permissions as base_permissions
from api.users.permissions import UserMessagePermissions
from api.base.exceptions import Conflict, UserGone
from api.base.filters import ListFilterMixin, PreprintFilterMixin
from api.base.parsers import (
JSONAPIRelationshipParser,
JSONAPIRelationshipParserForRegularJSON,
JSONAPIMultipleRelationshipsParser,
JSONAPIMultipleRelationshipsParserForRegularJSON,
)
from api.base.serializers import get_meta_type, AddonAccountSerializer
from api.base.utils import (
default_node_list_permission_queryset,
get_object_or_error,
get_user_auth,
hashids,
is_truthy,
)
from api.base.views import JSONAPIBaseView
from api.base.throttling import (
SendEmailThrottle,
SendEmailDeactivationThrottle,
NonCookieAuthThrottle,
BurstRateThrottle,
RootAnonThrottle,
)
from api.institutions.serializers import InstitutionSerializer
from api.nodes.filters import NodesFilterMixin, UserNodesFilterMixin
from api.nodes.serializers import DraftRegistrationLegacySerializer
from api.nodes.utils import NodeOptimizationMixin
from api.preprints.serializers import PreprintSerializer, PreprintDraftSerializer
from api.registrations import annotations as registration_annotations
from api.registrations.serializers import RegistrationSerializer
from api.resources import annotations as resource_annotations
from api.users.permissions import (
CurrentUser, ReadOnlyOrCurrentUser,
ReadOnlyOrCurrentUserRelationship,
ClaimUserPermission,
)
from api.users.serializers import (
UserAddonSettingsSerializer,
UserDetailSerializer,
UserIdentitiesSerializer,
UserInstitutionsRelationshipSerializer,
UserResetPasswordSerializer,
UserSerializer,
UserEmail,
UserEmailsSerializer,
UserNodeSerializer,
UserSettingsSerializer,
UserSettingsUpdateSerializer,
UserAccountExportSerializer,
ReadEmailUserDetailSerializer,
UserChangePasswordSerializer,
UserMessageSerializer,
ExternalLoginSerialiser,
ConfirmEmailTokenSerializer,
SanctionTokenSerializer,
)
from django.contrib.auth.models import AnonymousUser
from django.http import JsonResponse
from django.utils import timezone
from framework import sentry
from framework.auth.core import get_user, generate_verification_key
from framework.auth.views import send_confirm_email_async, ensure_external_identity_uniqueness
from framework.auth.tasks import update_affiliation_for_orcid_sso_users
from framework.auth.oauth_scopes import CoreScopes, normalize_scopes
from framework.auth.exceptions import ChangePasswordError
from framework.celery_tasks.handlers import enqueue_task
from framework.utils import throttle_period_expired
from framework.sessions.utils import remove_sessions_for_user
from framework.exceptions import PermissionsError, HTTPError
from rest_framework import permissions as drf_permissions
from rest_framework import generics
from rest_framework import status
from rest_framework.response import Response
from rest_framework.exceptions import NotAuthenticated, NotFound, ValidationError, Throttled
from osf.models import (
Contributor,
ExternalAccount,
Guid,
AbstractNode,
Preprint,
Node,
Registration,
OSFUser,
Email,
Tag,
NotificationTypeEnum,
PreprintProvider,
)
from osf.utils.tokens import TokenHandler
from osf.utils.tokens.handlers import sanction_handler
from website import settings, language
from website.project.views.contributor import send_claim_email, send_claim_registered_email
from website.util.metrics import CampaignClaimedTags, CampaignSourceTags
from framework.auth import exceptions
from website.project.views.contributor import _add_related_claimed_tag_to_user
from website.util import api_v2_url
from framework.auth import signals
class UserMixin:
"""Mixin with convenience methods for retrieving the current user based on the
current URL. By default, fetches the user based on the user_id kwarg.
"""
serializer_class = UserSerializer
user_lookup_url_kwarg = 'user_id'
def get_user(self, check_permissions=True):
key = self.kwargs[self.user_lookup_url_kwarg]
# If Contributor is in self.request.parents,
# then this view is getting called due to an embedded request (contributor embedding user)
# We prefer to access the user from the contributor object and take advantage
# of the query cache
if hasattr(self.request, 'parents') and len(self.request.parents.get(Contributor, {})) == 1:
# We expect one parent contributor view, so index into the first item
contrib_id, contrib = list(self.request.parents[Contributor].items())[0]
user = contrib.user
if user.is_disabled:
if getattr(user, 'gdpr_deleted', False):
raise NotFound
raise UserGone(user=user)
# Make sure that the contributor ID is correct
if user._id == key:
if check_permissions:
self.check_object_permissions(self.request, user)
return get_object_or_error(
OSFUser.objects.filter(id=user.id).annotate(default_region=F('addons_osfstorage_user_settings__default_region___id')).exclude(default_region=None),
request=self.request,
display_name='user',
)
if self.kwargs.get('is_embedded') is True:
if key in self.request.parents[OSFUser]:
return self.request.parents[OSFUser].get(key)
current_user = self.request.user
if isinstance(current_user, AnonymousUser):
if key == 'me':
raise NotAuthenticated
elif key == 'me' or key == current_user._id:
return get_object_or_error(
OSFUser.objects.filter(id=current_user.id).annotate(default_region=F('addons_osfstorage_user_settings__default_region___id')).exclude(default_region=None),
request=self.request,
display_name='user',
)
obj = get_object_or_error(OSFUser, key, self.request, 'user')
if check_permissions:
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
class UserList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.RequiresScopedRequestOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.USERS_READ]
required_write_scopes = [CoreScopes.NULL]
model_class = apps.get_model('osf.OSFUser')
serializer_class = UserSerializer
ordering = ('-date_registered')
view_category = 'users'
view_name = 'user-list'
def get_default_queryset(self):
return OSFUser.objects.filter(is_registered=True, date_disabled__isnull=True, merged_by__isnull=True)
# overrides ListCreateAPIView
def get_queryset(self):
return self.get_queryset_from_request()
class UserDetail(JSONAPIBaseView, generics.RetrieveUpdateAPIView, UserMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_read).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
ReadOnlyOrCurrentUser,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.USERS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE]
view_category = 'users'
view_name = 'user-detail'
serializer_class = UserDetailSerializer
parser_classes = (JSONAPIMultipleRelationshipsParser, JSONAPIMultipleRelationshipsParserForRegularJSON)
def get_serializer_class(self):
if self.request.auth:
scopes = self.request.auth.attributes['accessTokenScope']
if (CoreScopes.USER_EMAIL_READ in normalize_scopes(scopes) and self.request.user == self.get_user()):
return ReadEmailUserDetailSerializer
return UserDetailSerializer
# overrides RetrieveAPIView
def get_object(self):
return self.get_user()
# overrides RetrieveUpdateAPIView
def get_serializer_context(self):
# Serializer needs the request in order to make an update to privacy
context = JSONAPIBaseView.get_serializer_context(self)
context['request'] = self.request
return context
class UserAddonList(JSONAPIBaseView, generics.ListAPIView, ListFilterMixin, UserMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_addons_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_ADDON_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = UserAddonSettingsSerializer
view_category = 'users'
view_name = 'user-addons'
ordering = ('-id',)
def get_queryset(self):
qs = [addon for addon in self.get_user().get_addons() if 'accounts' in addon.config.configs]
sorted(qs, key=lambda addon: addon.id, reverse=True)
return qs
class UserAddonDetail(JSONAPIBaseView, generics.RetrieveAPIView, UserMixin, AddonSettingsMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_addons_read).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_ADDON_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = UserAddonSettingsSerializer
view_category = 'users'
view_name = 'user-addon-detail'
def get_object(self):
return self.get_addon_settings(check_object_permissions=False)
class UserAddonAccountList(JSONAPIBaseView, generics.ListAPIView, UserMixin, AddonSettingsMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/Users_addon_accounts_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_ADDON_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = AddonAccountSerializer
view_category = 'users'
view_name = 'user-external_accounts'
ordering = ('-date_last_refreshed',)
def get_queryset(self):
return self.get_addon_settings(check_object_permissions=False).external_accounts
class UserAddonAccountDetail(JSONAPIBaseView, generics.RetrieveAPIView, UserMixin, AddonSettingsMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/Users_addon_accounts_read).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_ADDON_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = AddonAccountSerializer
view_category = 'users'
view_name = 'user-external_account-detail'
def get_object(self):
user_settings = self.get_addon_settings(check_object_permissions=False)
account_id = self.kwargs['account_id']
account = ExternalAccount.load(account_id)
if not (account and user_settings.external_accounts.filter(id=account.id).exists()):
raise NotFound('Requested addon unavailable')
return account
class UserNodes(JSONAPIBaseView, generics.ListAPIView, UserMixin, UserNodesFilterMixin, NodeOptimizationMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_nodes_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
model_class = AbstractNode
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.NODE_BASE_READ]
required_write_scopes = [CoreScopes.USERS_WRITE, CoreScopes.NODE_BASE_WRITE]
serializer_class = UserNodeSerializer
view_category = 'users'
view_name = 'user-nodes'
ordering = ('-last_logged',)
# overrides NodesFilterMixin
def get_default_queryset(self):
user = self.get_user()
# Nodes the requested user has read_permissions on
default_queryset = user.nodes_contributor_or_group_member_to
if user != self.request.user:
# Further restrict UserNodes to nodes the *requesting* user can view
return Node.objects.get_nodes_for_user(self.request.user, base_queryset=default_queryset, include_public=True)
return self.optimize_node_queryset(default_queryset)
# overrides ListAPIView
def get_queryset(self):
return (
self.get_queryset_from_request()
.select_related('node_license')
.prefetch_related('contributor_set__user__guids', 'root__guids')
)
class UserPreprints(JSONAPIBaseView, generics.ListAPIView, UserMixin, PreprintFilterMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_preprints_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
ordering = ('-created')
model_class = AbstractNode
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.NODE_PREPRINTS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE, CoreScopes.NODE_PREPRINTS_WRITE]
serializer_class = PreprintSerializer
view_category = 'users'
view_name = 'user-preprints'
def get_default_queryset(self):
# the user who is requesting
auth = get_user_auth(self.request)
auth_user = getattr(auth, 'user', None)
# the user data being requested
target_user = self.get_user(check_permissions=False)
# Permissions on the list objects are handled by the query
default_qs = Preprint.objects.filter(_contributors__guids___id=target_user._id).exclude(machine_state='initial')
return self.preprints_queryset(default_qs, auth_user, allow_contribs=False, latest_only=True)
def get_queryset(self):
return self.get_queryset_from_request()
class UserDraftPreprints(JSONAPIBaseView, generics.ListAPIView, UserMixin, PreprintFilterMixin):
"""See [documentation for this endpoint](https://developer.osf.io/).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
ordering = ('-created')
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.NODE_PREPRINTS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE, CoreScopes.NODE_PREPRINTS_WRITE]
serializer_class = PreprintDraftSerializer
view_category = 'users'
view_name = 'user-draft-preprints'
def get_default_queryset(self):
user = self.get_user()
return user.preprints.filter(
machine_state='initial',
deleted__isnull=True,
)
def get_queryset(self):
return self.get_queryset_from_request()
class UserInstitutions(JSONAPIBaseView, generics.ListAPIView, UserMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_institutions_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.INSTITUTION_READ]
required_write_scopes = [CoreScopes.NULL]
serializer_class = InstitutionSerializer
view_category = 'users'
view_name = 'user-institutions'
ordering = ('-pk',)
def get_default_odm_query(self):
return None
def get_queryset(self):
user = self.get_user()
return user.get_affiliated_institutions()
class UserRegistrations(JSONAPIBaseView, generics.ListAPIView, UserMixin, NodesFilterMixin):
"""See [documentation for this endpoint](https://developer.osf.io/#operation/users_registrations_list).
"""
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
)
model_class = Registration
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.NODE_REGISTRATIONS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE, CoreScopes.NODE_REGISTRATIONS_WRITE]
serializer_class = RegistrationSerializer
view_category = 'users'
view_name = 'user-registrations'
ordering = ('-modified',)
# overrides NodesFilterMixin
def get_default_queryset(self):
user = self.get_user()
current_user = self.request.user
qs = default_node_list_permission_queryset(
user=current_user,
model_cls=Registration,
revision_state=registration_annotations.REVISION_STATE,
**resource_annotations.make_open_practice_badge_annotations(),
)
# OSF group members not copied to registration. Only registration contributors need to be checked here.
return qs.filter(contributor__user__id=user.id)
# overrides ListAPIView
def get_queryset(self):
return self.get_queryset_from_request().select_related(
'node_license',
).prefetch_related(
'contributor_set__user__guids',
'root__guids',
)
class UserDraftRegistrations(JSONAPIBaseView, generics.ListAPIView, UserMixin):
permission_classes = (
drf_permissions.IsAuthenticated,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USERS_READ, CoreScopes.NODE_DRAFT_REGISTRATIONS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE, CoreScopes.NODE_DRAFT_REGISTRATIONS_WRITE]
serializer_class = DraftRegistrationLegacySerializer
view_category = 'users'
view_name = 'user-draft-registrations'
ordering = ('-modified',)
def get_queryset(self):
user = self.get_user()
# Returns DraftRegistrations for which the user is a contributor, and the user can view
drafts = user.draft_registrations_active
return get_objects_for_user(user, 'read_draft_registration', drafts, with_superuser=False)
class UserInstitutionsRelationship(JSONAPIBaseView, generics.RetrieveDestroyAPIView, UserMixin):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
ReadOnlyOrCurrentUserRelationship,
)
required_read_scopes = [CoreScopes.USERS_READ]
required_write_scopes = [CoreScopes.USERS_WRITE]
serializer_class = UserInstitutionsRelationshipSerializer
parser_classes = (JSONAPIRelationshipParser, JSONAPIRelationshipParserForRegularJSON)
view_category = 'users'
view_name = 'user-institutions-relationship'
def get_object(self):
user = self.get_user(check_permissions=False)
obj = {
'data': user.get_affiliated_institutions(),
'self': user,
}
self.check_object_permissions(self.request, obj)
return obj
def perform_destroy(self, instance):
data = self.request.data['data']
user = self.request.user
current_institutions = set(user.get_institution_affiliations().values_list('institution___id', flat=True))
# DELETEs normally dont get type checked
# not the best way to do it, should be enforced everywhere, maybe write a test for it
for val in data:
if val['type'] != get_meta_type(self.serializer_class, self.request):
raise Conflict()
for val in data:
if val['id'] in current_institutions:
user.remove_affiliated_institution(val['id'])
user.save()
class UserIdentitiesList(JSONAPIBaseView, generics.ListAPIView, UserMixin):
"""
See [documentation for this endpoint](https://developer.osf.io/#operation/external_identities_list).
"""
permission_classes = (
base_permissions.TokenHasScope,
drf_permissions.IsAuthenticatedOrReadOnly,
CurrentUser,
)
serializer_class = UserIdentitiesSerializer
required_read_scopes = [CoreScopes.USER_SETTINGS_READ]
required_write_scopes = [CoreScopes.NULL]
view_category = 'users'
view_name = 'user-identities-list'
# overrides ListAPIView
def get_queryset(self):
user = self.get_user()
identities = []
for key, value in user.external_identity.items():
identities.append({'_id': key, 'external_id': list(value.keys())[0], 'status': list(value.values())[0]})
return identities
class UserIdentitiesDetail(JSONAPIBaseView, generics.RetrieveDestroyAPIView, UserMixin):
"""
See [documentation for this endpoint](https://developer.osf.io/#operation/external_identities_detail).
"""
permission_classes = (
base_permissions.TokenHasScope,
drf_permissions.IsAuthenticatedOrReadOnly,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_SETTINGS_READ]
required_write_scopes = [CoreScopes.USER_SETTINGS_WRITE]
serializer_class = UserIdentitiesSerializer
view_category = 'users'
view_name = 'user-identities-detail'
def get_object(self):
user = self.get_user()
identity_id = self.kwargs['identity_id']
try:
identity = user.external_identity[identity_id]
except KeyError:
raise NotFound('Requested external identity could not be found.')
return {'_id': identity_id, 'external_id': list(identity.keys())[0], 'status': list(identity.values())[0]}
def perform_destroy(self, instance):
user = self.get_user()
identity_id = self.kwargs['identity_id']
try:
user.external_identity.pop(identity_id)
except KeyError:
raise NotFound('Requested external identity could not be found.')
user.save()
class UserAccountExport(JSONAPIBaseView, generics.CreateAPIView, UserMixin):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.NULL]
required_write_scopes = [CoreScopes.USER_SETTINGS_WRITE]
view_category = 'users'
view_name = 'user-account-export'
serializer_class = UserAccountExportSerializer
throttle_classes = [UserRateThrottle, NonCookieAuthThrottle, BurstRateThrottle, SendEmailThrottle]
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.get_user()
NotificationTypeEnum.DESK_REQUEST_EXPORT.instance.emit(
user=user,
destination_address=settings.OSF_SUPPORT_EMAIL,
event_context={
'user_username': user.username,
'user_absolute_url': user.absolute_url,
'user__id': user._id,
},
)
user.email_last_sent = timezone.now()
user.save()
return Response(status=status.HTTP_204_NO_CONTENT)
class UserChangePassword(JSONAPIBaseView, generics.CreateAPIView, UserMixin):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.NULL]
required_write_scopes = [CoreScopes.USER_SETTINGS_WRITE]
view_category = 'users'
view_name = 'user_password'
serializer_class = UserChangePasswordSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = self.get_user()
existing_password = request.data['existing_password']
new_password = request.data['new_password']
# It has been more than 1 hour since last invalid attempt to change password. Reset the counter for invalid attempts.
if throttle_period_expired(user.change_password_last_attempt, settings.TIME_RESET_CHANGE_PASSWORD_ATTEMPTS):
user.reset_old_password_invalid_attempts()
# There have been more than 3 failed attempts and throttle hasn't expired.
if user.old_password_invalid_attempts >= settings.INCORRECT_PASSWORD_ATTEMPTS_ALLOWED and not throttle_period_expired(
user.change_password_last_attempt, settings.CHANGE_PASSWORD_THROTTLE,
):
time_since_throttle = (timezone.now() - user.change_password_last_attempt.replace(tzinfo=pytz.utc)).total_seconds()
wait_time = settings.CHANGE_PASSWORD_THROTTLE - time_since_throttle
raise Throttled(wait=wait_time)
try:
# double new password for confirmation because validation is done on the front-end.
user.change_password(existing_password, new_password, new_password)
except ChangePasswordError as error:
# A response object must be returned instead of raising an exception to avoid rolling back the transaction
# and losing the incrementation of failed password attempts
user.save()
return JsonResponse(
{'errors': [{'detail': message} for message in error.messages]},
status=400,
content_type='application/vnd.api+json; application/json',
)
user.save()
remove_sessions_for_user(user)
return Response(status=status.HTTP_204_NO_CONTENT)
class ExternalLogin(JSONAPIBaseView, generics.CreateAPIView):
"""
View to handle email submission for first-time oauth-login user.
HTTP Method: POST
"""
permission_classes = (
drf_permissions.AllowAny,
)
serializer_class = ExternalLoginSerialiser
view_category = 'users'
view_name = 'external-login'
throttle_classes = (NonCookieAuthThrottle, BurstRateThrottle, RootAnonThrottle)
@method_decorator(csrf_protect)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
session = request.session
external_id_provider = session.get('auth_user_external_id_provider', None)
external_id = session.get('auth_user_external_id', None)
fullname = session.get('auth_user_fullname', None) or request.data.get('auth_user_fullname', None)
accepted_terms_of_service = request.data.get('accepted_terms_of_service', False)
if session.get('auth_user_external_first_login', False) is not True:
raise HTTPError(status.HTTP_401_UNAUTHORIZED)
clean_email = request.data.get('email', None)
user = get_user(email=clean_email)
external_identity = {
external_id_provider: {
external_id: None,
},
}
try:
ensure_external_identity_uniqueness(external_id_provider, external_id, user)
except ValidationError as e:
raise HTTPError(status.HTTP_403_FORBIDDEN, e.message)
if user:
# 1. update user oauth, with pending status
external_identity[external_id_provider][external_id] = 'LINK'
if external_id_provider in user.external_identity:
if external_id_provider == 'orcid':
user.external_identity[external_id_provider] = external_identity[external_id_provider]
else:
user.external_identity[external_id_provider].update(external_identity[external_id_provider])
else:
user.external_identity.update(external_identity)
if not user.accepted_terms_of_service and accepted_terms_of_service:
user.accepted_terms_of_service = timezone.now()
# 2. add unconfirmed email and send confirmation email
user.add_unconfirmed_email(clean_email, external_identity=external_identity)
user.save()
send_confirm_email_async(
user,
clean_email,
external_id_provider=external_id_provider,
external_id=external_id,
)
signals.unconfirmed_user_created.send(user)
else:
# 1. create unconfirmed user with pending status
external_identity[external_id_provider][external_id] = 'CREATE'
accepted_terms_of_service = timezone.now() if accepted_terms_of_service else None
user = OSFUser.create_unconfirmed(
username=clean_email,
password=None,
fullname=fullname,
external_identity=external_identity,
campaign=None,
accepted_terms_of_service=accepted_terms_of_service,
)
# TODO: [#OSF-6934] update social fields, verified social fields cannot be modified
user.save()
# 3. send confirmation email
send_confirm_email_async(
user,
user.username,
external_id_provider=external_id_provider,
external_id=external_id,
)
signals.unconfirmed_user_created.send(user)
# Don't go anywhere
return JsonResponse(
{
'external_id_provider': external_id_provider,
'auth_user_fullname': fullname,
},
status=status.HTTP_200_OK,
content_type='application/vnd.api+json; application/json',
)
class ResetPassword(JSONAPIBaseView, generics.ListCreateAPIView):
"""
View for handling reset password requests.
GET:
- Takes an email as a query parameter.
- If the email is associated with an OSF account, sends an email with instructions to reset the password.
- If the email is not provided or invalid, returns a validation error.
- If the user has recently requested a password reset, returns a throttling error.
POST:
- Takes uid, token, and new password in the request data.
- Verifies the token and resets the password if valid.
- If the token is invalid or expired, returns an error.
- If the request data is incomplete, returns a validation error.
"""
permission_classes = (
drf_permissions.AllowAny,
)
serializer_class = UserResetPasswordSerializer
view_category = 'users'
view_name = 'request-reset-password'
throttle_classes = (NonCookieAuthThrottle, BurstRateThrottle, RootAnonThrottle, SendEmailThrottle)
def get(self, request, *args, **kwargs):
institutional = bool(request.query_params.get('institutional', None))
email = request.query_params.get('email', None)
if not email:
raise ValidationError('Request must include email in query params.')
status_message = language.RESET_PASSWORD_SUCCESS_STATUS_MESSAGE.format(email=email)
# check if the user exists
user_obj = get_user(email=email)
institutional = bool(request.query_params.get('institutional', None))
if user_obj:
# rate limit forgot_password_post
if not throttle_period_expired(user_obj.email_last_sent, settings.SEND_EMAIL_THROTTLE):
return Response(
{
'message': language.THROTTLE_PASSWORD_CHANGE_ERROR_MESSAGE,
'kind': 'error',
},
status=status.HTTP_429_TOO_MANY_REQUESTS,
)
elif user_obj.is_active:
# new random verification key (v2)
user_obj.verification_key_v2 = generate_verification_key(verification_type='password')
user_obj.email_last_sent = timezone.now()
user_obj.save()
reset_link = f'{settings.DOMAIN}resetpassword/{user_obj._id}/{user_obj.verification_key_v2["token"]}/'
if institutional:
notification_type = NotificationTypeEnum.USER_FORGOT_PASSWORD_INSTITUTION
else:
notification_type = NotificationTypeEnum.USER_FORGOT_PASSWORD
notification_type.instance.emit(
user=user_obj,
message_frequency='instantly',
event_context={
'reset_link': reset_link,
},
)
return Response(
status=status.HTTP_200_OK,
data={
'message': status_message,
'kind': 'success',
'institutional': institutional,
},
)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
uid = request.data.get('uid', None)
token = request.data.get('token', None)
password = request.data.get('password', None)
if not (uid and token and password):
error_data = {
'message_short': 'Invalid Request.',
'message_long': 'The request must include uid, token, and password.',
}
return JsonResponse(
error_data,
status=status.HTTP_400_BAD_REQUEST,
content_type='application/vnd.api+json; application/json',
)
user_obj = OSFUser.load(uid)
if not (user_obj and user_obj.verify_password_token(token=token)):
error_data = {
'message_short': 'Invalid Request.',
'message_long': 'The requested URL is invalid, has expired, or was already used',
}
return JsonResponse(
error_data,
status=status.HTTP_400_BAD_REQUEST,
content_type='application/vnd.api+json; application/json',
)
else:
# clear verification key (v2)
user_obj.verification_key_v2 = {}
# new verification key (v1) for CAS
user_obj.verification_key = generate_verification_key(verification_type=None)
try:
user_obj.set_password(password)
osf4m_source_tag, created = Tag.all_tags.get_or_create(name=CampaignSourceTags.Osf4m.value, system=True)
osf4m_claimed_tag, created = Tag.all_tags.get_or_create(name=CampaignClaimedTags.Osf4m.value, system=True)
if user_obj.all_tags.filter(id=osf4m_source_tag.id, system=True).exists():
user_obj.add_system_tag(osf4m_claimed_tag)
user_obj.save()
except exceptions.ChangePasswordError as error:
return JsonResponse(
{'errors': [{'detail': message} for message in error.messages]},
status=400,
content_type='application/vnd.api+json; application/json',
)
return Response(
status=status.HTTP_200_OK,
content_type='application/vnd.api+json; application/json',
)
class UserSettings(JSONAPIBaseView, generics.RetrieveUpdateAPIView, UserMixin):
permission_classes = (
drf_permissions.IsAuthenticatedOrReadOnly,
base_permissions.TokenHasScope,
CurrentUser,
)
required_read_scopes = [CoreScopes.USER_SETTINGS_READ]
required_write_scopes = [CoreScopes.USER_SETTINGS_WRITE]
throttle_classes = (SendEmailDeactivationThrottle,)
view_category = 'users'
view_name = 'user_settings'
serializer_class = UserSettingsSerializer
# overrides RetrieveUpdateAPIView
def get_serializer_class(self):
if self.request.method in ('PUT', 'PATCH'):
return UserSettingsUpdateSerializer
return UserSettingsSerializer
# overrides RetrieveUpdateAPIView
def get_object(self):
return self.get_user()
class ClaimUser(JSONAPIBaseView, generics.CreateAPIView, UserMixin):
permission_classes = (
base_permissions.TokenHasScope,
ClaimUserPermission,
)
required_read_scopes = [CoreScopes.NULL] # Tokens should not be able to access this
required_write_scopes = [CoreScopes.NULL] # Tokens should not be able to access this
view_category = 'users'
view_name = 'claim-user'
def _send_claim_email(self, *args, **kwargs):
""" This avoids needing to reimplement all of the logic in the sender methods.
When v1 is more fully deprecated, those send hooks should be reworked to not
rely upon a flask context and placed in utils (or elsewhere).
:param bool registered: Indicates which sender to call (passed in as keyword)
:param *args: Positional arguments passed to senders
:param **kwargs: Keyword arguments passed to senders
:return: None
"""
from website.app import app
from website.routes import make_url_map
try:
make_url_map(app)
except AssertionError:
# Already mapped
pass
ctx = app.test_request_context()
ctx.push()
if kwargs.pop('registered', False):
send_claim_registered_email(*args, **kwargs)
else:
send_claim_email(*args, **kwargs)
ctx.pop()