forked from ourresearch/jump-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
1807 lines (1400 loc) · 68.5 KB
/
views.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
# coding: utf-8
from flask import request
from flask import redirect
from flask import abort
from flask import render_template
from flask import jsonify
from flask import url_for
from flask import Response
from flask import send_file
from flask import g
from flask_jwt_extended import jwt_required, create_access_token, get_jwt_identity
from pyinstrument import Profiler
from sqlalchemy import func as sql_func
from werkzeug.security import safe_str_cmp
from werkzeug.security import generate_password_hash, check_password_hash
from psycopg2 import sql
from psycopg2.extras import execute_values
import os
import sys
import simplejson as json
from collections import defaultdict
from time import sleep
from time import time
import csv
import shortuuid
import datetime
import tempfile
import random
from collections import OrderedDict
from app import app
from app import logger
from app import jwt
from app import db
from app import get_db_cursor
# import ror_search
import password_reset
import prepared_demo_publisher
from emailer import create_email, send
from counter import Counter, CounterInput
from grid_id import GridId
from institution import Institution
from journal_price import JournalPrice, JournalPriceInput
from filter_titles import FilterTitles, FilterTitlesInput
from package import Package
from permission import Permission, UserInstitutionPermission
from perpetual_access import PerpetualAccess, PerpetualAccessInput
from ror_id import RorId, RorGridCrosswalk
from saved_scenario import SavedScenario
from saved_scenario import get_latest_scenario
from saved_scenario import save_raw_scenario_to_db
from saved_scenario import save_raw_member_institutions_included_to_db
from saved_scenario import save_feedback_on_member_institutions_included_to_db
from saved_scenario import get_latest_scenario_raw
from scenario import get_common_package_data
from scenario import get_clean_package_id
from consortium import get_consortium_ids
from consortium import Consortium
from user import User, default_password
from util import jsonify_fast
from util import jsonify_fast_no_sort
from util import str2bool
from util import elapsed
from util import abort_json
from util import safe_commit
from util import TimingMessages
from util import get_ip
from util import response_json
from util import get_sql_answer
from app import logger
from app import DEMO_PACKAGE_ID
from app import s3_client
def s3_cache_get(url):
print("in cache_get with", url)
filename = "{}.json".format(url.replace("/", "~"))
s3_clientobj = s3_client.get_object(Bucket="unsub-cache", Key=filename)
contents_string = s3_clientobj["Body"].read().decode("utf-8")
contents_json = json.loads(contents_string)
return contents_json
def authenticate_for_package(publisher_id, required_permission):
package = Package.query.get(publisher_id)
if not package:
abort_json(404, "Publisher not found")
if not is_authorized_superuser():
auth_user = authenticated_user()
if not auth_user:
abort_json(401, "Must be logged in.")
if not package.institution:
abort_json(400, "Publisher is not owned by any institution.")
if not auth_user.has_permission(package.institution.id, required_permission):
consortium_package = None
if package.consortium_package_id:
consortium_package = Package.query.get(package.consortium_package_id)
if not consortium_package:
abort_json(403, "Missing required permission '{}' for institution {}.".format(
required_permission.name,
package.institution.id)
)
if not auth_user.has_permission(consortium_package.institution.id, required_permission):
abort_json(403, "Missing required permission '{}' for institution {}.".format(
required_permission.name,
consortium_package.institution.id)
)
return package
def authenticated_user():
jwt_identity = get_jwt_identity()
user_id = jwt_identity.get("user_id", None) if jwt_identity else None
return User.query.get(user_id) if user_id else None
def lookup_user(user_id=None, email=None, username=None):
id_user = User.query.filter(User.id == user_id).scalar() if user_id is not None else None
email_user = User.query.filter(sql_func.lower(User.email) == email.lower()).scalar() if email is not None else None
username_user = User.query.filter(User.username == username).scalar() if username is not None else None
user_ids = set([user.id for user in [id_user, email_user, username_user] if user])
if len(user_ids) > 1:
return abort_json(400, "Email, username, and user id are in use by different users.")
return id_user or email_user or username_user
@app.before_request
def before_request_stuff():
if app.config["PROFILE_REQUESTS"]:
g.profiler = Profiler()
g.profiler.start()
@app.after_request
def after_request_stuff(resp):
sys.stdout.flush() # without this jason's heroku local buffers forever
#support CORS
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE, PATCH"
resp.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control"
resp.headers["Access-Control-Expose-Headers"] = "Authorization, Cache-Control"
resp.headers["Access-Control-Allow-Credentials"] = "true"
# make not cacheable because the GETs change after parameter change posts!
resp.cache_control.max_age = 0
resp.cache_control.no_cache = True
if app.config["PROFILE_REQUESTS"]:
g.profiler.stop()
print((g.profiler.output_text(str=True, color=True, show_all=True)))
return resp
class TimeoutError(Exception):
pass
@app.errorhandler(500)
def error_500(e):
response = jsonify({"message": "Internal Server Error"})
response.status_code = 500
return response
@app.errorhandler(TimeoutError)
def error_timeout(e):
response = jsonify({"message": "Timeout"})
response.status_code = 500
return response
@app.route("/", methods=["GET", "POST"])
def base_endpoint():
return jsonify_fast({
"version": "0.0.1",
"msg": "Don't panic"
})
# @app.route("/favicon.ico")
# def favicon():
# return redirect(url_for("static", filename="img/favicon.ico", _external=True, _scheme="https"))
@app.route("/scenario/<scenario_id>/journal/<issn_l>", methods=["GET"])
@jwt_required()
def jump_scenario_issn_get(scenario_id, issn_l):
my_saved_scenario = get_saved_scenario(scenario_id, required_permission=Permission.view())
scenario = my_saved_scenario.live_scenario
consortium_ids = get_consortium_ids()
if scenario_id in [d["scenario_id"] for d in consortium_ids]:
my_consortium = Consortium(scenario_id)
response = {"journal": {"member_institutions": my_consortium.to_dict_journal_zoom(issn_l)}}
else:
my_journal = scenario.get_journal(issn_l)
if not my_journal:
abort_json(404, f"Journal with ISSN-L {issn_l} not found in scenario")
response = {"_settings": scenario.settings.to_dict(), "journal": my_journal.to_dict_details()}
response = jsonify_fast_no_sort(response)
return response
@app.route("/live/data/common/<package_id>", methods=["GET"])
def jump_data_package_id_get(package_id):
if not is_authorized_superuser():
abort_json(500, "Secret doesn't match, not getting package")
if package_id.startswith("demo"):
package_id = DEMO_PACKAGE_ID
response = get_common_package_data(package_id)
response = jsonify_fast_no_sort(response)
return response
@app.route("/login", methods=["GET", "POST"])
def login():
return user_login()
def make_identity_dict(user):
# Identity can be any data that is json serializable. Include timestamp so is unique for each demo start.
return {
"user_id": user.id,
"login_uuid": shortuuid.uuid()[0:10],
"created": datetime.datetime.utcnow().isoformat(),
"is_demo_user": user.is_demo_user
}
# copies the existing /login route but uses the new jump_user table
@app.route("/user/login", methods=["POST"])
def user_login():
print("in user_login")
request_args = request.args
if request.is_json:
request_args = request.json
username = request_args.get("username", None)
email = request_args.get("email", None)
password = request_args.get("password", "")
if username is None and email is None:
return abort_json(400, "Username or email parameter is required.")
login_user = lookup_user(email=email, username=username)
# maybe the username was passed as an email
if not login_user and email and not username:
login_user = lookup_user(username=email)
if not login_user:
return abort_json(404, "User does not exist.")
if not check_password_hash(login_user.password_hash, password) and os.getenv("JWT_SECRET_KEY") != password:
return abort_json(403, "Bad password.")
identity_dict = make_identity_dict(login_user)
logger.info("login to account {} with {}".format(login_user.username, identity_dict))
access_token = create_access_token(identity=identity_dict)
login_user_permissions = db.session.query(UserInstitutionPermission).filter(
UserInstitutionPermission.user_id == login_user.id,
).first()
if not login_user_permissions:
assign_demo_institution(login_user)
safe_commit(db)
return jsonify({"access_token": access_token})
@app.route("/user/demo", methods=["POST"])
def register_demo_user():
request_args = request.args
if request.is_json:
request_args = request.json
email = request_args.get("email", None)
username = request_args.get("username", None)
display_name = request_args.get("name", "Anonymous User")
password = request_args.get("password", default_password())
if not email:
return abort_json(400, "Email parameter is required.")
existing_user = lookup_user(email=email, username=username)
if existing_user:
if check_password_hash(existing_user.password_hash, password):
return user_login()
else:
if lookup_user(email=email):
return abort_json(409, "A user with email {} already exists.".format(email))
else:
return abort_json(409, "A user with username {} already exists.".format(username))
demo_user = User()
demo_user.username = username
demo_user.email = email
demo_user.password_hash = generate_password_hash(password)
demo_user.display_name = display_name
demo_user.is_demo_user = True
db.session.add(demo_user)
if "@" in email and email.split("@")[-2].lower().endswith("+nocache"):
use_prepared_publisher = False
else:
use_prepared_publisher = True
assign_demo_institution(demo_user, use_prepared_publisher=use_prepared_publisher)
if safe_commit(db):
welcome_email = create_email(email, "Welcome to Unsub", "demo_user", {})
send(welcome_email, for_real=True)
identity_dict = make_identity_dict(demo_user)
logger.info("login to account {} with {}".format(demo_user.username, identity_dict))
access_token = create_access_token(identity=identity_dict)
return jsonify({"access_token": access_token})
else:
return abort_json(500, "Database error.")
def assign_demo_institution(user, use_prepared_publisher=True):
demo_institution = Institution()
demo_institution.display_name = "Demo University"
demo_institution.is_demo_institution = True
db.session.add(demo_institution)
db.session.add(GridId(institution_id=demo_institution.id, grid_id="grid.433631.0"))
db.session.add(RorId(institution_id=demo_institution.id, ror_id="00xbe3815"))
for permission in [Permission.view(), Permission.modify(), Permission.admin()]:
user_perm = UserInstitutionPermission()
user_perm.permission_id = permission.id,
user_perm.user_id = user.id,
user_perm.institution_id = demo_institution.id
db.session.add(user_perm)
demo_publisher = prepared_demo_publisher.get_demo_publisher(demo_institution, use_prepared=use_prepared_publisher)
db.session.add(demo_publisher)
def notify_changed_permissions(user, admin, old_permissions, new_permissions):
if old_permissions != new_permissions and user.id != admin.id and user.email:
diff_lines = []
for institution_id in set(list(old_permissions.keys()) + list(new_permissions.keys())):
old_names = set(old_permissions.get(institution_id, {}).get("permissions", []))
new_names = set(new_permissions.get(institution_id, {}).get("permissions", []))
if old_names != new_names:
institution_name = old_permissions.get(institution_id, new_permissions.get(institution_id))[
"institution_name"]
diff_lines.append("{} ({}):".format(institution_name, institution_id))
diff_lines.append("old: {}".format(",".join(old_names) if old_names else "[None]"))
diff_lines.append("new: {}".format(",".join(new_names) if new_names else "[None]"))
diff_lines.append("")
email = create_email(user.email, "Your Unsub permissions were changed.", "changed_permissions",
{"data": {
"display_name": user.display_name,
"admin_name": admin.display_name,
"admin_email": admin.email,
"diff": "\n".join(diff_lines)
}})
send(email, for_real=True)
@app.route("/user/new", methods=["POST"])
@jwt_required()
def register_new_user():
if not request.is_json:
return abort_json(400, "This post requires data.")
auth_user = authenticated_user()
if not auth_user:
return abort_json(401, "Must be logged in.")
new_email = request.json.get("email", None)
new_username = request.json.get("username", None)
display_name = request.json.get("name", "Anonymous User")
password = request.json.get("password", default_password())
if not new_email:
return abort_json(400, "Email parameter is required.")
req_user = lookup_user(email=new_email, username=new_username)
new_user_created = False
if not req_user:
new_user_created = True
req_user = User()
req_user.username = new_username
req_user.email = new_email
req_user.password_hash = generate_password_hash(password)
req_user.display_name = display_name
req_user.is_demo_user = auth_user.is_demo_user
db.session.add(req_user)
permissions_by_institution = defaultdict(set)
for permission_request in request.json.get("user_permissions", []):
try:
for permission_name in permission_request["permissions"]:
permissions_by_institution[permission_request["institution_id"]].add(permission_name)
except KeyError as e:
return abort_json(400, "Missing key in user_permissions object: {}".format(str(e)))
safe_commit(db)
old_permissions = req_user.to_dict_permissions()
for institution_id, permission_names in list(permissions_by_institution.items()):
if auth_user.has_permission(institution_id, Permission.admin()):
command = "delete from jump_user_institution_permission where user_id=%s and institution_id=%s"
with get_db_cursor() as cursor:
cursor.execute(command, (req_user.id, institution_id,))
safe_commit(db)
for permission_name in permission_names:
permission = Permission.get(permission_name)
if permission:
user_perm = UserInstitutionPermission()
user_perm.permission_id = permission.id,
user_perm.user_id = req_user.id,
user_perm.institution_id = institution_id
db.session.add(user_perm)
else:
return abort_json(400, "Unknown permission: {}.".format(permission_name))
else:
return abort_json(403, "Not authorized to create users for institution {}".format(institution_id))
safe_commit(db)
db.session.refresh(req_user)
new_permissions = req_user.to_dict_permissions()
if new_user_created:
email_institution = Institution.query.get(
list(permissions_by_institution.keys())[0]
) if permissions_by_institution else None
email = create_email(req_user.email, "Welcome to Unsub", "new_user", {"data": {
"email": new_email,
"password": password,
"institution_name": email_institution and email_institution.display_name
}})
send(email, for_real=True)
else:
notify_changed_permissions(req_user, auth_user, old_permissions, new_permissions)
return jsonify_fast_no_sort(req_user.to_dict())
@app.route("/user/me", methods=["POST", "GET"])
@jwt_required()
def my_user_info():
login_user = authenticated_user()
if not login_user:
return abort_json(401, "Must be logged in.")
if request.method == "POST":
if not request.is_json:
return abort_json(400, "Post a User object to change properties.")
if "email" in request.json:
email = request.json["email"]
if not email:
return abort_json(400, "Can't remove your email address.")
email_user = lookup_user(email=email)
if email_user and email_user.id != login_user.id:
return abort_json(409, "A user with email {} already exists.".format(email))
login_user.email = email
if "username" in request.json:
username = request.json["username"]
username_user = lookup_user(username=username)
if username_user and username_user.id != login_user.id:
return abort_json(409, "A user with username {} already exists.".format(username))
login_user.username = username
if "name" in request.json:
login_user.display_name = request.json["name"]
if "password" in request.json:
login_user.password_hash = generate_password_hash(request.json["password"] or "")
db.session.merge(login_user)
safe_commit(db)
return jsonify_fast_no_sort(login_user.to_dict())
@app.route("/user/id/<user_id>", methods=["GET"], defaults={"email": None, "username": None})
@app.route("/user/email/<email>", methods=["GET"], defaults={"user_id": None, "username": None})
@app.route("/user/username/<username>", methods=["GET"], defaults={"email": None, "user_id": None})
def user_info(user_id, email, username):
user = lookup_user(user_id=user_id, email=email, username=username)
if user:
return jsonify_fast_no_sort(user.to_dict())
else:
return abort_json(404, "User does not exist.")
@app.route("/user-permissions", methods=["GET", "POST"])
@jwt_required()
def user_permissions():
request_args = dict(request.args)
request_args.update(request.form)
if request.is_json:
request_args.update(request.json)
user_id = request_args.get("user_id", None)
email = request_args.get("user_email", None)
username = request_args.get("username", None)
institution_id = request_args.get("institution_id", None)
if not (user_id or email or username):
return abort_json(400, "A user_id, user_email, or username parameter is required.")
if isinstance(user_id, list):
user_id = user_id[0]
if isinstance(email, list):
email = email[0]
if isinstance(username, list):
username = username[0]
if not institution_id:
return abort_json(400, "Missing institution_id parameter.")
elif isinstance(institution_id, list):
institution_id = institution_id[0]
query_user = lookup_user(user_id=user_id, email=email, username=username)
if not query_user:
return abort_json(404, "User does not exist.")
if request.method == "POST":
old_permissions = query_user.to_dict_permissions()
auth_user = authenticated_user()
if not auth_user:
return abort_json(401, "Must be logged in.")
inst = Institution.query.get(institution_id)
if not inst:
return abort_json(404, "Institution does not exist.")
if not auth_user.has_permission(institution_id, Permission.admin()):
return abort_json(403, "Must have Admin permission to modify user permissions.")
permission_names = request_args.get("permissions", request_args.get("data", None))
if permission_names is None:
return abort_json(400, "Missing permissions list.")
if not isinstance(permission_names, list):
permission_names = [permission_names]
if query_user.id == auth_user.id and Permission.admin().name not in permission_names:
return abort_json(400, "Cannot revoke own admin permission.")
command = "delete from jump_user_institution_permission where user_id=%s and institution_id=%s"
with get_db_cursor() as cursor:
cursor.execute(command, (query_user.id, institution_id,))
perm_ids = []
for permission_name in permission_names:
permission = Permission.get(permission_name)
if permission:
perm_ids.append(permission.id)
else:
return abort_json(400, "Unknown permission: {}.".format(permission_name))
# this if block = don't run if role set to "unaffiliated", which drops permissions for the user_id
if perm_ids:
insert_values = [(user_id, institution_id, x,) for x in perm_ids]
with get_db_cursor() as cursor:
qry = sql.SQL("INSERT INTO jump_user_institution_permission values %s")
execute_values(cursor, qry, insert_values)
safe_commit(db)
db.session.refresh(query_user)
new_permissions = query_user.to_dict_permissions()
notify_changed_permissions(query_user, auth_user, old_permissions, new_permissions)
return jsonify_fast_no_sort(query_user.to_dict_permissions().get(institution_id, {}))
# @app.route("/institution/institution-Afxc4mAYXoJH", methods=["GET"])
# @jwt_required()
# def institution_jisc(institution_id="institution-Afxc4mAYXoJH"):
# print u"in institution_jisc"
#
# inst = Institution.query.get(institution_id)
# if not inst:
# return abort_json(404, u"Institution does not exist.")
#
# if not authorize_institution(inst, Permission.view()):
# return abort_json(403, u"Must have read permission to get institution properties.")
#
# print "authorized"
# response_dict = s3_cache_get("institution/institution-Afxc4mAYXoJH")
#
# return jsonify_fast_no_sort(response_dict)
@app.route("/institution/<institution_id>", methods=["POST", "GET"])
@jwt_required()
def institution(institution_id):
inst = Institution.query.get(institution_id)
if not inst:
return abort_json(404, "Institution does not exist.")
if request.method == "POST":
if not authorize_institution(inst, Permission.modify()):
return abort_json(403, "Must have Write permission to modify institution properties.")
request_args = request.args
if request.is_json:
request_args = request.json
display_name = request_args.get("name", None)
if display_name:
inst.display_name = display_name
db.session.add(inst)
safe_commit(db)
if not authorize_institution(inst, Permission.view()):
return abort_json(403, "Must have read permission to get institution properties.")
return jsonify_fast_no_sort(inst.to_dict())
@app.route("/institution/<institution_id>/ror/<ror_id>", methods=["POST", "DELETE"])
@jwt_required()
def institution_ror_id(institution_id, ror_id):
inst = Institution.query.get(institution_id)
if not inst:
return abort_json(404, "Institution does not exist.")
if not authorize_institution(inst, Permission.modify()):
return abort_json(403, "Must have Write permission to modify institution properties.")
grid_ids = [x.grid_id for x in RorGridCrosswalk.query.filter(RorGridCrosswalk.ror_id == ror_id).all()]
if request.method == "POST":
if not grid_ids:
return abort_json(404, "Unknown ROR '{}'.".format(ror_id))
db.session.merge(RorId(institution_id=inst.id, ror_id=ror_id))
for grid_id in grid_ids:
db.session.merge(GridId(institution_id=inst.id, grid_id=grid_id))
elif request.method == "DELETE":
command = "delete from jump_ror_id where ror_id=%s and institution_id=%s"
with get_db_cursor() as cursor:
cursor.execute(command, (ror_id, institution_id,))
for grid_id in grid_ids:
command = "delete from jump_grid_id where grid_id=%s and institution_id=%s"
with get_db_cursor() as cursor:
cursor.execute(command, (grid_id, institution_id,))
db.session.commit()
return jsonify_fast_no_sort(inst.to_dict())
# curl -s -X POST -H 'Accept: application/json' -H "Content-Type: application/json' --data '{"username":"test","password":"password","rememberMe":false}' http://localhost:5004/login
# curl -H 'Accept: application/json' -H "Authorization: Bearer ${TOKEN}" http://localhost:5004/protected
# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
# Access the identity of the current user with get_jwt_identity
identity_dict = get_jwt_identity()
return jsonify({"logged_in_as": identity_dict["user_id"]})
# Protect a view with jwt_required, which requires a valid access token
# in the request to access.
@app.route("/super", methods=["GET"])
def super():
if not is_authorized_superuser():
abort_json(403, "Secret doesn't match, not getting package")
return jsonify({"success": True})
def is_authorized_superuser():
secret = request.args.get("secret", "")
if secret and safe_str_cmp(secret, os.getenv("JWT_SECRET_KEY")):
return True
return False
def authorize_institution(auth_institution, required_permission):
if is_authorized_superuser():
return True
auth_user = authenticated_user()
if not auth_user:
return abort_json(401, "Authentication required.")
return auth_user.has_permission(auth_institution.id, required_permission)
def get_saved_scenario(scenario_id, test_mode=False, required_permission=None):
my_saved_scenario = SavedScenario.query.get(scenario_id)
if not my_saved_scenario:
abort_json(404, "Scenario {} not found.".format(scenario_id))
if required_permission:
if my_saved_scenario.package.institution_id:
authenticate_for_package(my_saved_scenario.package.package_id, required_permission)
else:
abort_json(
400,
"Scenario package {} has no institution_id. Can't decide how to authenticate.".format(
my_saved_scenario.package.package_id
)
)
my_saved_scenario.set_live_scenario(None)
return my_saved_scenario
@app.route("/account", methods=["GET"])
@jwt_required()
def live_account_get():
return abort_json(404, "Removed. Use /user/me or /institution/<institution_id>.")
def get_jwt():
if request.args and request.args.get("jwt", None):
return request.args.get("jwt")
if "Authorization" in request.headers and request.headers["Authorization"] and "Bearer " in request.headers["Authorization"]:
return request.headers["Authorization"].replace("Bearer ", "")
return None
# @app.route("/publisher/package-3WkCDEZTqo6S", methods=["GET"])
# @jwt_required()
# def get_package_jisc_package_3WkCDEZTqo6S(package_id="package-3WkCDEZTqo6S"):
# authenticate_for_package(package_id, Permission.view())
# print u"in get_package_package_3WkCDEZTqo6S"
# response_dict = s3_cache_get("publisher/package-3WkCDEZTqo6S")
# return jsonify_fast_no_sort(response_dict)
def get_feedback(feedback_id):
package_id = feedback_id.replace("feedback-", "package-")
authenticate_for_package(package_id, Permission.view())
package = Package.query.filter(Package.package_id == package_id).scalar()
package_dict = package.to_package_dict_feedback_set()
response = jsonify_fast_no_sort(package_dict)
return response
@app.route("/publisher/<package_id>", methods=["GET"])
@app.route("/package/<package_id>", methods=["GET"])
@app.route("/feedback/<package_id>", methods=["GET"])
@jwt_required()
def get_package(package_id):
if package_id.startswith("feedback"):
return get_feedback(package_id)
authenticate_for_package(package_id, Permission.view())
package = Package.query.filter(Package.package_id == package_id).scalar()
package_dict = package.to_package_dict()
response = jsonify_fast_no_sort(package_dict)
return response
@app.route("/publisher/<publisher_id>", methods=["POST"])
@jwt_required()
def update_publisher(publisher_id):
authenticate_for_package(publisher_id, required_permission=Permission.modify())
publisher = Package.query.filter(Package.package_id == publisher_id).scalar()
if not request.is_json:
return abort_json(400, "Post an object to change properties.")
if "name" in request.json:
publisher.package_name = request.json["name"]
if "description" in request.json:
publisher.package_description = request.json["description"]
if "currency" in request.json:
publisher.currency = request.json["currency"]
if (publisher.currency == "") or (publisher.currency == None):
publisher.currency = None
else:
publisher.currency = publisher.currency.upper()
if "is_deleted" in request.json:
publisher.is_deleted = request.json["is_deleted"]
if "cost_bigdeal" in request.json:
cost = request.json["cost_bigdeal"]
if (cost == "") or (cost == None):
cost = None
else:
try:
cost = int(float(cost))
except (ValueError, TypeError):
return abort_json(400, "Couldn't parse cost_bigdeal '{}' as an int.".format(cost))
publisher.big_deal_cost = cost
if "cost_bigdeal_increase" in request.json:
increase = request.json["cost_bigdeal_increase"]
if (increase == "") or (increase == None):
increase = None
else:
try:
increase = float(increase)
except (ValueError, TypeError):
return abort_json(400, "Couldn't parse cost_bigdeal_increase '{}' as a float.".format(increase))
publisher.big_deal_cost_increase = increase
db.session.merge(publisher)
safe_commit(db)
package_dict = publisher.to_package_dict()
return jsonify_fast_no_sort(package_dict)
@app.route("/publisher/new", methods=["POST"])
@jwt_required()
def new_publisher():
auth_user = authenticated_user()
if not request.is_json:
return abort_json(400, "Post an object to change properties.")
if "institution_id" not in request.json:
return abort_json(400, "institution_id is required")
pub_institution = Institution.query.get(request.json["institution_id"])
if not pub_institution:
abort_json(404, "institution not found")
if not auth_user.has_permission(pub_institution.id, Permission.modify()):
abort_json(401, "must have Modify permission for institution {}".format(pub_institution.id))
if "name" not in request.json:
return abort_json(400, "name is required")
new_package = Package()
new_package.package_id = "package-{}".format(shortuuid.uuid()[0:12])
new_package.institution_id = pub_institution.id
new_package.package_name = request.json["name"]
new_package.package_description = request.json.get("description", None)
new_package.publisher = None
new_package.is_demo = pub_institution.is_demo_institution
new_package.created = datetime.datetime.utcnow().isoformat()
db.session.add(new_package)
safe_commit(db)
package_dict = new_package.to_package_dict()
return jsonify_fast_no_sort(package_dict)
def _long_error_message():
return "Something is wrong with the input file. This is placeholder for a message describing it. It's a little longer than the longest real message."
def _json_to_temp_file(req):
if "file" in req.json and "name" in req.json:
file_name = req.json["name"] or ""
suffix = ".{}".format(file_name.split(".")[-1]) if "." in file_name else ""
temp_filename = tempfile.mkstemp(suffix=suffix)[1]
with open(temp_filename, "wb") as temp_file:
temp_file.write(req.json["file"].split(",")[-1].decode("base64"))
return temp_filename
else:
return None
def _load_package_file(package_id, req, file_type, table_class):
loader = table_class()
temp_file = _json_to_temp_file(req)
if temp_file:
load_result = loader.load(package_id, temp_file, file_type, commit=True)
if load_result["success"]:
return load_result
else:
return abort_json(400, load_result)
else:
return abort_json(400, "expected a JSON object like {file: <base64-encoded file>, name: <file name>}")
@app.route("/publisher/<package_id>/<data_file_name>/status", methods=["GET"])
@jwt_required()
def jump_data_file_status(package_id, data_file_name):
authenticate_for_package(package_id, Permission.view())
package = Package.query.filter(Package.package_id == package_id).scalar()
package_dict = package.to_package_dict()
data_files_list = package_dict["data_files"]
for data_file_dict in data_files_list:
if data_file_dict["name"] == data_file_name:
return jsonify_fast_no_sort(data_file_dict)
return abort_json(400, "Unknown data file type {}".format(data_file_name))
@app.route("/publisher/<package_id>/counter-jr1", methods=["GET", "POST", "DELETE"])
@app.route("/publisher/<package_id>/counter-trj2", methods=["GET", "POST", "DELETE"])
@app.route("/publisher/<package_id>/counter-trj3", methods=["GET", "POST", "DELETE"])
@app.route("/publisher/<package_id>/counter-trj4", methods=["GET", "POST", "DELETE"])
@app.route("/publisher/<package_id>/counter", methods=["GET", "POST", "DELETE"])
@jwt_required()
def jump_counter(package_id):
authenticate_for_package(package_id, Permission.view() if request.method == "GET" else Permission.modify())
url_end = request.base_url.rsplit("/", 1)[1]
if url_end == "counter":
url_end = "counter-jr1"
report_name = url_end.split("-")[1]
if request.method == "GET":
rows = Counter.query.filter(Counter.package_id == package_id, Counter.report_name == report_name).all()
if rows:
return jsonify_fast_no_sort({"rows": [row.to_dict() for row in rows]})
else:
return abort_json(404, "no counter file for package {}".format(package_id))
elif request.method == "DELETE":
CounterInput().set_to_delete(package_id, report_name)
return jsonify_fast_no_sort({"message": "Queued for delete."})
else:
if request.args.get("error", False):
return abort_json(400, _long_error_message())
else:
print("loading counter package {}".format(package_id))
response = _load_package_file(package_id, request, url_end, CounterInput)
return jsonify_fast_no_sort(response)
# @app.route("/publisher/<package_id>/counter/raw", methods=["GET"])
# @jwt_required()
# def jump_get_raw_counter(package_id):
# authenticate_for_package(package_id, Permission.view() if request.method == "GET" else Permission.modify())
#
# raw = CounterInput.get_raw_upload_object(package_id)
#
# if not raw:
# return abort_json(404, u"no raw counter file for package {}".format(package_id))
#
# return Response(raw["body"], content_type=raw["content_type"], headers=raw["headers"])
@app.route("/publisher/<package_id>/perpetual-access", methods=["GET", "POST", "DELETE"])
@jwt_required()
def jump_perpetual_access(package_id):
package = authenticate_for_package(package_id, Permission.view() if request.method == "GET" else Permission.modify())
if request.method == "GET":
rows = PerpetualAccess.query.filter(PerpetualAccess.package_id == package_id, PerpetualAccess.issn_l != None).all()
if rows:
return jsonify_fast_no_sort({"rows": [row.to_dict() for row in rows]})
else: