This repository has been archived by the owner on Jan 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
serve.py
executable file
·3336 lines (2956 loc) · 122 KB
/
serve.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
#! /usr/bin/python3
# Dependencies
# ============
# Standard
# --------
import os
import os.path
import sys
import re
import urllib
import json
import unicodedata
import html
import subprocess
from datetime import datetime, timezone
from email.utils import parsedate_tz, mktime_tz
# Non-standard
# ------------
#
# See http://flask.pocoo.org/docs/0.10/
# On Debian, Ubuntu, etc.:
# - old version: sudo apt-get install python3-flask
# - latest version: sudo -H pip3 install flask
from flask import Flask, request, url_for, render_template, flash, redirect,\
abort, jsonify, g, session
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from werkzeug.datastructures import MultiDict
# See https://flask-login.readthedocs.io/
# Install from PyPi: sudo -H pip3 install flask-login
from flask_login import LoginManager, UserMixin, login_user, logout_user,\
current_user, login_required
# See https://rauth.readthedocs.io/
# Install form PyPi: sudo -H pip3 install rauth
from rauth import OAuth1Service, OAuth2Service
import requests
# See https://developers.google.com/api-client-library/python/guide/aaa_oauth
# Install form PyPi: sudo -H pip3 install oauth2client
from oauth2client import client, crypt
# See https://pythonhosted.org/Flask-OpenID/
# Install from PyPi: sudo -H pip3 install Flask-OpenID
from flask_openid import OpenID
# See https://flask-httpauth.readthedocs.io/
# Install from PyPi: sudo -H pip3 install flask-httpauth
from flask_httpauth import HTTPBasicAuth
# See https://passlib.readthedocs.io/
# Install from PyPi: sudo -H pip3 install passlib
from passlib.apps import custom_app_context as pwd_context
# See https://flask-wtf.readthedocs.io/ and https://wtforms.readthedocs.io/
# Install from PyPi: sudo -H pip3 install Flask-WTF
from flask_wtf import FlaskForm
from wtforms import validators, widgets, Form, FormField, FieldList,\
StringField, TextAreaField, SelectField, SelectMultipleField, HiddenField,\
ValidationError
from wtforms.compat import string_types
# See http://tinydb.readthedocs.io/
# Install from PyPi: sudo -H pip3 install tinydb
from tinydb import TinyDB, Query, where
from tinydb.database import Document
from tinydb.operations import delete
from tinydb.storages import Storage, touch
# See https://github.com/eugene-eeo/tinyrecord
# Install from PyPi: sudo -H pip3 install tinyrecord
from tinyrecord import transaction
# See http://rdflib.readthedocs.io/
# On Debian, Ubuntu, etc.:
# - old version: sudo apt-get install python3-rdflib
# - latest version: sudo -H pip3 install rdflib
import rdflib
from rdflib import Literal, Namespace
from rdflib.namespace import SKOS, RDF
# See https://www.dulwich.io/
# On Debian, Ubuntu, etc.:
# - old version: sudo apt-get install python3-dulwich
# - latest version: sudo -H pip3 install dulwich
from dulwich.repo import Repo
from dulwich.errors import NotGitRepository
import dulwich.porcelain as git
# See https://github.com/bloomberg/python-github-webhook
# Installed locally
from github_webhook import Webhook
# See http://flask-cors.readthedocs.io/
# Install from PyPi: sudo -H pip3 install flask-cors
# need to allow CORS for requests from js
from flask_cors import CORS, cross_origin
# Customization
# =============
mscwg_email = 'mscwg@rda-groups.org'
# Replacement for JSONStorage
class JSONStorageWithGit(Storage):
"""Store the data in a JSON file and log the change in a Git repo.
"""
def __init__(self, path, create_dirs=False, encoding='utf8', **kwargs):
"""Create a new instance.
Also creates the storage file, if it doesn't exist.
Arguments:
path (str): Path/filename of the JSON data.
"""
super(JSONStorageWithGit, self).__init__()
# Create file if not exists
touch(path, create_dirs=create_dirs)
self.kwargs = kwargs
self._handle = open(path, 'r+', encoding=encoding)
# Ensure Git is configured properly
git_repo = os.path.dirname(path)
try:
self.repo = Repo(git_repo)
except NotGitRepository:
self.repo = Repo.init(git_repo)
self.filename = path
basename = os.path.basename(path)
self.name = os.path.splitext(basename)[0]
@property
def _refname(self):
return b'refs/heads/master'
def close(self):
self._handle.close()
def read(self):
# Get the file size
self._handle.seek(0, os.SEEK_END)
size = self._handle.tell()
if not size:
# File is empty
return None
else:
self._handle.seek(0)
return json.load(self._handle)
def write(self, data):
# Write the json file
self._handle.seek(0)
serialized = json.dumps(data, **self.kwargs)
self._handle.write(serialized)
self._handle.flush()
os.fsync(self._handle.fileno())
self._handle.truncate()
# Add file to Git staging area
added, ignored = git.add(repo=self.repo, paths=[self.filename])
# Avoid empty commits
if not added:
print("WARNING: Failed to stage changes to {}."
.format(self.filename))
if ignored:
print("DEBUG: Operation blocked by gitignore pattern.")
return
changes = 0
for groupname, group in git.status(repo=self.repo)[0].items():
changes += len(group)
if not changes:
return
# Prepare commit information
committer = 'MSCWG <{}>'.format(mscwg_email).encode('utf8')
user = None
if g:
# This will either catch an API user or return None
user = g.get('user', None)
if current_user and current_user.is_authenticated:
# If human user is logged in, use their record instead
user = current_user
if user:
author = ('{} <{}>'.format(
user['name'], user['email']).encode('utf8'))
message = ('Update to {} from {}\n\nUser ID:\n{}'.format(
self.name, user['name'], user['userid'])
.encode('utf8'))
else:
author = committer
message = ('Update to {}'.format(self.name).encode('utf8'))
# Execute commit
git.commit(self.repo, message=message, author=author,
committer=committer)
class User(Document):
'''This provides implementations for the methods that Flask-Login
expects user objects to have.
'''
__hash__ = Document.__hash__
@property
def is_active(self):
if self.get('blocked'):
return False
return True
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
return str(self.doc_id)
def __eq__(self, other):
'''
Checks the equality of two `UserMixin` objects using `get_id`.
'''
if isinstance(other, User):
return self.get_id() == other.get_id()
return NotImplemented
def __ne__(self, other):
'''
Checks the inequality of two `UserMixin` objects using `get_id`.
'''
equal = self.__eq__(other)
if equal is NotImplemented:
return NotImplemented
return not equal
class ApiUser(Document):
'''For objects representing an application using the API. Source:
https://blog.miguelgrinberg.com/post/restful-authentication-with-flask
'''
@property
def is_active(self):
if self.get('blocked'):
return False
return True
@property
def is_authenticated(self):
return True
@property
def is_anonymous(self):
return False
def get_id(self):
return str(self.doc_id)
def __eq__(self, other):
'''
Checks the equality of two `UserMixin` objects using `get_id`.
'''
if isinstance(other, User):
return self.get_id() == other.get_id()
return NotImplemented
def __ne__(self, other):
'''
Checks the inequality of two `UserMixin` objects using `get_id`.
'''
equal = self.__eq__(other)
if equal is NotImplemented:
return NotImplemented
return not equal
def hash_password(self, password):
self['password_hash'] = pwd_context.encrypt(password)
user_db.table('api_users').update(
{'password_hash': self.get('password_hash')},
doc_ids=[self.doc_id])
return True
def verify_password(self, password):
result, new_hash = pwd_context.verify_and_update(
password, self.get('password_hash'))
if new_hash:
self['password_hash'] = new_hash
user_db.table('api_users').update(
{'password_hash': self.get('password_hash')},
doc_ids=[self.doc_id])
return result
def generate_auth_token(self, expiration=600):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': self.doc_id})
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
api_users = user_db.table('api_users')
user_record = api_users.get(doc_id=int(data['id']))
if not user_record:
return None
user = ApiUser(value=user_record, doc_id=user_record.doc_id)
return user
class OAuthSignIn(object):
'''Abstraction layer for RAuth. Source:
https://blog.miguelgrinberg.com/post/oauth-authentication-with-flask
'''
providers = None
def __init__(self, provider_name):
self.provider_name = provider_name
if 'OAUTH_CREDENTIALS' not in app.config:
print('WARNING: OAuth authentication will not work without secret'
' application keys. Please run your tests with a different'
' authentication method.')
self.consumer_id = None
self.consumer_secret = None
elif provider_name not in app.config['OAUTH_CREDENTIALS']:
self.consumer_id = None
self.consumer_secret = None
else:
credentials = app.config['OAUTH_CREDENTIALS'][provider_name]
self.consumer_id = credentials['id']
self.consumer_secret = credentials['secret']
def authorize(self):
pass
def callback(self):
pass
def get_callback_url(self):
return url_for('oauth_callback', provider=self.provider_name,
_external=True)
@classmethod
def get_provider(self, provider_name):
if self.providers is None:
self.providers = {}
for provider_class in self.__subclasses__():
provider = provider_class()
self.providers[provider.provider_name] = provider
return self.providers[provider_name]
class GoogleSignIn(OAuthSignIn):
def __init__(self):
super(GoogleSignIn, self).__init__('google')
self.formatted_name = 'Google'
discovery = oauth_db.get(Query().provider == self.provider_name)
discovery_url = ('https://accounts.google.com/.well-known/'
'openid-configuration')
if not discovery:
try:
r = requests.get(discovery_url)
discovery = r.json()
discovery['provider'] = self.provider_name
expiry_timestamp = mktime_tz(
parsedate_tz(r.headers['expires']))
discovery['timestamp'] = expiry_timestamp
oauth_db.insert(discovery)
except Exception as e:
print('WARNING: could not retrieve URLs for {}.'
.format(self.provider_name))
print(e)
discovery = dict()
elif (datetime.now(timezone.utc).timestamp() > discovery['timestamp']):
try:
last_expiry_date = datetime.fromtimestamp(
discovery['timestamp'], timezone.utc)
headers = {
'If-Modified-Since': last_expiry_date
.strftime('%a, %d %b %Y %H:%M:%S %Z')}
r = requests.get(discovery_url, headers=headers)
if r.status_code != requests.codes.not_modified:
discovery.update(r.json())
expiry_timestamp = mktime_tz(
parsedate_tz(r.headers['expires']))
discovery['timestamp'] = expiry_timestamp
oauth_db.update(discovery, doc_ids=[discovery.doc_id])
except Exception as e:
print('WARNING: could not update URLs for {}.'
.format(self.provider_name))
print(e)
self.service = OAuth2Service(
name=self.provider_name,
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url=discovery.get(
'authorization_endpoint',
'https://accounts.google.com/o/oauth2/v2/auth'),
access_token_url=discovery.get(
'token_endpoint',
'https://www.googleapis.com/oauth2/v4/token'),
base_url=discovery.get(
'issuer',
'https://accounts.google.com'))
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='profile email',
response_type='code',
redirect_uri=self.get_callback_url()))
def callback(self):
if 'code' not in request.args:
return (None, None, None)
r = self.service.get_raw_access_token(
method='POST',
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()})
oauth_info = r.json()
access_token = oauth_info['access_token']
id_token = oauth_info['id_token']
oauth_session = self.service.get_session(access_token)
try:
idinfo = client.verify_id_token(id_token, self.consumer_id)
if idinfo['iss'] not in ['accounts.google.com',
'https://accounts.google.com']:
raise crypt.AppIdentityError("Wrong issuer.")
except crypt.AppIdentityError as e:
print(e)
return (None, None, None)
return (
self.provider_name + '$' + idinfo['sub'],
idinfo.get('name'),
idinfo.get('email'))
class LinkedinSignIn(OAuthSignIn):
def __init__(self):
super(LinkedinSignIn, self).__init__('linkedin')
self.formatted_name = 'LinkedIn'
self.service = OAuth2Service(
name=self.provider_name,
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url='https://www.linkedin.com/oauth/v2/authorization',
access_token_url='https://www.linkedin.com/oauth/v2/accessToken',
base_url='https://api.linkedin.com/v1/people/')
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='r_basicprofile r_emailaddress',
response_type='code',
redirect_uri=self.get_callback_url()))
def callback(self):
if 'code' not in request.args:
return (None, None, None)
r = self.service.get_raw_access_token(
method='POST',
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()})
oauth_info = r.json()
access_token = oauth_info['access_token']
oauth_session = self.service.get_session(access_token)
idinfo = oauth_session.get(
'~:(id,formatted-name,email-address)?format=json').json()
return (
self.provider_name + '$' + idinfo['id'],
idinfo.get('formattedName'),
idinfo.get('emailAddress'))
class TwitterSignIn(OAuthSignIn):
def __init__(self):
super(TwitterSignIn, self).__init__('twitter')
self.formatted_name = 'Twitter'
self.service = OAuth1Service(
name=self.provider_name,
consumer_key=self.consumer_id,
consumer_secret=self.consumer_secret,
request_token_url='https://api.twitter.com/oauth/request_token',
authorize_url='https://api.twitter.com/oauth/authorize',
access_token_url='https://api.twitter.com/oauth/access_token',
base_url='https://api.twitter.com/1.1/')
def authorize(self):
request_token = self.service.get_request_token(
params={'oauth_callback': self.get_callback_url()})
session['request_token'] = request_token
return redirect(self.service.get_authorize_url(request_token[0]))
def callback(self):
request_token = session.pop('request_token')
if 'oauth_verifier' not in request.args:
return (None, None, None)
oauth_session = self.service.get_auth_session(
request_token[0],
request_token[1],
data={'oauth_verifier': request.args['oauth_verifier']}
)
idinfo = oauth_session.get('account/verify_credentials.json').json()
return (
self.provider_name + '$' + str(idinfo.get('id')),
idinfo.get('name'),
# Need to write policy pages before retrieving email addresses
None)
class GithubSignIn(OAuthSignIn):
def __init__(self):
super(GithubSignIn, self).__init__('github')
self.formatted_name = 'GitHub'
self.service = OAuth2Service(
name=self.provider_name,
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url='https://github.com/login/oauth/authorize',
access_token_url='https://github.com/login/oauth/access_token',
base_url='https://api.github.com/')
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='read:user user:email',
redirect_uri=self.get_callback_url()))
def callback(self):
if 'code' not in request.args:
return (None, None, None)
access_token = self.service.get_access_token(
method='POST',
data={'code': request.args['code'],
'redirect_uri': self.get_callback_url()})
oauth_session = self.service.get_session(access_token)
idinfo = oauth_session.get('user').json()
if not idinfo.get('email'):
email_address = ''
emailinfo = oauth_session.get('user/emails').json()
for email_object in emailinfo:
email_address = email_object.get('email')
if email_object.get('primary', False):
break
if email_address:
idinfo['email'] = email_address
return (
self.provider_name + '$' + idinfo['login'],
idinfo.get('name'),
idinfo.get('email'))
class GitlabSignIn(OAuthSignIn):
def __init__(self):
super(GitlabSignIn, self).__init__('gitlab')
self.formatted_name = 'GitLab'
discovery = oauth_db.get(Query().provider == self.provider_name)
discovery_url = ('https://gitlab.com/.well-known/'
'openid-configuration')
if not discovery:
try:
r = requests.get(discovery_url)
discovery = r.json()
discovery['provider'] = self.provider_name
expiry_timestamp = mktime_tz(
parsedate_tz(r.headers['date'])) + 3600
discovery['timestamp'] = expiry_timestamp
oauth_db.insert(discovery)
except Exception as e:
print('WARNING: could not retrieve URLs for {}.'
.format(self.provider_name))
print(e)
discovery = dict()
elif (datetime.now(timezone.utc).timestamp() > discovery['timestamp']):
try:
last_expiry_date = datetime.fromtimestamp(
discovery['timestamp'], timezone.utc)
headers = {
'If-Modified-Since': last_expiry_date
.strftime('%a, %d %b %Y %H:%M:%S %Z')}
r = requests.get(discovery_url, headers=headers)
if r.status_code != requests.codes.not_modified:
discovery.update(r.json())
expiry_timestamp = mktime_tz(
parsedate_tz(r.headers['date'])) + 3600
discovery['timestamp'] = expiry_timestamp
oauth_db.update(discovery, doc_ids=[discovery.doc_id])
except Exception as e:
print('WARNING: could not update URLs for {}.'
.format(self.provider_name))
print(e)
self.userinfo = discovery.get(
'userinfo_endpoint',
'https://gitlab.com/oauth/userinfo')
self.service = OAuth2Service(
name=self.provider_name,
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url=discovery.get(
'authorization_endpoint',
'https://gitlab.com/oauth/authorize'),
access_token_url=discovery.get(
'token_endpoint',
'https://gitlab.com/oauth/token'),
base_url=discovery.get(
'issuer',
'https://gitlab.com'))
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='openid email',
response_type='code',
redirect_uri=self.get_callback_url()))
def callback(self):
if 'code' not in request.args:
return (None, None, None)
r = self.service.get_raw_access_token(
method='POST',
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()})
oauth_info = r.json()
access_token = oauth_info['access_token']
id_token = oauth_info['id_token']
oauth_session = self.service.get_session(access_token)
idinfo = oauth_session.get(self.userinfo).json()
return (
self.provider_name + '$' + idinfo['sub'],
idinfo.get('name'),
idinfo.get('email'))
class OrcidSignIn(OAuthSignIn):
def __init__(self):
super(OrcidSignIn, self).__init__('orcid')
self.formatted_name = 'ORCID'
self.service = OAuth2Service(
name=self.provider_name,
client_id=self.consumer_id,
client_secret=self.consumer_secret,
authorize_url='https://orcid.org/oauth/authorize',
access_token_url='https://orcid.org/oauth/token',
base_url='https://pub.orcid.org/v2.0/')
def authorize(self):
return redirect(self.service.get_authorize_url(
scope='/authenticate',
response_type='code',
redirect_uri=self.get_callback_url()))
def callback(self):
if 'code' not in request.args:
return (None, None, None)
r = self.service.get_raw_access_token(
method='POST',
data={'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': self.get_callback_url()})
oauth_info = r.json()
access_token = oauth_info['access_token']
orcid = oauth_info['orcid']
oauth_session = self.service.get_session(access_token)
idinfo = oauth_session.get(
'{}/record'.format(orcid),
headers={'Content-type': 'application/vnd.orcid+json'}).json()
email = None
emails = idinfo.get('person', dict()).get('emails', dict()).get(
'email', list())
for email_obj in emails:
this_email = email_obj.get('email')
if this_email and email_obj.get('primary'):
email = this_email
break
elif email:
continue
email = this_email
return (
self.provider_name + '$' + orcid,
oauth_info.get('name'),
email)
# Basic setup
# ===========
script_dir = os.path.dirname(__file__)
app = Flask(__name__, instance_relative_config=True)
# Data storage path defaults:
app.config['MAIN_DATABASE_PATH'] = os.path.join(
app.instance_path, 'data', 'db.json')
app.config['USER_DATABASE_PATH'] = os.path.join(
app.instance_path, 'data', 'users.json')
app.config['OAUTH_DATABASE_PATH'] = os.path.join(
app.instance_path, 'oauth-urls.json')
app.config['OPENID_PATH'] = os.path.join(app.instance_path, 'open-id')
# Variable config options go here:
app.config.from_object('config.for.Production')
# Secret application keys go here:
app.config.from_pyfile('keys.cfg', silent=True)
# Any of these settings may be overridden in a .cfg file specified by the
# following environment variable:
app.config.from_envvar('MSC_SETTINGS', silent=True)
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True
for path in [os.path.dirname(app.config['MAIN_DATABASE_PATH']),
os.path.dirname(app.config['USER_DATABASE_PATH']),
app.config['OPENID_PATH']]:
if not os.path.isdir(path):
print('INFO: creating empty data directory at {}'.format(path))
os.makedirs(path)
lm = LoginManager(app)
lm.login_view = 'login'
lm.login_message = 'Please sign in to access this page.'
lm.login_message_category = "error"
db = TinyDB(
app.config['MAIN_DATABASE_PATH'], storage=JSONStorageWithGit,
indent=2, ensure_ascii=False)
user_db = TinyDB(
app.config['USER_DATABASE_PATH'], storage=JSONStorageWithGit,
indent=2, ensure_ascii=False)
oauth_db = TinyDB(app.config['OAUTH_DATABASE_PATH'])
thesaurus = rdflib.Graph()
thesaurus.parse(os.path.join(script_dir, 'simple-unesco-thesaurus.ttl'),
format='turtle')
UNO = Namespace('http://vocabularies.unesco.org/ontology#')
thesaurus_link = ('<a href="http://vocabularies.unesco.org/browser/thesaurus/'
'en/">UNESCO Thesaurus</a>')
oid = OpenID(app, app.config['OPENID_PATH'])
auth = HTTPBasicAuth()
webhook = Webhook(app, secret=app.config['WEBHOOK_SECRET'])
# Data model
# ----------
table_names = {
'm': 'metadata-schemes',
'g': 'organizations',
't': 'tools',
'c': 'mappings',
'e': 'endorsements'}
tables = dict()
for key, value in table_names.items():
tables[key] = db.table(value)
templates = {
'm': 'metadata-scheme.html',
'g': 'organization.html',
't': 'tool.html',
'c': 'mapping.html',
'e': 'endorsement.html'}
relations_msc_form = {
'parent scheme': 'parent_schemes',
'maintainer': 'maintainers',
'funder': 'funders',
'user': 'users',
'supported scheme': 'supported_schemes',
'input scheme': 'input_schemes',
'output scheme': 'output_schemes',
'endorsed scheme': 'endorsed_schemes',
'originator': 'originators'}
relations_form_msc = {v: k for k, v in relations_msc_form.items()}
relations_inverse = {
'parent scheme': 'child_schemes',
'supported scheme': 'tools',
'input scheme': 'mappings_from',
'output scheme': 'mappings_to',
'endorsed scheme': 'endorsements'}
useful_fields = dict()
useful_fields['m'] = ['title', 'identifiers', 'description', 'keywords',
'locations']
useful_fields['g'] = ['name', 'identifiers']
useful_fields['t'] = ['title', 'identifiers', 'description', 'locations']
useful_fields['c'] = ['identifiers', 'locations', 'input_schemes',
'output_schemes']
useful_fields['e'] = ['identifiers', 'locations', 'endorsed_schemes']
computing_platforms = ['Windows', 'Mac OS X', 'Linux', 'BSD', 'cross-platform']
# Top 10 languages according to http://www.langpop.com/ in 2013.
# Though not really belonging here, 'XML' added for XSL tranformations.
programming_languages = [
'C', 'Java', 'PHP', 'JavaScript', 'C++', 'Python', 'Shell', 'Ruby',
'Objective-C', 'C#', 'XML']
programming_languages.sort()
id_scheme_list = ['DOI']
scheme_locations = [
('', ''), ('document', 'document'), ('website', 'website'),
('RDA-MIG', 'RDA MIG Schema'), ('DTD', 'XML/SGML DTD'),
('XSD', 'XML Schema'), ('RDFS', 'RDF Schema')]
organization_locations = [
('', ''), ('website', 'website'), ('email', 'email address')]
organization_types = [
('standards body', 'standards body'), ('archive', 'archive'),
('professional group', 'professional group'),
('coordination group', 'coordination group')]
tool_locations = [
('', ''), ('document', 'document'), ('website', 'website'),
('application', 'application'),
('service', 'service endpoint')]
tool_type_regexp = (
r'(terminal \([^)]+\)|graphical \([^)]+\)|web service|web application|^$)')
tool_type_help = (
'Must be one of "terminal (<platform>)", "graphical (<platform>)",'
' "web service", "web application".')
tool_type_list = ['web application', 'web service']
for platform in computing_platforms:
tool_type_list.append('terminal ({})'.format(platform))
tool_type_list.append('graphical ({})'.format(platform))
mapping_location_regexp = (
r'(document|library \([^)]+\)|executable \([^)]+\)|^$)')
mapping_location_help = (html.escape(
'Must be one of "document", "library (<language>)",'
' "executable (<platform>)".'))
mapping_location_list = ['document']
for language in programming_languages:
mapping_location_list.append('library ({})'.format(language))
for platform in computing_platforms:
mapping_location_list.append('executable ({})'.format(platform))
endorsement_locations = [('', ''), ('document', 'document')]
# Utility functions
# =================
def get_subject_terms(complete=False):
"""Returns a list of subject terms. By default, only returns terms that
would yield results in a search for metadata schemes. Pass `complete=True`
to get a full list of all allowed subject terms.
"""
keyword_uris = set()
if complete:
for generator in [
thesaurus.subjects(RDF.type, UNO.Domain),
thesaurus.subjects(RDF.type, UNO.MicroThesaurus),
thesaurus.subjects(RDF.type, SKOS.Concept)]:
for uri in generator:
keyword_uris.add(uri)
else:
keyword_uris |= get_used_term_uris()
subject_set = set()
for uri in keyword_uris:
subject_set.add(str(thesaurus.preferredLabel(uri, lang='en')[0][1]))
subject_set.add('Multidisciplinary')
subject_list = list(subject_set)
subject_list.sort()
return subject_list
def request_wants_json():
"""Returns True if request is for JSON instead of HTML, False otherwise.
From http://flask.pocoo.org/snippets/45/
"""
best = request.accept_mimetypes \
.best_match(['application/json', 'text/html'])
return best == 'application/json' and \
request.accept_mimetypes[best] > request.accept_mimetypes['text/html']
def get_term_list(uri, broader=True, narrower=True):
"""Recursively finds broader or narrower (or both) terms in the thesaurus.
Arguments:
uri (str): URI of term in thesaurus
broader (Boolean): Whether to search for broader terms
(default: True)
narrower (Boolean): Whether to search for narrower terms
(default: True)
Returns:
list: Given URI plus those of broader/narrower terms
"""
terms = list()
terms.append(uri)
if broader:
broader_terms = thesaurus.objects(uri, SKOS.broader)
for broader_term in broader_terms:
if broader_term not in terms:
terms = get_term_list(broader_term, narrower=False) + terms
if narrower:
narrower_terms = thesaurus.objects(uri, SKOS.narrower)
for narrower_term in narrower_terms:
if narrower_term not in terms:
terms += get_term_list(narrower_term, broader=False)
return terms
def get_term_uri(term):
"""Translates a string into the URI of the broadest term in the thesaurus
that has that string as its preferred label in English.
Arguments:
term (str): string to look up
Returns:
str: URI of a thesaurus term, if one is found
None: if no matching term is found
"""
concept_id = None
concept_ids = thesaurus.subjects(SKOS.prefLabel, Literal(term, lang="en"))
priority = 0
for uri in concept_ids:
concept_type = thesaurus.value(subject=uri, predicate=RDF.type)
if concept_type == UNO.Domain and priority < 3:
concept_id = uri
priority = 3
elif concept_type == UNO.MicroThesaurus and priority < 2:
concept_id = uri
priority = 2
elif priority < 1:
concept_id = uri
priority = 1
return concept_id
def get_term_tree(uris, filter=list()):
"""Takes a list of URIs of terms in the thesaurus and recursively builds
a list of dictionaries, each of which providing the preferred label of
the term in English, its corresponding URL in the Catalog, and (if
applicable) a list of dictionaries corresponding to immediately narrower
terms in the thesaurus.
The list of narrower terms can optionally be filtered with a whitelist.
Arguments:
uris (list of str): List of URIs of terms in thesaurus
filter (list): URIs of terms that can be listed as narrower than the
given one
Returns:
list: Dictionaries of two or three items: 'name' (the preferred label
of the term in English), 'url' (the URL of the corresponding
Catalog page), 'children' (list of dictionaries, only present if
narrower terms exist)
"""
tree = list()
for uri in uris:
result = dict()
term = str(thesaurus.preferredLabel(uri, lang='en')[0][1])
result['name'] = term
slug = to_url_slug(term)
result['url'] = url_for('subject', subject=slug)
narrower_ids = thesaurus.objects(uri, SKOS.narrower)
children = list()
if filter:
children = [id for id in narrower_ids if id in filter]
else:
children = narrower_ids
if children:
result['children'] = get_term_tree(children, filter=filter)
tree.append(result)
tree.sort(key=lambda k: k['name'])
return tree
def get_used_term_uris():
"""Returns a deduplicated list of URIs corresponding to the subject keywords
in use in the database, plus the URIs of all their broader terms. Note that
this does not look for version-specific keywords.
"""
# Get a list of all the keywords used in the database
Scheme = Query()
classified_schemes = tables['m'].search(Scheme.keywords.exists())
keyword_set = set()
for classified_scheme in classified_schemes:
for keyword in classified_scheme['keywords']:
keyword_set.add(keyword)
# Transform to URIs
keyword_uris = set()
for keyword in keyword_set:
uri = get_term_uri(keyword)