-
Notifications
You must be signed in to change notification settings - Fork 332
/
user.py
1924 lines (1617 loc) · 76.6 KB
/
user.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
import datetime as dt
import logging
import re
from future.moves.urllib.parse import urljoin, urlencode
import uuid
from copy import deepcopy
from flask import Request as FlaskRequest
from framework import analytics
from guardian.shortcuts import get_perms
from past.builtins import basestring
# OSF imports
import itsdangerous
import pytz
from dirtyfields import DirtyFieldsMixin
from django.apps import apps
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import PermissionsMixin
from django.dispatch import receiver
from django.db import models
from django.db.models import Count
from django.db.models.signals import post_save
from django.utils import timezone
from guardian.shortcuts import get_objects_for_user
from framework.auth import Auth, signals, utils
from framework.auth.core import generate_verification_key
from framework.auth.exceptions import (ChangePasswordError, ExpiredTokenError,
InvalidTokenError,
MergeConfirmedRequiredError,
MergeConflictError)
from framework.exceptions import PermissionsError
from framework.sessions.utils import remove_sessions_for_user
from osf.utils.requests import get_current_request
from osf.exceptions import reraise_django_validation_errors, UserStateError
from osf.models.base import BaseModel, GuidMixin, GuidMixinQuerySet
from osf.models.notable_email_domain import NotableEmailDomain
from osf.models.contributor import Contributor, RecentlyAddedContributor
from osf.models.institution import Institution
from osf.models.mixins import AddonModelMixin
from osf.models.spam import SpamMixin
from osf.models.session import Session
from osf.models.tag import Tag
from osf.models.validators import validate_email, validate_social, validate_history_item
from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField
from osf.utils.fields import NonNaiveDateTimeField, LowercaseEmailField
from osf.utils.names import impute_names
from osf.utils.requests import check_select_for_update
from osf.utils.permissions import API_CONTRIBUTOR_PERMISSIONS, MANAGER, MEMBER, MANAGE, ADMIN
from website import settings as website_settings
from website import filters, mails
from website.project import new_bookmark_collection
from website.util.metrics import OsfSourceTags
logger = logging.getLogger(__name__)
MAX_QUICKFILES_MERGE_RENAME_ATTEMPTS = 1000
def get_default_mailing_lists():
return {'Open Science Framework Help': True}
name_formatters = {
'long': lambda user: user.fullname,
'surname': lambda user: user.family_name if user.family_name else user.fullname,
'initials': lambda user: u'{surname}, {initial}.'.format(
surname=user.family_name,
initial=user.given_name_initial,
),
}
class OSFUserManager(BaseUserManager):
def create_user(self, username, password=None):
if not username:
raise ValueError('Users must have a username')
user = self.model(
username=self.normalize_email(username),
is_active=True,
date_registered=timezone.now()
)
user.set_password(password)
user.save(using=self._db)
return user
_queryset_class = GuidMixinQuerySet
def all(self):
return self.get_queryset().all()
def eager(self, *fields):
fk_fields = set(self.model.get_fk_field_names()) & set(fields)
m2m_fields = set(self.model.get_m2m_field_names()) & set(fields)
return self.select_related(*fk_fields).prefetch_related(*m2m_fields)
def create_superuser(self, username, password):
user = self.create_user(username, password=password)
user.is_superuser = True
user.is_staff = True
user.is_active = True
user.save(using=self._db)
return user
class Email(BaseModel):
address = LowercaseEmailField(unique=True, db_index=True, validators=[validate_email])
user = models.ForeignKey('OSFUser', related_name='emails', on_delete=models.CASCADE)
def __unicode__(self):
return self.address
class OSFUser(DirtyFieldsMixin, GuidMixin, BaseModel, AbstractBaseUser, PermissionsMixin, AddonModelMixin, SpamMixin):
FIELD_ALIASES = {
'_id': 'guids___id',
'system_tags': 'tags',
}
settings_type = 'user' # Needed for addons
USERNAME_FIELD = 'username'
# Node fields that trigger an update to the search engine on save
SEARCH_UPDATE_FIELDS = {
'fullname',
'given_name',
'middle_names',
'family_name',
'suffix',
'merged_by',
'date_disabled',
'date_confirmed',
'jobs',
'schools',
'social',
}
# Overrides DirtyFieldsMixin, Foreign Keys checked by '<attribute_name>_id' rather than typical name.
FIELDS_TO_CHECK = SEARCH_UPDATE_FIELDS.copy()
FIELDS_TO_CHECK.update({'password', 'last_login', 'merged_by_id', 'username'})
# TODO: Add SEARCH_UPDATE_NODE_FIELDS, for fields that should trigger a
# search update for all nodes to which the user is a contributor.
SOCIAL_FIELDS = {
'orcid': u'http://orcid.org/{}',
'github': u'http://github.com/{}',
'scholar': u'http://scholar.google.com/citations?user={}',
'twitter': u'http://twitter.com/{}',
'profileWebsites': [],
'linkedIn': u'https://www.linkedin.com/{}',
'impactStory': u'https://impactstory.org/u/{}',
'researcherId': u'http://researcherid.com/rid/{}',
'researchGate': u'https://researchgate.net/profile/{}',
'academiaInstitution': u'https://{}',
'academiaProfileID': u'.academia.edu/{}',
'baiduScholar': u'http://xueshu.baidu.com/scholarID/{}',
'ssrn': u'http://papers.ssrn.com/sol3/cf_dev/AbsByAuth.cfm?per_id={}'
}
SPAM_USER_PROFILE_FIELDS = {
'schools': ['degree', 'institution', 'department'],
'jobs': ['title', 'institution', 'department']
}
# The primary email address for the account.
# This value is unique, but multiple "None" records exist for:
# * unregistered contributors where an email address was not provided.
# TODO: Update mailchimp subscription on username change in user.save()
# TODO: Consider making this a FK to Email with to_field='address'
# Django supports this (https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#django.contrib.auth.models.CustomUser.USERNAME_FIELD)
# but some third-party apps may not.
username = models.CharField(max_length=255, db_index=True, unique=True)
# Hashed. Use `User.set_password` and `User.check_password`
# password = models.CharField(max_length=255)
fullname = models.CharField(max_length=255)
# user has taken action to register the account
is_registered = models.BooleanField(db_index=True, default=False)
# for internal use
tags = models.ManyToManyField('Tag', blank=True)
# security emails that have been sent
# TODO: This should be removed and/or merged with system_tags
security_messages = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# <message label>: <datetime>
# ...
# }
# user was invited (as opposed to registered unprompted)
is_invited = models.BooleanField(default=False, db_index=True)
# Per-project unclaimed user data:
# TODO: add validation
unclaimed_records = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# <project_id>: {
# 'name': <name that referrer provided>,
# 'referrer_id': <user ID of referrer>,
# 'token': <token used for verification urls>,
# 'email': <email the referrer provided or None>,
# 'claimer_email': <email the claimer entered or None>,
# 'last_sent': <timestamp of last email sent to referrer or None>
# }
# ...
# }
# Time of last sent notification email to newly added contributors
# Format : {
# <project_id>: {
# 'last_sent': time.time()
# }
# ...
# }
contributor_added_email_records = DateTimeAwareJSONField(default=dict, blank=True)
# Tracks last email sent where user was added to an OSF Group
member_added_email_records = DateTimeAwareJSONField(default=dict, blank=True)
# Tracks last email sent where an OSF Group was connected to a node
group_connected_email_records = DateTimeAwareJSONField(default=dict, blank=True)
# The user into which this account was merged
merged_by = models.ForeignKey('self', null=True, blank=True, related_name='merger', on_delete=models.CASCADE)
# verification key v1: only the token string, no expiration time
# used for cas login with username and verification key
verification_key = models.CharField(max_length=255, null=True, blank=True)
# verification key v2: token, and expiration time
# used for password reset, confirm account/email, claim account/contributor-ship
verification_key_v2 = DateTimeAwareJSONField(default=dict, blank=True, null=True)
# Format: {
# 'token': <verification token>
# 'expires': <verification expiration time>
# }
email_last_sent = NonNaiveDateTimeField(null=True, blank=True)
change_password_last_attempt = NonNaiveDateTimeField(null=True, blank=True)
# Logs number of times user attempted to change their password where their
# old password was invalid
old_password_invalid_attempts = models.PositiveIntegerField(default=0)
# email verification tokens
# see also ``unconfirmed_emails``
email_verifications = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# <token> : {'email': <email address>,
# 'expiration': <datetime>}
# }
# email lists to which the user has chosen a subscription setting
mailchimp_mailing_lists = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# 'list1': True,
# 'list2: False,
# ...
# }
# email lists to which the user has chosen a subscription setting,
# being sent from osf, rather than mailchimp
osf_mailing_lists = DateTimeAwareJSONField(default=get_default_mailing_lists, blank=True)
# Format: {
# 'list1': True,
# 'list2: False,
# ...
# }
# the date this user was registered
date_registered = NonNaiveDateTimeField(db_index=True, auto_now_add=True)
# list of collaborators that this user recently added to nodes as a contributor
# recently_added = fields.ForeignField("user", list=True)
recently_added = models.ManyToManyField('self',
through=RecentlyAddedContributor,
through_fields=('user', 'contributor'),
symmetrical=False)
# Attached external accounts (OAuth)
# external_accounts = fields.ForeignField("externalaccount", list=True)
external_accounts = models.ManyToManyField('ExternalAccount', blank=True)
# CSL names
given_name = models.CharField(max_length=255, blank=True)
middle_names = models.CharField(max_length=255, blank=True)
family_name = models.CharField(max_length=255, blank=True)
suffix = models.CharField(max_length=255, blank=True)
# identity for user logged in through external idp
external_identity = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# <external_id_provider>: {
# <external_id>: <status from ('VERIFIED, 'CREATE', 'LINK')>,
# ...
# },
# ...
# }
# Employment history
jobs = DateTimeAwareJSONField(default=list, blank=True, validators=[validate_history_item])
# Format: list of {
# 'title': <position or job title>,
# 'institution': <institution or organization>,
# 'department': <department>,
# 'location': <location>,
# 'startMonth': <start month>,
# 'startYear': <start year>,
# 'endMonth': <end month>,
# 'endYear': <end year>,
# 'ongoing: <boolean>
# }
# Educational history
schools = DateTimeAwareJSONField(default=list, blank=True, validators=[validate_history_item])
# Format: list of {
# 'degree': <position or job title>,
# 'institution': <institution or organization>,
# 'department': <department>,
# 'location': <location>,
# 'startMonth': <start month>,
# 'startYear': <start year>,
# 'endMonth': <end month>,
# 'endYear': <end year>,
# 'ongoing: <boolean>
# }
# Social links
social = DateTimeAwareJSONField(default=dict, blank=True, validators=[validate_social])
# Format: {
# 'profileWebsites': <list of profile websites>
# 'twitter': <list of twitter usernames>,
# 'github': <list of github usernames>,
# 'linkedIn': <list of linkedin profiles>,
# 'orcid': <orcid for user>,
# 'researcherID': <researcherID>,
# 'impactStory': <impactStory identifier>,
# 'scholar': <google scholar identifier>,
# 'ssrn': <SSRN username>,
# 'researchGate': <researchGate username>,
# 'baiduScholar': <bauduScholar username>,
# 'academiaProfileID': <profile identifier for academia.edu>
# }
# date the user last sent a request
date_last_login = NonNaiveDateTimeField(null=True, blank=True, db_index=True)
# date the user first successfully confirmed an email address
date_confirmed = NonNaiveDateTimeField(db_index=True, null=True, blank=True)
# When the user was disabled.
date_disabled = NonNaiveDateTimeField(db_index=True, null=True, blank=True)
# When the user was soft-deleted (GDPR)
deleted = NonNaiveDateTimeField(db_index=True, null=True, blank=True)
# when comments were last viewed
comments_viewed_timestamp = DateTimeAwareJSONField(default=dict, blank=True)
# Format: {
# 'Comment.root_target._id': 'timestamp',
# ...
# }
# timezone for user's locale (e.g. 'America/New_York')
timezone = models.CharField(blank=True, default='Etc/UTC', max_length=255)
# user language and locale data (e.g. 'en_US')
locale = models.CharField(blank=True, max_length=255, default='en_US')
# whether the user has requested to deactivate their account
requested_deactivation = models.BooleanField(default=False)
# whether the user has who requested deactivation has been contacted about their pending request. This is reset when
# requests are canceled
contacted_deactivation = models.BooleanField(default=False)
affiliated_institutions = models.ManyToManyField('Institution', blank=True)
notifications_configured = DateTimeAwareJSONField(default=dict, blank=True)
# The time at which the user agreed to our updated ToS and Privacy Policy (GDPR, 25 May 2018)
accepted_terms_of_service = NonNaiveDateTimeField(null=True, blank=True)
chronos_user_id = models.TextField(null=True, blank=True, db_index=True)
# The primary department to which the institution user belongs,
# in case we support multiple departments in the future.
department = models.TextField(null=True, blank=True)
objects = OSFUserManager()
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
def __repr__(self):
return '<OSFUser({0!r}) with guid {1!r}>'.format(self.username, self._id)
@property
def deep_url(self):
"""Used for GUID resolution."""
return '/profile/{}/'.format(self._primary_key)
@property
def url(self):
return '/{}/'.format(self._id)
@property
def absolute_url(self):
return urljoin(website_settings.DOMAIN, self.url)
@property
def absolute_api_v2_url(self):
from website import util
return util.api_v2_url('users/{}/'.format(self._id))
@property
def api_url(self):
return '/api/v1/profile/{}/'.format(self._id)
@property
def profile_url(self):
return '/{}/'.format(self._id)
@property
def is_disabled(self):
return self.date_disabled is not None
@is_disabled.setter
def is_disabled(self, val):
"""Set whether or not this account has been disabled."""
if val and not self.date_disabled:
self.date_disabled = timezone.now()
elif val is False:
self.date_disabled = None
@property
def is_confirmed(self):
return bool(self.date_confirmed)
@property
def is_merged(self):
"""Whether or not this account has been merged into another account.
"""
return self.merged_by is not None
@property
def unconfirmed_emails(self):
# Handle when email_verifications field is None
email_verifications = self.email_verifications or {}
return [
each['email']
for each
in email_verifications.values()
]
@property
def social_links(self):
"""
Returns a dictionary of formatted social links for a user.
Social account values which are stored as account names are
formatted into appropriate social links. The 'type' of each
respective social field value is dictated by self.SOCIAL_FIELDS.
I.e. If a string is expected for a specific social field that
permits multiple accounts, a single account url will be provided for
the social field to ensure adherence with self.SOCIAL_FIELDS.
"""
social_user_fields = {}
for key, val in self.social.items():
if val and key in self.SOCIAL_FIELDS:
if isinstance(self.SOCIAL_FIELDS[key], basestring):
if isinstance(val, basestring):
social_user_fields[key] = self.SOCIAL_FIELDS[key].format(val)
else:
# Only provide the first url for services where multiple accounts are allowed
social_user_fields[key] = self.SOCIAL_FIELDS[key].format(val[0])
else:
if isinstance(val, basestring):
social_user_fields[key] = [val]
else:
social_user_fields[key] = val
return social_user_fields
@property
def given_name_initial(self):
"""
The user's preferred initialization of their given name.
Some users with common names may choose to distinguish themselves from
their colleagues in this way. For instance, there could be two
well-known researchers in a single field named "Robert Walker".
"Walker, R" could then refer to either of them. "Walker, R.H." could
provide easy disambiguation.
NOTE: The internal representation for this should never end with a
period. "R" and "R.H" would be correct in the prior case, but
"R.H." would not.
"""
return self.given_name[0]
@property
def email(self):
if self.has_usable_username():
return self.username
else:
return None
@property
def all_tags(self):
"""Return a queryset containing all of this user's tags (incl. system tags)."""
# Tag's default manager only returns non-system tags, so we can't use self.tags
return Tag.all_tags.filter(osfuser=self)
@property
def system_tags(self):
"""The system tags associated with this node. This currently returns a list of string
names for the tags, for compatibility with v1. Eventually, we can just return the
QuerySet.
"""
return self.all_tags.filter(system=True).values_list('name', flat=True)
@property
def csl_given_name(self):
return utils.generate_csl_given_name(self.given_name, self.middle_names, self.suffix)
def csl_name(self, node_id=None):
# disabled users are set to is_registered = False but have a fullname
if self.is_registered or self.is_disabled:
name = self.fullname
else:
name = self.get_unclaimed_record(node_id)['name']
if self.family_name and self.given_name:
"""If the user has a family and given name, use those"""
return {
'family': self.family_name,
'given': self.csl_given_name,
}
else:
""" If the user doesn't autofill his family and given name """
parsed = utils.impute_names(name)
given_name = parsed['given']
middle_names = parsed['middle']
family_name = parsed['family']
suffix = parsed['suffix']
csl_given_name = utils.generate_csl_given_name(given_name, middle_names, suffix)
return {
'family': family_name,
'given': csl_given_name,
}
@property
def osfstorage_region(self):
from addons.osfstorage.models import Region
osfs_settings = self._settings_model('osfstorage')
region_subquery = osfs_settings.objects.get(owner=self.id).default_region_id
return Region.objects.get(id=region_subquery)
@property
def contributor_to(self):
"""
Nodes that user has perms to through contributorship - group membership not factored in
"""
return self.nodes.filter(is_deleted=False, type__in=['osf.node', 'osf.registration'])
@property
def visible_contributor_to(self):
"""
Nodes where user is a bibliographic contributor (group membership not factored in)
"""
return self.nodes.filter(is_deleted=False, contributor__visible=True, type__in=['osf.node', 'osf.registration'])
@property
def all_nodes(self):
"""
Return all AbstractNodes that the user has explicit permissions to - either through contributorship or group membership
- similar to guardian.get_objects_for_user(self, READ_NODE, AbstractNode, with_superuser=False), but not looking at
NodeUserObjectPermissions, just NodeGroupObjectPermissions.
"""
from osf.models import AbstractNode
return AbstractNode.objects.get_nodes_for_user(self)
@property
def contributor_or_group_member_to(self):
"""
Nodes and registrations that user has perms to through contributorship or group membership
"""
return self.all_nodes.filter(type__in=['osf.node', 'osf.registration'])
@property
def nodes_contributor_or_group_member_to(self):
"""
Nodes that user has perms to through contributorship or group membership
"""
from osf.models import Node
return Node.objects.get_nodes_for_user(self)
def set_unusable_username(self):
"""Sets username to an unusable value. Used for, e.g. for invited contributors
and merged users.
NOTE: This is necessary because Django does not allow the username column to be nullable.
"""
if self._id:
self.username = self._id
else:
self.username = str(uuid.uuid4())
return self.username
def has_usable_username(self):
return '@' in self.username
@property
def is_authenticated(self): # Needed for django compat
return True
@property
def is_anonymous(self):
return False
@property
def osf_groups(self):
"""
OSFGroups that the user belongs to
"""
OSFGroup = apps.get_model('osf.OSFGroup')
return get_objects_for_user(self, 'member_group', OSFGroup, with_superuser=False)
def group_role(self, group):
"""
For the given OSFGroup, return the user's role - either member or manager
"""
if group.is_manager(self):
return MANAGER
elif group.is_member(self):
return MEMBER
else:
return None
def get_absolute_url(self):
return self.absolute_api_v2_url
def get_addon_names(self):
return []
# django methods
def get_full_name(self):
return self.fullname
def get_short_name(self):
return self.username
def __unicode__(self):
return self.get_short_name()
def __str__(self):
return self.get_short_name()
def get_verified_external_id(self, external_service, verified_only=False):
identifier_info = self.external_identity.get(external_service, {})
for external_id, status in identifier_info.items():
if status and status == 'VERIFIED' or not verified_only:
return external_id
return None
@property
def contributed(self):
return self.nodes.all()
@property
def can_be_merged(self):
"""The ability of the `merge_user` method to fully merge the user"""
return all((addon.can_be_merged for addon in self.get_addons()))
def merge_user(self, user):
"""Merge a registered user into this account. This user will be
a contributor on any project. if the registered user and this account
are both contributors of the same project. Then it will remove the
registered user and set this account to the highest permission of the two
and set this account to be visible if either of the two are visible on
the project.
:param user: A User object to be merged.
"""
# Attempt to prevent self merges which end up removing self as a contributor from all projects
if self == user:
raise ValueError('Cannot merge a user into itself')
# Fail if the other user has conflicts.
if not user.can_be_merged:
raise MergeConflictError('Users cannot be merged')
# Move over the other user's attributes
# TODO: confirm
for system_tag in user.system_tags.all():
self.add_system_tag(system_tag)
self.is_registered = self.is_registered or user.is_registered
self.is_invited = self.is_invited or user.is_invited
self.is_superuser = self.is_superuser or user.is_superuser
self.is_staff = self.is_staff or user.is_staff
# copy over profile only if this user has no profile info
if user.jobs and not self.jobs:
self.jobs = user.jobs
if user.schools and not self.schools:
self.schools = user.schools
if user.social and not self.social:
self.social = user.social
unclaimed = user.unclaimed_records.copy()
unclaimed.update(self.unclaimed_records)
self.unclaimed_records = unclaimed
# - unclaimed records should be connected to only one user
user.unclaimed_records = {}
security_messages = user.security_messages.copy()
security_messages.update(self.security_messages)
self.security_messages = security_messages
notifications_configured = user.notifications_configured.copy()
notifications_configured.update(self.notifications_configured)
self.notifications_configured = notifications_configured
if not website_settings.RUNNING_MIGRATION:
for key, value in user.mailchimp_mailing_lists.items():
# subscribe to each list if either user was subscribed
subscription = value or self.mailchimp_mailing_lists.get(key)
signals.user_merged.send(self, list_name=key, subscription=subscription)
# clear subscriptions for merged user
signals.user_merged.send(user, list_name=key, subscription=False, send_goodbye=False)
for target_id, timestamp in user.comments_viewed_timestamp.items():
if not self.comments_viewed_timestamp.get(target_id):
self.comments_viewed_timestamp[target_id] = timestamp
elif timestamp > self.comments_viewed_timestamp[target_id]:
self.comments_viewed_timestamp[target_id] = timestamp
# Give old user's emails to self
user.emails.update(user=self)
for k, v in user.email_verifications.items():
email_to_confirm = v['email']
if k not in self.email_verifications and email_to_confirm != user.username:
self.email_verifications[k] = v
user.email_verifications = {}
self.affiliated_institutions.add(*user.affiliated_institutions.values_list('pk', flat=True))
for service in user.external_identity:
for service_id in user.external_identity[service].keys():
if not (
service_id in self.external_identity.get(service, '') and
self.external_identity[service][service_id] == 'VERIFIED'
):
# Prevent 'CREATE', merging user has already been created.
external = user.external_identity[service][service_id]
status = 'VERIFIED' if external == 'VERIFIED' else 'LINK'
if self.external_identity.get(service):
self.external_identity[service].update(
{service_id: status}
)
else:
self.external_identity[service] = {
service_id: status
}
user.external_identity = {}
# FOREIGN FIELDS
self.external_accounts.add(*user.external_accounts.values_list('pk', flat=True))
# - addons
# Note: This must occur before the merged user is removed as a
# contributor on the nodes, as an event hook is otherwise fired
# which removes the credentials.
for addon in user.get_addons():
user_settings = self.get_or_add_addon(addon.config.short_name)
user_settings.merge(addon)
user_settings.save()
# - projects where the user was a contributor (group member only are not included).
for node in user.contributed:
# Skip quickfiles
if node.is_quickfiles:
continue
user_perms = Contributor(node=node, user=user).permission
# if both accounts are contributor of the same project
if node.is_contributor(self) and node.is_contributor(user):
self_perms = Contributor(node=node, user=self).permission
permissions = API_CONTRIBUTOR_PERMISSIONS[max(API_CONTRIBUTOR_PERMISSIONS.index(user_perms), API_CONTRIBUTOR_PERMISSIONS.index(self_perms))]
node.set_permissions(user=self, permissions=permissions)
visible1 = self._id in node.visible_contributor_ids
visible2 = user._id in node.visible_contributor_ids
if visible1 != visible2:
node.set_visible(user=self, visible=True, log=True, auth=Auth(user=self))
node.contributor_set.filter(user=user).delete()
else:
node.contributor_set.filter(user=user).update(user=self)
node.add_permission(self, user_perms)
node.remove_permission(user, user_perms)
node.save()
# Skip bookmark collections
user.collection_set.exclude(is_bookmark_collection=True).update(creator=self)
from osf.models import QuickFilesNode
from osf.models import BaseFileNode
# - projects where the user was the creator
user.nodes_created.exclude(type=QuickFilesNode._typedmodels_type).update(creator=self)
# - file that the user has checked_out, import done here to prevent import error
for file_node in BaseFileNode.files_checked_out(user=user):
file_node.checkout = self
file_node.save()
# Transfer user's preprints
self._merge_users_preprints(user)
# Transfer user's draft registrations
self._merge_user_draft_registrations(user)
# transfer group membership
for group in user.osf_groups:
if not group.is_manager(self):
if group.has_permission(user, MANAGE):
group.make_manager(self)
else:
group.make_member(self)
group.remove_member(user)
# finalize the merge
remove_sessions_for_user(user)
# - username is set to the GUID so the merging user can set it primary
# in the future (note: it cannot be set to None due to non-null constraint)
user.set_unusable_username()
user.set_unusable_password()
user.verification_key = None
user.osf_mailing_lists = {}
user.merged_by = self
user.save()
def _merge_users_preprints(self, user):
"""
Preprints use guardian. The PreprintContributor table stores order and bibliographic information.
Permissions are stored on guardian tables. PreprintContributor information needs to be transferred
from user -> self, and preprint permissions need to be transferred from user -> self.
"""
from osf.models.preprint import PreprintContributor
# Loop through `user`'s preprints
for preprint in user.preprints.all():
user_contributor = PreprintContributor.objects.get(preprint=preprint, user=user)
user_perms = user_contributor.permission
# Both `self` and `user` are contributors on the preprint
if preprint.is_contributor(self) and preprint.is_contributor(user):
self_contributor = PreprintContributor.objects.get(preprint=preprint, user=self)
self_perms = self_contributor.permission
max_perms_index = max(API_CONTRIBUTOR_PERMISSIONS.index(self_perms), API_CONTRIBUTOR_PERMISSIONS.index(user_perms))
# Add the highest of `self` perms or `user` perms to `self`
preprint.set_permissions(user=self, permissions=API_CONTRIBUTOR_PERMISSIONS[max_perms_index])
if not self_contributor.visible and user_contributor.visible:
# if `self` is not visible, but `user` is visible, make `self` visible.
preprint.set_visible(user=self, visible=True, log=True, auth=Auth(user=self))
# Now that perms and bibliographic info have been transferred to `self` contributor,
# delete `user` contributor
user_contributor.delete()
else:
# `self` is not a contributor, but `user` is. Transfer `user` permissions and
# contributor information to `self`. Remove permissions from `user`.
preprint.contributor_set.filter(user=user).update(user=self)
preprint.add_permission(self, user_perms)
if preprint.creator == user:
preprint.creator = self
preprint.remove_permission(user, user_perms)
preprint.save()
@property
def draft_registrations_active(self):
"""
Active draft registrations attached to a user (user is a contributor)
"""
return self.draft_registrations.filter(
(models.Q(registered_node__isnull=True) | models.Q(registered_node__deleted__isnull=False)),
branched_from__deleted__isnull=True,
deleted__isnull=True,
)
def _merge_user_draft_registrations(self, user):
"""
Draft Registrations have contributors, and this model uses guardian.
The DraftRegistrationContributor table stores order and bibliographic information.
Permissions are stored on guardian tables. DraftRegistration information needs to be transferred
from user -> self, and draft registration permissions need to be transferred from user -> self.
"""
from osf.models import DraftRegistrationContributor
# Loop through `user`'s draft registrations
for draft_reg in user.draft_registrations.all():
user_contributor = DraftRegistrationContributor.objects.get(draft_registration=draft_reg, user=user)
user_perms = user_contributor.permission
# Both `self` and `user` are contributors on the draft reg
if draft_reg.is_contributor(self) and draft_reg.is_contributor(user):
self_contributor = DraftRegistrationContributor.objects.get(draft_registration=draft_reg, user=self)
self_perms = self_contributor.permission
max_perms_index = max(API_CONTRIBUTOR_PERMISSIONS.index(self_perms), API_CONTRIBUTOR_PERMISSIONS.index(user_perms))
# Add the highest of `self` perms or `user` perms to `self`
draft_reg.set_permissions(user=self, permissions=API_CONTRIBUTOR_PERMISSIONS[max_perms_index])
if not self_contributor.visible and user_contributor.visible:
# if `self` is not visible, but `user` is visible, make `self` visible.
draft_reg.set_visible(user=self, visible=True, log=True, auth=Auth(user=self))
# Now that perms and bibliographic info have been transferred to `self` contributor,
# delete `user` contributor
user_contributor.delete()
else:
# `self` is not a contributor, but `user` is. Transfer `user` permissions and
# contributor information to `self`. Remove permissions from `user`.
draft_reg.contributor_set.filter(user=user).update(user=self)
draft_reg.add_permission(self, user_perms)
if draft_reg.initiator == user:
draft_reg.initiator = self
draft_reg.remove_permission(user, user_perms)
draft_reg.save()
def deactivate_account(self):
"""
Disables user account, making is_disabled true, while also unsubscribing user
from mailchimp emails, remove any existing sessions.
Ported from framework/auth/core.py
"""
from website import mailchimp_utils
from framework.auth import logout
try:
mailchimp_utils.unsubscribe_mailchimp(
list_name=website_settings.MAILCHIMP_GENERAL_LIST,
user_id=self._id,
username=self.username
)
except mailchimp_utils.mailchimp.ListNotSubscribedError:
pass
except mailchimp_utils.mailchimp.InvalidApiKeyError:
if not website_settings.ENABLE_EMAIL_SUBSCRIPTIONS:
pass
else:
raise
except mailchimp_utils.mailchimp.EmailNotExistsError:
pass
# Call to `unsubscribe` above saves, and can lead to stale data
self.reload()
self.is_disabled = True
# we must call both methods to ensure the current session is cleared and all existing
# sessions are revoked.
req = get_current_request()
if isinstance(req, FlaskRequest):
logout()
remove_sessions_for_user(self)
def reactivate_account(self):
"""
Enable user account
"""
self.is_disabled = False
self.requested_deactivation = False
from website.mailchimp_utils import subscribe_on_confirm
subscribe_on_confirm(self)
def update_is_active(self):
"""Update ``is_active`` to be consistent with the fields that
it depends on.
"""
# The user can log in if they have set a password OR