-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·2179 lines (1866 loc) · 108 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, jsonify, Response, render_template, session, redirect, url_for
from globus_sdk import AuthClient, AccessTokenAuthorizer, ConfidentialAppAuthClient
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from werkzeug.utils import secure_filename
import phpserialize
import json
import os
import random
import stat
from shutil import copyfile, copy2, rmtree
from datetime import datetime
import pathlib
import sys, traceback
import requests
from PIL import Image
from io import BytesIO
import ast
import urllib.parse
import urllib.request
import requests
import string
import random
from flask_mail import Mail, Message
from functools import wraps
from slugify import slugify
# For debugging
from pprint import pprint
# Init app and use the config from instance folder
app = Flask(__name__, instance_relative_config=True)
app.config.from_pyfile('app.cfg')
# Remove trailing slash / from URL base to avoid "//" caused by config with trailing slash
app.config['FLASK_APP_BASE_URI'] = app.config['FLASK_APP_BASE_URI'].strip('/')
app.config['CONNECTION_IMAGE_URL'] = app.config['CONNECTION_IMAGE_URL'].strip('/')
# The `stage_user` and `user_connection` tables don't use this prefix
wp_db_table_prefix = app.config['WP_DB_TABLE_PREFIX']
# Prefix for the Connections meta fields
connection_meta_key_prefix = app.config['CONNECTION_META_KEY_PREFIX']
# Flask-Mail instance
mail = Mail(app)
# Init DB
db = SQLAlchemy(app)
# Init MA
ma = Marshmallow(app)
# User-Connection mapping table
# No prefix
connects = db.Table('user_connection',
db.Column('user_id', db.Integer, db.ForeignKey(wp_db_table_prefix + 'users.id')),
db.Column('connection_id', db.Integer, db.ForeignKey(wp_db_table_prefix + 'connections.id'))
)
# StageUser Class/Model
class StageUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
globus_user_id = db.Column(db.String(100), unique=True)
globus_username = db.Column(db.String(200))
email = db.Column(db.String(200))
first_name = db.Column(db.String(200))
last_name = db.Column(db.String(200))
component = db.Column(db.String(200))
other_component = db.Column(db.String(200))
organization = db.Column(db.String(200))
other_organization = db.Column(db.String(200))
role = db.Column(db.String(100))
other_role = db.Column(db.String(200))
photo = db.Column(db.String(500))
photo_url = db.Column(db.String(500))
access_requests = db.Column(db.String(500)) # Checkboxes
globus_identity = db.Column(db.String(200))
google_email = db.Column(db.String(200))
github_username = db.Column(db.String(200))
slack_username = db.Column(db.String(200))
protocols_io_email = db.Column(db.String(200))
phone = db.Column(db.String(100))
website = db.Column(db.String(500))
bio = db.Column(db.Text)
orcid = db.Column(db.String(100))
pm = db.Column(db.Boolean)
pm_name = db.Column(db.String(100))
pm_email = db.Column(db.String(100))
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
deny = db.Column(db.Boolean)
globus_parsed_email = db.Column(db.String(200))
def __init__(self, a_dict):
try:
self.globus_user_id = a_dict['globus_user_id'] if 'globus_user_id' in a_dict else ''
self.globus_username = a_dict['globus_username'] if 'globus_username' in a_dict else ''
self.email = a_dict['email'] if 'email' in a_dict else ''
self.first_name = a_dict['first_name'] if 'first_name' in a_dict else ''
self.last_name = a_dict['last_name'] if 'last_name' in a_dict else ''
self.component = a_dict['component'] if 'component' in a_dict else ''
self.other_component = a_dict['other_component'] if 'other_component' in a_dict else ''
self.organization = a_dict['organization'] if 'organization' in a_dict else ''
self.other_organization = a_dict['other_organization'] if 'other_organization' in a_dict else ''
self.role = a_dict['role'] if 'role' in a_dict else ''
self.other_role = a_dict['other_role'] if 'other_role' in a_dict else ''
self.photo = a_dict['photo'] if 'photo' in a_dict else ''
self.photo_url = a_dict['photo_url'] if 'photo_url' in a_dict else ''
self.access_requests = json.dumps(a_dict['access_requests']) if 'access_requests' in a_dict else ''
self.globus_identity = a_dict['globus_identity'] if 'globus_identity' in a_dict else ''
self.google_email = a_dict['google_email'] if 'google_email' in a_dict else ''
self.github_username = a_dict['github_username'] if 'github_username' in a_dict else ''
self.slack_username = a_dict['slack_username'] if 'slack_username' in a_dict else ''
self.protocols_io_email = a_dict['protocols_io_email'] if 'protocols_io_email' in a_dict else ''
self.phone = a_dict['phone'] if 'phone' in a_dict else ''
self.website = a_dict['website'] if 'website' in a_dict else ''
self.bio = a_dict['bio'] if 'bio' in a_dict else ''
self.orcid = a_dict['orcid'] if 'orcid' in a_dict else ''
self.pm = a_dict['pm'] if 'pm' in a_dict else ''
self.pm_name = a_dict['pm_name'] if 'pm_name' in a_dict else ''
self.pm_email = a_dict['pm_email'] if 'pm_email' in a_dict else ''
self.globus_parsed_email = a_dict['globus_parsed_email'] if 'globus_parsed_email' in a_dict else ''
except e:
raise e
# Define output format with marshmallow schema
class StageUserSchema(ma.Schema):
class Meta:
fields = ('id', 'globus_user_id','globus_username', 'email', 'first_name', 'last_name', 'component', 'other_component', 'organization', 'other_organization',
'role', 'other_role', 'photo', 'photo_url', 'access_requests', 'globus_identity', 'google_email', 'github_username', 'slack_username', 'protocols_io_email', 'phone', 'website',
'bio', 'orcid', 'pm', 'pm_name', 'pm_email', 'created_at', 'deny', 'globus_parsed_email')
# WPUserMeta Class/Model
class WPUserMeta(db.Model):
__tablename__ = wp_db_table_prefix + 'usermeta'
umeta_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey(wp_db_table_prefix + 'users.id'), nullable=False)
meta_key = db.Column(db.String(255), nullable=False)
meta_value = db.Column(db.Text)
# WPUserMeta Schema
class WPUserMetaSchema(ma.Schema):
class Meta:
model = WPUserMeta
fields = ('umeta_id', 'user_id', 'meta_key', 'meta_value')
# ConnectionMeta
class ConnectionMeta(db.Model):
__tablename__ = wp_db_table_prefix + 'connections_meta'
meta_id = db.Column(db.Integer, primary_key=True)
entry_id = db.Column(db.Integer, db.ForeignKey(wp_db_table_prefix + 'connections.id'), nullable=False)
meta_key = db.Column(db.String(255), nullable=False)
meta_value = db.Column(db.Text)
# ConnectionMeta Schema
class ConnectionMetaSchema(ma.Schema):
class Meta:
fields = ('meta_id', 'entry_id', 'meta_key', 'meta_value')
class ConnectionEmail(db.Model):
__tablename__ = wp_db_table_prefix + 'connections_email'
id = db.Column(db.Integer, primary_key=True)
entry_id = db.Column(db.Integer, db.ForeignKey(wp_db_table_prefix + 'connections.id'), nullable=False)
order = db.Column(db.Integer)
preferred = db.Column(db.Integer)
type = db.Column(db.Text)
address = db.Column(db.Text)
visibility = db.Column(db.Text)
class ConnectionPhone(db.Model):
__tablename__ = wp_db_table_prefix + 'connections_phone'
id = db.Column(db.Integer, primary_key=True)
entry_id = db.Column(db.Integer, db.ForeignKey(wp_db_table_prefix + 'connections.id'), nullable=False)
order = db.Column(db.Integer)
preferred = db.Column(db.Integer)
type = db.Column(db.Text)
number = db.Column(db.Text)
visibility = db.Column(db.Text)
# Connection
class Connection(db.Model):
__tablename__ = wp_db_table_prefix + 'connections'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.Text)
first_name = db.Column(db.Text)
last_name = db.Column(db.Text)
organization = db.Column(db.Text)
options = db.Column(db.Text)
phone_numbers = db.Column(db.Text)
date_added = db.Column(db.Text)
entry_type = db.Column(db.Text)
visibility = db.Column(db.Text)
slug = db.Column(db.Text)
family_name = db.Column(db.Text)
honorific_prefix = db.Column(db.Text)
middle_name = db.Column(db.Text)
honorific_suffix = db.Column(db.Text)
title = db.Column(db.Text)
department = db.Column(db.Text)
contact_first_name = db.Column(db.Text)
contact_last_name = db.Column(db.Text)
addresses = db.Column(db.Text)
im = db.Column(db.Text)
social = db.Column(db.Text)
links = db.Column(db.Text)
dates = db.Column(db.Text)
birthday = db.Column(db.Text)
anniversary = db.Column(db.Text)
bio = db.Column(db.Text)
notes = db.Column(db.Text)
excerpt = db.Column(db.Text)
added_by = db.Column(db.Integer)
edited_by = db.Column(db.Integer)
owner = db.Column(db.Integer)
user = db.Column(db.Integer)
status = db.Column(db.String(20))
metas = db.relationship('ConnectionMeta', backref='connection', lazy='joined')
emails = db.relationship('ConnectionEmail', backref='connection', lazy='joined')
phones = db.relationship('ConnectionPhone', backref='connection', lazy='joined')
# Connection Schema
class ConnectionSchema(ma.Schema):
class Meta:
fields = ('id', 'first_name', 'last_name', 'email', 'phone_numbers', 'organization', 'department', 'title', 'bio', 'options', 'metas')
metas = ma.Nested(ConnectionMetaSchema, many=True)
# WPUser Class/Model
class WPUser(db.Model):
__tablename__ = wp_db_table_prefix + 'users'
id = db.Column(db.Integer, primary_key=True)
user_login = db.Column(db.String(60), nullable=False)
user_pass = db.Column(db.String(255), nullable=False)
user_email = db.Column(db.String(500), nullable=False)
metas = db.relationship('WPUserMeta', backref='user', lazy='joined')
connection = db.relationship('Connection', secondary=connects, backref=db.backref('owners', lazy='dynamic'))
# WPUser Schema
class WPUserSchema(ma.Schema):
class Meta:
model = WPUser
fields = ('id', 'user_login', 'user_email', 'metas', 'connection')
metas = ma.Nested(WPUserMetaSchema, many=True)
connection = ma.Nested(ConnectionSchema, many=True)
# Init schema
stage_user_schema = StageUserSchema(strict=True)
stage_users_schema = StageUserSchema(many=True, strict=True)
wp_user_schema = WPUserSchema(strict=True)
wp_users_schema = WPUserSchema(many=True, strict=True)
wp_user_meta_schema = WPUserMetaSchema(strict=True)
wp_user_metas_schema = WPUserMetaSchema(many=True, strict=True)
connection_schema = ConnectionSchema(strict=True)
connections_schema = ConnectionSchema(many=True, strict=True)
# Send email confirmation of new user registration to admins
def send_new_user_registered_mail(data):
data["access_requests"].sort();
msg = Message(subject='New user registration submitted', recipients=app.config['MAIL_ADMIN_LIST'])
msg.body = render_template('email/new_user_registered_email.txt', data = data)
msg.html = render_template('email/new_user_registered_email.html', data = data)
mail.send(msg)
# Send email to admins once user profile updated
# Only email when the access requests has changed
def send_user_profile_updated_mail(data, old_access_requests_data):
msg = Message('User profile updated', recipients=app.config['MAIL_ADMIN_LIST'])
# We need the values for the lists to be in order
# old_access_requests_data_sorted = dict(sorted(old_access_requests_data.items(), key=lambda item: item[1]))
old_access_requests_data["access_requests"].sort(); data["access_requests"].sort();
msg.body = render_template('email/user_profile_updated_email.txt', data = data, old_access_requests_data = old_access_requests_data)
msg.html = render_template('email/user_profile_updated_email.html', data = data, old_access_requests_data = old_access_requests_data)
mail.send(msg)
# Once admin approves the new user registration, email the new user as well as the admins
def send_new_user_approved_mail(recipient, data):
msg = Message('New user registration approved', recipients=[recipient] + app.config['MAIL_ADMIN_LIST'])
msg.body = render_template('email/new_user_approved_email.txt', data = data)
msg.html = render_template('email/new_user_approved_email.html', data = data)
mail.send(msg)
# Send user email once registration is denied
def send_new_user_denied_mail(recipient, data):
msg = Message('New user registration denied', recipients=[recipient] + app.config['MAIL_ADMIN_LIST'])
msg.body = render_template('email/new_user_denied_email.txt', data = data)
msg.html = render_template('email/new_user_denied_email.html', data = data)
mail.send(msg)
# Get user info from globus with the auth access token
def get_globus_user_info(token):
auth_client = AuthClient(authorizer=AccessTokenAuthorizer(token))
return auth_client.oauth2_userinfo()
# Create user info based on submitted form data
def construct_user(request):
photo_file = None
imgByteArr = None
# Users can only choose to upload image ,pull image from URL, or just the default image
# Values: "upload", "url", "default", or "existing"
# When "default" or "existing" (only happens when updating approved profile) selected
# no need to handle image from the client side
profile_pic_option = request.form['profile_pic_option'].lower()
if profile_pic_option == 'upload':
if 'photo' in request.files and request.files['photo']:
photo_file = request.files['photo']
elif profile_pic_option == 'url':
photo_url = request.form['photo_url']
if photo_url:
response = requests.get(photo_url)
img = Image.open(BytesIO(response.content))
imgByteArr = BytesIO()
img.save(imgByteArr, format=img.format)
imgByteArr = imgByteArr.getvalue()
# strip() removes any leading and trailing whitespaces including tabs (\t)
user_info = {
# Get the globus user id and globus username from session data
"globus_user_id": session['globus_user_id'],
"globus_username": session['globus_username'],
# All others are from the form data
"email": request.form['email'].strip(),
"first_name": request.form['first_name'].strip(),
"last_name": request.form['last_name'].strip(),
"phone": request.form['phone'].strip(),
"component": request.form['component'],
"other_component": request.form['other_component'].strip(),
"organization": request.form['organization'],
"other_organization": request.form['other_organization'].strip(),
"role": request.form['role'],
"other_role": request.form['other_role'].strip(),
"photo": '',
"photo_url": request.form['photo_url'].strip(),
# multiple checkboxes
"access_requests": request.form.getlist('access_requests'),
"globus_identity": request.form['globus_identity'].strip(),
"google_email": request.form['google_email'].strip(),
"github_username": request.form['github_username'].strip(),
"slack_username": request.form['slack_username'].strip(),
"protocols_io_email": request.form['protocols_io_email'].strip(),
"website": request.form['website'].strip(),
"bio": request.form['bio'],
"orcid": request.form['orcid'].strip(),
"pm": get_pm_selection(request.form['pm']),
"pm_name": request.form['pm_name'].strip(),
"pm_email": request.form['pm_email'].strip(),
"globus_parsed_email": request.form['globus_parsed_email'].strip(),
}
img_to_upload = photo_file if photo_file is not None else imgByteArr if imgByteArr is not None else None
return user_info, profile_pic_option, img_to_upload
def get_pm_selection(value):
# Make comparison case insensitive
value = value.lower()
if value == 'yes':
return True
elif value == 'no':
return False
else:
return None
# Generate CSRF tokens for registration form and profile form
def generate_csrf_token(stringLength = 10):
if 'csrf_token' not in session:
letters = string.ascii_lowercase
session['csrf_token'] = ''.join(random.choice(letters) for i in range(stringLength))
return session['csrf_token']
def show_registration_form():
# If user registered with their direct globus ID, we can't gurentee the "Full name" contains a space
# Because it's possible the users only entered firstname in "Full name" during globus ID registration on globus site
name_words = session['name'].split(" ")
context = {
'isAuthenticated': True,
'username': session['name'],
'csrf_token': generate_csrf_token(),
'globus_user_id': session['globus_user_id'],
'globus_username': session['globus_username'],
'first_name': name_words[0],
# Use empty for last name if not present
'last_name': name_words[1] if (len(name_words) > 1) else "",
# 'email': session['email'],
# Replacing the prefilled email with user-editable, and saving the globus email in a hidden field
'globus_parsed_email': session['email'],
'recaptcha_site_key': app.config['GOOGLE_RECAPTCHA_SITE_KEY']
}
print('show_registration_form(): context')
return render_template('register.html', data = context)
# Three different types of message for authenticated users
def show_user_error(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('user_message/user_error.html', data = context)
def show_user_confirmation(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('user_message/user_confirmation.html', data = context)
def show_user_info(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('user_message/user_info.html', data = context)
# Admin messages
def show_admin_error(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('admin_message/admin_error.html', data = context)
def show_admin_confirmation(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('admin_message/admin_confirmation.html', data = context)
def show_admin_info(message):
context = {
'isAuthenticated': True,
'username': session['name'],
'message': message
}
return render_template('admin_message/admin_info.html', data = context)
# Check if the user is registered and approved
# meaning this user is in `wp_users`, `wp_connections`, and `user_connection` tables and
# the user has the role of "member" or "administrator", the role is assigned when the user is approved
# A use with a submitted registration but pending is not consodered to be an approved user
def user_is_approved(globus_user_id):
user_meta = WPUserMeta.query.filter(WPUserMeta.meta_key.like('openid-connect-generic-subject-identity'), WPUserMeta.meta_value == globus_user_id).first()
if not user_meta:
print('user_is_approved(): No user found with globus_user_id: ' + globus_user_id)
return False
users = [user_meta.user]
result = wp_users_schema.dump(users)
user = result[0][0]
capabilities = next((meta for meta in user['metas'] if meta['meta_key'] == wp_db_table_prefix + 'capabilities'), {})
if (('meta_value' in capabilities) and ('member' in capabilities['meta_value'] or 'administrator' in capabilities['meta_value'])):
return True
else:
return False
# Check if user has the "administrator" role
def user_is_admin(globus_user_id):
user_meta = WPUserMeta.query.filter(WPUserMeta.meta_key.like('openid-connect-generic-subject-identity'), WPUserMeta.meta_value == globus_user_id).first()
if not user_meta:
print('user_is_admin(): No user found with globus_user_id: ' + globus_user_id)
return False
users = [user_meta.user]
result = wp_users_schema.dump(users)
user = result[0][0]
capabilities = next((meta for meta in user['metas'] if meta['meta_key'] == wp_db_table_prefix + 'capabilities'), {})
if (('meta_value' in capabilities) and ('administrator' in capabilities['meta_value'])):
return True
else:
return False
# Check if the user registration is still pending for approval in `stage_user` table
def user_in_pending(globus_user_id):
stage_user = StageUser.query.filter(StageUser.globus_user_id == globus_user_id)
if stage_user.count() == 0:
return False
return True
# Add new user reigstration to `stage_user` table
def add_new_stage_user(user_info, profile_pic_option, img_to_upload):
# First handle the profile image and save it to target directory
user_info['photo'] = handle_stage_user_profile_pic(user_info, profile_pic_option, img_to_upload)
try:
stage_user = StageUser(user_info)
except Exception as e:
print('User data is invalid')
print(e)
if StageUser.query.filter(StageUser.globus_user_id == stage_user.globus_user_id).first():
print('The same stage user exists')
else:
try:
db.session.add(stage_user)
db.session.commit()
except Exception as e:
print('Failed to add a new stage user')
print(e)
# Given a new user's first name and last name, get the unique slug name for `wp_connections`
# Expecially useful when multiple users have the same names: joe-smith, joe-smith-1, joe-smith-2
# The connections plugin uses slug as image folder name in cconnection-images
def unique_connection_slug(first_name, last_name, connection_id = None):
first_name = first_name.lower()
last_name = last_name.lower()
slug = slugify(first_name + '-' + last_name)
# If exisiting user updates first name and last name, make sure the new slug is not used
if connection_id:
# Filter conditions: different connection ID but the same first/last name
# Meaning the same user won't get a new slug
connections = Connection.query.filter(Connection.id != connection_id, db.func.lower(Connection.first_name) == first_name, db.func.lower(Connection.last_name) == last_name)
# If a new user's first name and last name the same as an exisiting user, also create a unique slug
else:
connections = Connection.query.filter(db.func.lower(Connection.first_name) == first_name, db.func.lower(Connection.last_name) == last_name)
if connections.count() > 0:
slug = slug + '-' + str(connections.count())
return slug
# Query the user data to populate into profile form
# This is different from get_wp_user() in that it also returns the meta and connection data
# from where we can parse all the profile data
def get_user_profile(globus_user_id):
user_meta = WPUserMeta.query.filter(WPUserMeta.meta_key.like('openid-connect-generic-subject-identity'), WPUserMeta.meta_value == globus_user_id).first()
if not user_meta:
print('No WP user found with globus_user_id: ' + globus_user_id)
return None
users = [user_meta.user]
result = wp_users_schema.dump(users)
user = result[0][0]
return user
# Only save image to the stage dir, once approved, will copy to target dir
def handle_stage_user_profile_pic(user_info, profile_pic_option, img_to_upload):
save_path = ''
if profile_pic_option == 'upload':
_, extension = img_to_upload.filename.rsplit('.', 1)
img_file = img_to_upload
save_path = os.path.join(app.config['STAGE_USER_IMAGE_DIR'], secure_filename(f"{user_info['globus_user_id']}.{extension}"))
img_file.save(save_path)
elif profile_pic_option == 'url':
response = requests.get(user_info['photo_url'])
img_file = Image.open(BytesIO(response.content))
extension = img_file.format
save_path = os.path.join(app.config['STAGE_USER_IMAGE_DIR'], secure_filename(f"{user_info['globus_user_id']}.{extension}"))
img_file.save(save_path)
else:
# Use default image
save_path = os.path.join(app.config['STAGE_USER_IMAGE_DIR'], secure_filename(f"{user_info['globus_user_id']}.png"))
source_file_path = os.path.join(app.root_path, 'static', 'images', 'default_profile.png')
copyfile(source_file_path, save_path)
# Also keep the file owner and group
keep_file_owner_and_group(source_file_path, save_path)
return save_path
# Save the profile image to target dir directly per user, no need to use stage image dir
def update_user_profile_pic(user_info, profile_pic_option, img_to_upload, image_dir, current_image_filename):
save_path = ''
if profile_pic_option == 'existing':
save_path = os.path.join(image_dir, current_image_filename)
elif profile_pic_option == 'upload':
_, extension = img_to_upload.filename.rsplit('.', 1)
img_file = img_to_upload
save_path = os.path.join(image_dir, secure_filename(f"{user_info['globus_user_id']}.{extension}"))
img_file.save(save_path)
elif profile_pic_option == 'url':
response = requests.get(user_info['photo_url'])
img_file = Image.open(BytesIO(response.content))
extension = img_file.format
save_path = os.path.join(image_dir, secure_filename(f"{user_info['globus_user_id']}.{extension}"))
img_file.save(save_path)
else:
# Use default image
save_path = os.path.join(image_dir, secure_filename(f"{user_info['globus_user_id']}.png"))
source_file_path = os.path.join(app.root_path, 'static', 'images', 'default_profile.png')
copyfile(source_file_path, save_path)
# Also keep the file owner and group
keep_file_owner_and_group(source_file_path, save_path)
return save_path
# Update user profile with user-provided information
def update_user_profile(connection_id, user_info, profile_pic_option, img_to_upload):
# First get the exisiting wp_user record with globus id
# this has no connection data
wp_user = get_wp_user(session['globus_user_id'])
# Get connection profile by connection id
connection_profile = get_connection_profile(connection_id)
# If by any chance the user updates first name or last name
# We need to copy old dir to the new image directory
# There won't be an existing dir due to unique_connection_slug()
# Copy old image to new image dir if user changed first/last name, AKA new unique slug name
current_slug = connection_profile.slug
current_image_dir = os.path.join(app.config['CONNECTION_IMAGE_DIR'], current_slug)
# If we see 'image' field in options, it means this user is added either via registration or WP connections plugin with an image
# thus there's an image folder with an image
try:
options = json.loads(connection_profile.options)
current_image_path = options['image']['meta']['original']['path']
current_image_filename = current_image_path.split('/')[-1]
# In case the image folder is gone if someone manually deleted it, we check to make and create one to avoid unknown errors
if not pathlib.Path(current_image_dir).exists():
pathlib.Path(current_image_dir).mkdir(parents=True, exist_ok=True)
# Otherwise, this connection entry is created directly from WP connections plugin without uploading an image
# thus there's no image folder created
except KeyError:
# We create the image folder
pathlib.Path(current_image_dir).mkdir(parents=True, exist_ok=True)
# Copy over the default image
current_image_filename = 'default_profile.png'
save_path = os.path.join(current_image_dir, secure_filename(f"{user_info['globus_user_id']}.png"))
source_file_path = os.path.join(app.root_path, 'static', 'images', current_image_filename)
copyfile(source_file_path, save_path)
# Also keep the file owner and group
keep_file_owner_and_group(source_file_path, save_path)
except TypeError:
# We create the image folder
pathlib.Path(current_image_dir).mkdir(parents=True, exist_ok=True)
# Copy over the default image
current_image_filename = 'default_profile.png'
save_path = os.path.join(current_image_dir, secure_filename(f"{user_info['globus_user_id']}.png"))
source_file_path = os.path.join(app.root_path, 'static', 'images', current_image_filename)
copyfile(source_file_path, save_path)
# Also keep the file owner and group
keep_file_owner_and_group(source_file_path, save_path)
# This exisiting user doesn't change first name and last name, so no need to get new unique slug
if (user_info['first_name'].lower() == connection_profile.first_name.lower()) and (user_info['last_name'].lower() == connection_profile.last_name.lower()):
# Update profile image directly
user_info['photo'] = update_user_profile_pic(user_info, profile_pic_option, img_to_upload, current_image_dir, current_image_filename)
# Otherwise, we need a new slug and create the new image folder and copy old images to this new location
else:
new_slug = unique_connection_slug(user_info['first_name'], user_info['last_name'], connection_id)
new_image_dir = os.path.join(app.config['CONNECTION_IMAGE_DIR'], new_slug)
# Create the new image folder
pathlib.Path(new_image_dir).mkdir(parents=True, exist_ok=True)
# Copy all old images to this new folder
for file in os.listdir(current_image_dir):
file_path = os.path.join(current_image_dir, file)
new_file_path = os.path.join(new_image_dir, file)
if os.path.isfile(file_path):
copy2(file_path, new_image_dir)
# Also keep the file owner and group
keep_file_owner_and_group(file_path, new_file_path)
# Finally delete the old image folder
try:
rmtree(current_image_dir)
except Exception as e:
print("Failed to delete the old profile image folder due to new slug: " + current_image_dir)
print(e)
user_info['photo'] = update_user_profile_pic(user_info, profile_pic_option, img_to_upload, new_image_dir, current_image_filename)
# Convert the user_info dict into object via StageUser() model
# So edit_connection() can be reused for approcing new user by editing matched and updating exisiting approved user
user_obj = StageUser(user_info)
edit_connection(user_obj, wp_user, connection_profile)
db.session.commit()
# This is user approval without using existing mathicng profile
# Approving by moving user data from `stage_user` into `wp_user` and `wp_connections`
# also add the ids to the `user_connection` table
def approve_stage_user_by_creating_new(stage_user):
# First need to check if there's an exisiting wp_user record with the same globus id
wp_user = get_wp_user(stage_user.globus_user_id)
if not wp_user:
# Create new user and meta
new_wp_user = create_new_user(stage_user)
# MUST do this before create_new_connection()
db.session.add(new_wp_user)
# Create profile in `wp_connections`
create_new_connection(stage_user, new_wp_user)
else:
edit_wp_user(stage_user)
create_new_connection(stage_user, wp_user)
db.session.delete(stage_user)
db.session.commit()
def approve_stage_user_by_editing_matched(stage_user_obj, connection_profile):
# First need to check if there's an exisiting wp_user record with the same globus id
wp_user = get_wp_user(stage_user_obj.globus_user_id)
if not wp_user:
# Create new user and meta
new_wp_user = create_new_user(stage_user_obj)
db.session.add(new_wp_user)
# Edit profile in `wp_connections`
edit_connection(stage_user_obj, new_wp_user, connection_profile, True)
else:
# Update the `wp_users` record
edit_wp_user(stage_user_obj)
edit_connection(stage_user_obj, wp_user, connection_profile, True)
db.session.delete(stage_user_obj)
db.session.commit()
# Edit the exisiting wp_user role as "member"
def edit_wp_user(stage_user_obj):
wp_user = get_wp_user(stage_user_obj.globus_user_id)
wp_user.user_login = stage_user_obj.email
wp_user.user_email = stage_user_obj.email
meta_capabilities = next((meta for meta in wp_user.metas if meta.meta_key == wp_db_table_prefix + 'capabilities'), None)
if meta_capabilities:
meta_capabilities.meta_value = "a:1:{s:6:\"member\";b:1;}"
def create_new_user(stage_user_obj):
# Create a new wp_user record
new_wp_user = WPUser()
new_wp_user.user_login = stage_user_obj.email
new_wp_user.user_email = stage_user_obj.email
new_wp_user.user_pass = generate_password()
# Create new usermeta for "member" role
meta_capabilities = WPUserMeta()
meta_capabilities.meta_key = wp_db_table_prefix + 'capabilities'
meta_capabilities.meta_value = "a:1:{s:6:\"member\";b:1;}"
new_wp_user.metas.append(meta_capabilities)
# Create new usermeta for globus id
meta_globus_user_id = WPUserMeta()
meta_globus_user_id.meta_key = "openid-connect-generic-subject-identity"
meta_globus_user_id.meta_value = stage_user_obj.globus_user_id
new_wp_user.metas.append(meta_globus_user_id)
# Create new usermeta for globus username
meta_globus_username = WPUserMeta()
meta_globus_username.meta_key = "globus_username"
meta_globus_username.meta_value = stage_user_obj.globus_username
new_wp_user.metas.append(meta_globus_username)
# Create new usermeta for globus email captured from legacy email support
meta_globus_parsed_email = WPUserMeta()
meta_globus_parsed_email.meta_key = "globus_parsed_email"
meta_globus_parsed_email.meta_value = stage_user_obj.globus_parsed_email
new_wp_user.metas.append(meta_globus_parsed_email)
return new_wp_user
def generate_password():
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = 16
return "".join(random.sample(s, passlen))
def create_new_connection(stage_user_obj, new_wp_user):
# First get the id of admin user in `wp_usermeta` table
admin_id = WPUserMeta.query.filter(WPUserMeta.meta_key.like('openid-connect-generic-subject-identity'), WPUserMeta.meta_value == session['globus_user_id']).first().user_id
connection = Connection()
connection_email = ConnectionEmail()
connection_email.order = 0
connection_email.preferred = 0
connection_email.type = 'work'
connection_email.address = stage_user_obj.email
connection_email.visibility = 'public'
connection.emails.append(connection_email)
connection_phone = ConnectionPhone()
connection_phone.order = 0
connection_phone.preferred = 0
connection_phone.type = 'workphone'
connection_phone.number = stage_user_obj.phone
connection_phone.visibility = 'public'
connection.phones.append(connection_phone)
connection.first_name = stage_user_obj.first_name
connection.last_name = stage_user_obj.last_name
connection.organization = stage_user_obj.organization
connection.department = stage_user_obj.component
connection.title = stage_user_obj.role
connection.date_added = str(datetime.today().timestamp())
connection.entry_type = 'individual'
connection.visibility = 'public'
# slug for new user doesn't require connection ID
connection.slug = unique_connection_slug(stage_user_obj.first_name, stage_user_obj.last_name, None)
connection.family_name = ''
connection.honorific_prefix = ''
connection.middle_name = ''
connection.honorific_suffix = ''
connection.contact_first_name = ''
connection.contact_last_name = ''
connection.addresses = 'a:0:{}'
connection.im = 'a:0:{}'
connection.social = 'a:0:{}'
connection.links = 'a:0:{}'
connection.dates = 'a:0:{}'
connection.birthday = ''
connection.anniversary = ''
connection.bio = stage_user_obj.bio
connection.notes = ''
connection.excerpt = ''
connection.added_by = admin_id
connection.edited_by = admin_id
connection.owner = admin_id
connection.user = 0
connection.status = 'approved'
# Initial values use empty then update later
connection.email = ''
connection.phone_numbers = ''
connection.options = ''
connection.owners.append(new_wp_user)
db.session.commit()
# Then update the rest and add metas
# Now get the id for email and phone to compose the email and phone for connections
connection.email = f"a:1:{{i:0;a:7:{{s:2:\"id\";i:{connection.emails[0].id};s:4:\"type\";s:4:\"work\";s:4:\"name\";s:10:\"Work Email\";s:10:\"visibility\";s:6:\"public\";s:5:\"order\";i:0;s:9:\"preferred\";b:0;s:7:\"address\";s:{len(connection.emails[0].address)}:\"{connection.emails[0].address}\";}}}}"
connection.phone_numbers = f"a:1:{{i:0;a:7:{{s:2:\"id\";i:{connection.phones[0].id};s:4:\"type\";s:9:\"workphone\";s:4:\"name\";s:10:\"Work Phone\";s:10:\"visibility\";s:6:\"public\";s:5:\"order\";i:0;s:9:\"preferred\";b:0;s:6:\"number\";s:{len(connection.phones[0].number)}:\"{connection.phones[0].number}\";}}}}"
# Handle profile image
# For new user registration, stage_user_obj.photo will never be empty
# So no need to check if stage_user_obj.photo === '' here like in edit_connection()
photo_file_name = stage_user_obj.photo.split('/')[-1]
target_image_dir = os.path.join(app.config['CONNECTION_IMAGE_DIR'], connection.slug)
pathlib.Path(target_image_dir).mkdir(parents=True, exist_ok=True)
new_file_path = os.path.join(target_image_dir, photo_file_name)
copyfile(stage_user_obj.photo, new_file_path)
# Also keep the file owner and group
keep_file_owner_and_group(stage_user_obj.photo, new_file_path)
# Delete stage image file
os.unlink(stage_user_obj.photo)
# Get the MIME type of image
image = Image.open(new_file_path)
content_type = Image.MIME[image.format]
image_path = os.path.join(app.config['CONNECTION_IMAGE_DIR'], connection.slug, photo_file_name)
image_url = app.config['CONNECTION_IMAGE_URL'] + "/" + connection.slug + "/" + photo_file_name
connection.options = "{\"entry\":{\"type\":\"individual\"},\"image\":{\"linked\":true,\"display\":true,\"name\":{\"original\":\"" + photo_file_name + "\"},\"meta\":{\"original\":{\"name\":\"" + photo_file_name + "\",\"path\":\"" + image_path + "\",\"url\": \"" + image_url + "\",\"width\":200,\"height\":200,\"size\":\"width=\\\"200\\\" height=\\\"200\\\"\",\"mime\":\"" + content_type + "\",\"type\":2}}}}"
globus_identity = stage_user_obj.globus_identity
google_email = stage_user_obj.google_email
globus_parsed_email = stage_user_obj.globus_parsed_email
github_username = stage_user_obj.github_username
slack_username = stage_user_obj.slack_username
protocols_io_email = stage_user_obj.protocols_io_email
# Other connections metas
connection_meta_component = ConnectionMeta()
connection_meta_component.meta_key = connection_meta_key_prefix + 'component'
connection_meta_component.meta_value = stage_user_obj.component
connection.metas.append(connection_meta_component)
connection_meta_other_component = ConnectionMeta()
connection_meta_other_component.meta_key = connection_meta_key_prefix + 'other_component'
connection_meta_other_component.meta_value = stage_user_obj.other_component
connection.metas.append(connection_meta_other_component)
connection_meta_organization = ConnectionMeta()
connection_meta_organization.meta_key = connection_meta_key_prefix + 'organization'
connection_meta_organization.meta_value = stage_user_obj.organization
connection.metas.append(connection_meta_organization)
connection_meta_other_organization = ConnectionMeta()
connection_meta_other_organization.meta_key = connection_meta_key_prefix + 'other_organization'
connection_meta_other_organization.meta_value = stage_user_obj.other_organization
connection.metas.append(connection_meta_other_organization)
connection_meta_role = ConnectionMeta()
connection_meta_role.meta_key = connection_meta_key_prefix + 'role'
connection_meta_role.meta_value = stage_user_obj.role
connection.metas.append(connection_meta_role)
connection_meta_other_role = ConnectionMeta()
connection_meta_other_role.meta_key = connection_meta_key_prefix + 'other_role'
connection_meta_other_role.meta_value = stage_user_obj.other_role
connection.metas.append(connection_meta_other_role)
connection_meta_access_requests = ConnectionMeta()
connection_meta_access_requests.meta_key = connection_meta_key_prefix + 'access_requests'
connection_meta_access_requests.meta_value = stage_user_obj.access_requests
connection.metas.append(connection_meta_access_requests)
connection_meta_globus_identity = ConnectionMeta()
connection_meta_globus_identity.meta_key = connection_meta_key_prefix + 'globus_identity'
connection_meta_globus_identity.meta_value = globus_identity
connection.metas.append(connection_meta_globus_identity)
connection_meta_google_email = ConnectionMeta()
connection_meta_google_email.meta_key = connection_meta_key_prefix + 'google_email'
connection_meta_google_email.meta_value = google_email
connection.metas.append(connection_meta_google_email)
connection_meta_github_username = ConnectionMeta()
connection_meta_github_username.meta_key = connection_meta_key_prefix + 'github_username'
connection_meta_github_username.meta_value = github_username
connection.metas.append(connection_meta_github_username)
connection_meta_slack_username = ConnectionMeta()
connection_meta_slack_username.meta_key = connection_meta_key_prefix + 'slack_username'
connection_meta_slack_username.meta_value = slack_username
connection.metas.append(connection_meta_slack_username)
connection_meta_protocols_io_email = ConnectionMeta()
connection_meta_protocols_io_email.meta_key = connection_meta_key_prefix + 'protocols_io_email'
connection_meta_protocols_io_email.meta_value = protocols_io_email
connection.metas.append(connection_meta_protocols_io_email)
connection_meta_website = ConnectionMeta()
connection_meta_website.meta_key = connection_meta_key_prefix + 'website'
connection_meta_website.meta_value = stage_user_obj.website
connection.metas.append(connection_meta_website)
connection_meta_orcid = ConnectionMeta()
connection_meta_orcid.meta_key = connection_meta_key_prefix + 'orcid'
connection_meta_orcid.meta_value = stage_user_obj.orcid
connection.metas.append(connection_meta_orcid)
connection_meta_pm = ConnectionMeta()
connection_meta_pm.meta_key = connection_meta_key_prefix + 'pm'
connection_meta_pm.meta_value = stage_user_obj.pm
connection.metas.append(connection_meta_pm)
connection_meta_pm_name = ConnectionMeta()
connection_meta_pm_name.meta_key = connection_meta_key_prefix + 'pm_name'
connection_meta_pm_name.meta_value = stage_user_obj.pm_name
connection.metas.append(connection_meta_pm_name)
connection_meta_pm_email = ConnectionMeta()
connection_meta_pm_email.meta_key = connection_meta_key_prefix + 'pm_email'
connection_meta_pm_email.meta_value = stage_user_obj.pm_email
connection.metas.append(connection_meta_pm_email)
connection_meta_globus_parsed_email = ConnectionMeta()
connection_meta_globus_parsed_email.meta_key = connection_meta_key_prefix + 'globus_parsed_email'
connection_meta_globus_parsed_email.meta_value = stage_user_obj.globus_parsed_email
connection.metas.append(connection_meta_globus_parsed_email)
# Overwrite the existing fields with the ones from user registration or profile update
def edit_connection(user_obj, wp_user, connection, new_user = False):
# First get the id of user in `wp_usermeta` table
# If this profile is approved by using a matching connection, the edit_user_id is the admin user id
# If this profile is updated by the user after approval, it's the user's id
edit_user_id = WPUserMeta.query.filter(WPUserMeta.meta_key.like('openid-connect-generic-subject-identity'), WPUserMeta.meta_value == session['globus_user_id']).first().user_id
# Handle the connections email and phone first
connection_email = ConnectionEmail()
connection_email.order = 0
connection_email.preferred = 0
connection_email.type = 'work'
connection_email.address = user_obj.email
connection_email.visibility = 'public'
connection_phone = ConnectionPhone()
connection_phone.order = 0
connection_phone.preferred = 0
connection_phone.type = 'workphone'
connection_phone.number = user_obj.phone
connection_phone.visibility = 'public'
existing_email = next((e for e in connection.emails if e.type == 'work'), None)