-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathviews.py
More file actions
827 lines (676 loc) · 28.5 KB
/
views.py
File metadata and controls
827 lines (676 loc) · 28.5 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
import logging
from rest_framework import status as http_status
from django.utils import timezone
from django.core.exceptions import ValidationError
from flask import request
from mailchimp3.mailchimpclient import MailChimpError
from framework import sentry
from framework.auth import utils as auth_utils
from framework.auth import cas
from framework.auth import logout as osf_logout
from framework.auth.decorators import collect_auth
from framework.auth.decorators import must_be_logged_in
from framework.auth.decorators import must_be_confirmed
from framework.auth.exceptions import ChangePasswordError
from framework.auth.views import send_confirm_email_async
from framework.auth.signals import (
user_account_merged,
user_account_deactivated,
user_account_reactivated,
)
from framework.exceptions import HTTPError, PermissionsError
from framework.flask import redirect # VOL-aware redirect
from framework.status import push_status_message
from framework.utils import throttle_period_expired
from osf import features
from osf.models import ApiOAuth2Application, ApiOAuth2PersonalToken, OSFUser
from osf.exceptions import BlockedEmailError, OSFError
from osf.utils.requests import string_type_request_headers
from website import mails
from website import mailchimp_utils
from website import settings
from website import language
from website.external_web_app.decorators import ember_flag_is_active
from website.oauth.utils import get_available_scopes
from website.profile import utils as profile_utils
from website.util import api_v2_url, web_url_for, paths
from website.util.sanitize import escape_html
from addons.base import utils as addon_utils
from osf.external.messages.celery_publishers import (
publish_reactivate_user,
publish_deactivated_user,
publish_merged_user
)
from api.waffle.utils import storage_i18n_flag_active
logger = logging.getLogger(__name__)
def validate_user(data, user):
"""Check if the user in request is the user who log in """
if 'id' in data:
if data['id'] != user._id:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
else:
# raise an error if request doesn't have user id
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data={'message_long': '"id" is required'})
@must_be_logged_in
def resend_confirmation(auth):
user = auth.user
data = request.get_json()
validate_user(data, user)
if not throttle_period_expired(user.email_last_sent, settings.SEND_EMAIL_THROTTLE):
raise HTTPError(http_status.HTTP_400_BAD_REQUEST,
data={'message_long': 'Too many requests. Please wait a while before sending another confirmation email.'})
try:
primary = data['email']['primary']
confirmed = data['email']['confirmed']
address = data['email']['address'].strip().lower()
except KeyError:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST)
if primary or confirmed:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data={'message_long': 'Cannnot resend confirmation for confirmed emails'})
user.add_unconfirmed_email(address)
# TODO: This setting is now named incorrectly.
if settings.CONFIRM_REGISTRATIONS_BY_EMAIL:
send_confirm_email_async(user, email=address)
user.email_last_sent = timezone.now()
user.save()
return _profile_view(user, is_profile=True)
@must_be_logged_in
def update_user(auth):
"""Update the logged-in user's profile."""
# trust the decorator to handle auth
user = auth.user
data = request.get_json()
validate_user(data, user)
# TODO: Expand this to support other user attributes
##########
# Emails #
##########
if 'emails' in data:
emails_list = [x['address'].strip().lower() for x in data['emails']]
if user.username.strip().lower() not in emails_list:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
available_emails = [
each.strip().lower() for each in
list(user.emails.values_list('address', flat=True)) + user.unconfirmed_emails
]
# removals
removed_emails = [
each.strip().lower()
for each in available_emails
if each not in emails_list
]
if user.username.strip().lower() in removed_emails:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
for address in removed_emails:
if user.emails.filter(address=address):
try:
user.remove_email(address)
except PermissionsError as e:
raise HTTPError(http_status.HTTP_403_FORBIDDEN, str(e))
user.remove_unconfirmed_email(address)
# additions
added_emails = [
each['address'].strip().lower()
for each in data['emails']
if each['address'].strip().lower() not in available_emails
]
for address in added_emails:
try:
user.add_unconfirmed_email(address)
except (ValidationError, ValueError):
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data=dict(
message_long='Invalid Email')
)
except BlockedEmailError:
sentry.log_message(
'User attempted to add a blocked email',
extra_data={
'user_id': user.id,
'address': address,
}
)
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data=dict(
message_long=language.BLOCKED_EMAIL)
)
# TODO: This setting is now named incorrectly.
if settings.CONFIRM_REGISTRATIONS_BY_EMAIL:
if not throttle_period_expired(user.email_last_sent, settings.SEND_EMAIL_THROTTLE):
raise HTTPError(http_status.HTTP_400_BAD_REQUEST,
data={'message_long': 'Too many requests. Please wait a while before adding an email to your account.'})
send_confirm_email_async(user, email=address)
############
# Username #
############
# get the first email that is set to primary and has an address
primary_email = next(each for each in data['emails']
# email is primary
if each.get('primary') and each.get('confirmed')
# an address is specified (can't trust those sneaky users!)
and each.get('address')
)
if primary_email:
primary_email_address = primary_email['address'].strip().lower()
if primary_email_address not in [each.strip().lower() for each in user.emails.values_list('address', flat=True)]:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
username = primary_email_address
# make sure the new username has already been confirmed
if username and username != user.username and user.emails.filter(address=username).exists():
mails.send_mail(
user.username,
mails.PRIMARY_EMAIL_CHANGED,
user=user,
new_address=username,
can_change_preferences=False,
osf_contact_email=settings.OSF_CONTACT_EMAIL
)
# Remove old primary email from subscribed mailing lists
for list_name, subscription in user.mailchimp_mailing_lists.items():
if subscription:
mailchimp_utils.unsubscribe_mailchimp_async(list_name, user._id, username=user.username)
user.username = username
###################
# Timezone/Locale #
###################
if 'locale' in data:
if data['locale']:
locale = data['locale'].replace('-', '_')
user.locale = locale
# TODO: Refactor to something like:
# user.timezone = data.get('timezone', user.timezone)
if 'timezone' in data:
if data['timezone']:
user.timezone = data['timezone']
user.save()
return _profile_view(user, is_profile=True)
def _profile_view(profile, is_profile=False, include_node_counts=False):
if profile and profile.is_disabled:
raise HTTPError(http_status.HTTP_410_GONE)
if profile:
profile_user_data = profile_utils.serialize_user(profile, full=True, is_profile=is_profile, include_node_counts=include_node_counts)
ret = {
'profile': profile_user_data,
'user': {
'_id': profile._id,
'is_profile': is_profile,
'can_edit': None, # necessary for rendering nodes
'permissions': [], # necessary for rendering nodes
},
}
return ret
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
@must_be_logged_in
def profile_view_json(auth):
return _profile_view(auth.user, True)
@collect_auth
@must_be_confirmed
def profile_view_id_json(uid, auth):
user = OSFUser.load(uid)
is_profile = auth and auth.user == user
# Do NOT embed nodes, they aren't necessary
return _profile_view(user, is_profile)
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_PROFILE)
def profile_view(auth):
# Embed node data, so profile node lists can be rendered
return _profile_view(auth.user, True, include_node_counts=True)
@collect_auth
@must_be_confirmed
def profile_view_id(uid, auth):
user = OSFUser.load(uid)
is_profile = auth and auth.user == user
# Embed node data, so profile node lists can be rendered
return _profile_view(user, is_profile, include_node_counts=True)
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS)
def user_profile(auth, **kwargs):
user = auth.user
return {
'user_id': user._id,
'user_api_url': user.api_url,
}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_ACCOUNTS)
def user_account(auth, **kwargs):
user = auth.user
user_addons = addon_utils.get_addons_by_config_type('user', user)
if 'password_reset' in request.args:
push_status_message('Password updated successfully.', kind='success', trust=False)
return {
'user_id': user._id,
'addons': user_addons,
'addons_js': collect_user_config_js([addon for addon in settings.ADDONS_AVAILABLE if 'user' in addon.configs]),
'addons_css': [],
'requested_deactivation': user.requested_deactivation,
'external_identity': user.external_identity,
'storage_flag_is_active': storage_i18n_flag_active(),
}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_ACCOUNTS)
def user_account_password(auth, **kwargs):
user = auth.user
old_password = request.form.get('old_password', None)
new_password = request.form.get('new_password', None)
confirm_password = request.form.get('confirm_password', None)
# 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):
push_status_message(
message='Too many failed attempts. Please wait a while before attempting to change your password.',
kind='warning',
trust=False
)
return redirect(web_url_for('user_account'))
try:
user.change_password(old_password, new_password, confirm_password)
except ChangePasswordError as error:
for m in error.messages:
push_status_message(m, kind='warning', trust=False)
else:
# We have to logout the user first so all CAS sessions are invalid
user.save()
osf_logout()
return redirect(cas.get_logout_url(cas.get_login_url(
web_url_for('user_account', _absolute=True) + '?password_reset=True',
username=user.username,
verification_key=user.verification_key,
)))
user.save()
return redirect(web_url_for('user_account'))
@must_be_logged_in
@ember_flag_is_active(features.ENABLE_GV)
def user_addons(auth, **kwargs):
user = auth.user
ret = {
'addon_settings': addon_utils.get_addons_by_config_type('accounts', user),
}
accounts_addons = [addon for addon in settings.ADDONS_AVAILABLE if 'accounts' in addon.configs]
ret.update({
'addon_enabled_settings': [addon.short_name for addon in accounts_addons],
'addons_js': collect_user_config_js(accounts_addons),
'addon_capabilities': settings.ADDON_CAPABILITIES,
'addons_css': []
})
return ret
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_NOTIFICATIONS)
def user_notifications(auth, **kwargs):
"""Get subscribe data from user"""
return {
'mailing_lists': dict(list(auth.user.mailchimp_mailing_lists.items()) + list(auth.user.osf_mailing_lists.items()))
}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_APPS)
def oauth_application_list(auth, **kwargs):
"""Return app creation page with list of known apps. API is responsible for tying list to current user."""
app_list_url = api_v2_url('applications/')
return {
'app_list_url': app_list_url
}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_APPS)
def oauth_application_register(auth, **kwargs):
"""Register an API application: blank form view"""
app_list_url = api_v2_url('applications/') # POST request to this url
return {'app_list_url': app_list_url,
'app_detail_url': ''}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_APPS)
def oauth_application_detail(auth, **kwargs):
"""Show detail for a single OAuth application"""
client_id = kwargs.get('client_id')
# The client ID must be an active and existing record, and the logged-in user must have permission to view it.
try:
record = ApiOAuth2Application.objects.get(client_id=client_id)
except ApiOAuth2Application.DoesNotExist:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
except ValueError: # Invalid client ID -- ApiOAuth2Application will not exist
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
if record.owner != auth.user:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
if record.is_active is False:
raise HTTPError(http_status.HTTP_410_GONE)
app_detail_url = api_v2_url(f'applications/{client_id}/') # Send request to this URL
return {'app_list_url': '',
'app_detail_url': app_detail_url}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_TOKENS)
def personal_access_token_list(auth, **kwargs):
"""Return token creation page with list of known tokens. API is responsible for tying list to current user."""
token_list_url = api_v2_url('tokens/')
return {
'token_list_url': token_list_url
}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_TOKENS)
def personal_access_token_register(auth, **kwargs):
"""Register a personal access token: blank form view"""
token_list_url = api_v2_url('tokens/') # POST request to this url
return {'token_list_url': token_list_url,
'token_detail_url': '',
'scope_options': get_available_scopes()}
@must_be_logged_in
@ember_flag_is_active(features.EMBER_USER_SETTINGS_TOKENS)
def personal_access_token_detail(auth, **kwargs):
"""Show detail for a single personal access token"""
_id = kwargs.get('_id')
# The ID must be an active and existing record, and the logged-in user must have permission to view it.
try:
record = ApiOAuth2PersonalToken.objects.get(_id=_id)
except ApiOAuth2PersonalToken.DoesNotExist:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
if record.owner != auth.user:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
if record.is_active is False:
raise HTTPError(http_status.HTTP_410_GONE)
token_detail_url = api_v2_url(f'tokens/{_id}/') # Send request to this URL
return {'token_list_url': '',
'token_detail_url': token_detail_url,
'scope_options': get_available_scopes()}
@must_be_logged_in
def delete_external_identity(auth, **kwargs):
"""Removes single external identity from user"""
data = request.get_json()
identity = data.get('identity')
if not identity:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST)
for service in auth.user.external_identity:
if identity in auth.user.external_identity[service]:
auth.user.external_identity[service].pop(identity)
if len(auth.user.external_identity[service]) == 0:
auth.user.external_identity.pop(service)
auth.user.save()
return
raise HTTPError(http_status.HTTP_404_NOT_FOUND, 'Unable to find requested identity')
def collect_user_config_js(addon_configs):
"""Collect webpack bundles for each of the addons' user-cfg.js modules. Return
the URLs for each of the JS modules to be included on the user addons config page.
:param list addons: List of user's addon config records.
"""
js_modules = []
for addon_config in addon_configs:
js_path = paths.resolve_addon_path(addon_config, 'user-cfg.js')
if js_path:
js_modules.append(js_path)
return js_modules
@must_be_logged_in
def user_choose_addons(**kwargs):
auth = kwargs['auth']
json_data = escape_html(request.get_json())
auth.user.config_addons(json_data, auth)
@must_be_logged_in
def user_choose_mailing_lists(auth, **kwargs):
""" Update mailing list subscription on user model and in mailchimp
Example input:
{
"Open Science Framework General": true,
...
}
"""
user = auth.user
json_data = escape_html(request.get_json())
if json_data:
for list_name, subscribe in json_data.items():
# TO DO: change this to take in any potential non-mailchimp, something like try: update_subscription(), except IndexNotFound: update_mailchimp_subscription()
if list_name == settings.OSF_HELP_LIST:
user.osf_mailing_lists[settings.OSF_HELP_LIST] = subscribe
else:
update_mailchimp_subscription(user, list_name, subscribe)
else:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data=dict(
message_long="Must provide a dictionary of the format {'mailing list name': Boolean}")
)
user.save()
all_mailing_lists = {}
all_mailing_lists.update(user.mailchimp_mailing_lists)
all_mailing_lists.update(user.osf_mailing_lists)
return {'message': 'Successfully updated mailing lists', 'result': all_mailing_lists}, 200
def update_mailchimp_subscription(user, list_name, subscription):
""" Update mailing list subscription in mailchimp.
:param obj user: current user
:param str list_name: mailing list
:param boolean subscription: true if user is subscribed
"""
if subscription:
mailchimp_utils.subscribe_mailchimp_async(list_name, user._id)
else:
try:
mailchimp_utils.unsubscribe_mailchimp_async(list_name, user._id, username=user.username)
except (MailChimpError, OSFError):
# User has already unsubscribed, so nothing to do
pass
@user_account_merged.connect
def send_account_merged_message(user):
""" Sends a message using Celery messaging to alert other services that an osf.io user has been merged."""
publish_merged_user(user)
@user_account_merged.connect
def unsubscribe_old_merged_account_from_mailchimp(user):
""" This is a merged account (an old account that was merged into an active one) so it needs to be unsubscribed
from mailchimp."""
for key, value in user.mailchimp_mailing_lists.items():
subscription = value or user.merged_by.mailchimp_mailing_lists.get(key)
update_mailchimp_subscription(user.merged_by, list_name=key, subscription=subscription)
update_mailchimp_subscription(user, list_name=key, subscription=False)
@user_account_deactivated.connect
def send_account_deactivation_message(user):
""" Sends a message using Celery messaging to alert other services that an osf.io user has been deactivated."""
publish_deactivated_user(user)
@user_account_reactivated.connect
def send_account_reactivation_message(user):
""" Sends a message using Celery messaging to alert other services that an osf.io user has been reactivated."""
publish_reactivate_user(user)
def mailchimp_get_endpoint(**kwargs):
"""Endpoint that the mailchimp webhook hits to check that the OSF is responding"""
return {}, http_status.HTTP_200_OK
def sync_data_from_mailchimp(**kwargs):
"""Endpoint that the mailchimp webhook sends its data to"""
key = request.args.get('key')
if key == settings.MAILCHIMP_WEBHOOK_SECRET_KEY:
r = request
action = r.values['type']
list_name = mailchimp_utils.get_list_name_from_id(list_id=r.values['data[list_id]'])
username = r.values['data[email]']
try:
user = OSFUser.objects.get(username=username)
except OSFUser.DoesNotExist as e:
sentry.log_exception(e)
sentry.log_message('A user with this username does not exist.')
raise HTTPError(404, data=dict(message_short='User not found',
message_long='A user with this username does not exist'))
if action == 'unsubscribe':
user.mailchimp_mailing_lists[list_name] = False
user.save()
elif action == 'subscribe':
user.mailchimp_mailing_lists[list_name] = True
user.save()
else:
# TODO: get tests to pass with sentry logging
# sentry.log_exception()
# sentry.log_message("Unauthorized request to the OSF.")
raise HTTPError(http_status.HTTP_401_UNAUTHORIZED)
@must_be_logged_in
def impute_names(**kwargs):
name = request.args.get('name', '')
return auth_utils.impute_names(name)
@must_be_logged_in
def serialize_names(**kwargs):
user = kwargs['auth'].user
return {
'full': user.fullname,
'given': user.given_name,
'middle': user.middle_names,
'family': user.family_name,
'suffix': user.suffix,
}
def get_target_user(auth, uid=None):
target = OSFUser.load(uid) if uid else auth.user
if target is None:
raise HTTPError(http_status.HTTP_404_NOT_FOUND)
return target
def append_editable(data, auth, uid=None):
target = get_target_user(auth, uid)
data['editable'] = auth.user == target
def serialize_social_addons(user):
ret = {}
for user_settings in user.get_addons():
config = user_settings.config
if user_settings.public_id:
ret[config.short_name] = user_settings.public_id
return ret
@collect_auth
def serialize_social(auth, uid=None, **kwargs):
target = get_target_user(auth, uid)
ret = target.social
append_editable(ret, auth, uid)
if ret['editable']:
ret['addons'] = serialize_social_addons(target)
return ret
def serialize_job(job):
return {
'institution': job.get('institution'),
'department': job.get('department'),
'title': job.get('title'),
'startMonth': job.get('startMonth'),
'startYear': job.get('startYear'),
'endMonth': job.get('endMonth'),
'endYear': job.get('endYear'),
'ongoing': job.get('ongoing', False),
}
def serialize_school(school):
return {
'institution': school.get('institution'),
'department': school.get('department'),
'degree': school.get('degree'),
'startMonth': school.get('startMonth'),
'startYear': school.get('startYear'),
'endMonth': school.get('endMonth'),
'endYear': school.get('endYear'),
'ongoing': school.get('ongoing', False),
}
def serialize_contents(field, func, auth, uid=None):
target = get_target_user(auth, uid)
ret = {
'contents': [
func(content)
for content in getattr(target, field)
]
}
append_editable(ret, auth, uid)
return ret
@collect_auth
def serialize_jobs(auth, uid=None, **kwargs):
ret = serialize_contents('jobs', serialize_job, auth, uid)
append_editable(ret, auth, uid)
return ret
@collect_auth
def serialize_schools(auth, uid=None, **kwargs):
ret = serialize_contents('schools', serialize_school, auth, uid)
append_editable(ret, auth, uid)
return ret
@must_be_logged_in
def unserialize_names(**kwargs):
user = kwargs['auth'].user
json_data = escape_html(request.get_json())
# json get can return None, use `or` here to ensure we always strip a string
user.fullname = (json_data.get('full') or '').strip()
user.given_name = (json_data.get('given') or '').strip()
user.middle_names = (json_data.get('middle') or '').strip()
user.family_name = (json_data.get('family') or '').strip()
user.suffix = (json_data.get('suffix') or '').strip()
user.save()
def verify_user_match(auth, **kwargs):
uid = kwargs.get('uid')
if uid and uid != auth.user._id:
raise HTTPError(http_status.HTTP_403_FORBIDDEN)
@must_be_logged_in
def unserialize_social(auth, **kwargs):
verify_user_match(auth, **kwargs)
user = auth.user
json_data = escape_html(request.get_json())
for soc in user.SOCIAL_FIELDS.keys():
user.social[soc] = json_data.get(soc)
try:
user.save()
except ValidationError as exc:
raise HTTPError(http_status.HTTP_400_BAD_REQUEST, data=dict(
message_long=exc.messages[0]
))
def unserialize_job(job):
return {
'institution': job.get('institution'),
'department': job.get('department'),
'title': job.get('title'),
'startMonth': job.get('startMonth'),
'startYear': job.get('startYear'),
'endMonth': job.get('endMonth'),
'endYear': job.get('endYear'),
'ongoing': job.get('ongoing'),
}
def unserialize_school(school):
return {
'institution': school.get('institution'),
'department': school.get('department'),
'degree': school.get('degree'),
'startMonth': school.get('startMonth'),
'startYear': school.get('startYear'),
'endMonth': school.get('endMonth'),
'endYear': school.get('endYear'),
'ongoing': school.get('ongoing'),
}
def unserialize_contents(field, func, auth):
user = auth.user
json_data = escape_html(request.get_json())
contents = [
func(content)
for content in json_data.get('contents', [])
]
setattr(
user,
field,
contents
)
user.save()
if contents:
saved_fields = {field: contents}
request_headers = string_type_request_headers(request)
user.check_spam(saved_fields=saved_fields, request_headers=request_headers)
@must_be_logged_in
def unserialize_jobs(auth, **kwargs):
verify_user_match(auth, **kwargs)
unserialize_contents('jobs', unserialize_job, auth)
# TODO: Add return value
@must_be_logged_in
def unserialize_schools(auth, **kwargs):
verify_user_match(auth, **kwargs)
unserialize_contents('schools', unserialize_school, auth)
# TODO: Add return value
@must_be_logged_in
def request_export(auth):
user = auth.user
if not throttle_period_expired(user.email_last_sent, settings.SEND_EMAIL_THROTTLE):
raise HTTPError(http_status.HTTP_400_BAD_REQUEST,
data={'message_long': 'Too many requests. Please wait a while before sending another account export request.',
'error_type': 'throttle_error'})
mails.send_mail(
to_addr=settings.OSF_SUPPORT_EMAIL,
mail=mails.REQUEST_EXPORT,
user=auth.user,
can_change_preferences=False,
)
user.email_last_sent = timezone.now()
user.save()
return {'message': 'Sent account export request'}
@must_be_logged_in
def request_deactivation(auth):
user = auth.user
user.requested_deactivation = True
user.save()
return {'message': 'Sent account deactivation request'}
@must_be_logged_in
def cancel_request_deactivation(auth):
user = auth.user
user.requested_deactivation = False
user.contacted_deactivation = False # In case we've already contacted them once.
user.save()
return {'message': 'You have canceled your deactivation request'}