-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathimplementation.py
3588 lines (2994 loc) · 127 KB
/
implementation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import flask
import flask_babel
from flask_babel import gettext
from flask import render_template, session, redirect, make_response, request, \
jsonify
import jwt
import requests
from requests.auth import AuthBase
from urllib.parse import quote
from os import path
from datetime import datetime
import base64
import functools
import re
from string import ascii_lowercase
from microsetta_interface.model_i18n import translate_source, \
translate_sample, translate_survey_template, EN_US_KEY, LANGUAGES, \
ES_MX_KEY, ES_ES_KEY, JA_JP_KEY, PARTIAL_TO_FULL_LOCALES
# Authrocket uses RS256 public keys, so you can validate anywhere and safely
# store the key in code. Obviously using this mechanism, we'd have to push code
# to roll the keys, which is not ideal, but you can instead hold this in a
# config somewhere and reload
# Python is dumb, don't put spaces anywhere in this string.
from werkzeug.exceptions import BadRequest, Unauthorized
from microsetta_interface.config_manager import SERVER_CONFIG
import importlib.resources as pkg_resources
from microsetta_interface.redis_cache import RedisCache
from microsetta_interface.util import has_non_keyword_arguments, \
parse_request_csv_col, parse_request_csv, dict_to_csv
from collections import defaultdict
# TODO: source from a microsetta_private_api endpoint
class Source:
SOURCE_TYPE_HUMAN = "human"
SOURCE_TYPE_ANIMAL = "animal"
SOURCE_TYPE_ENVIRONMENT = "environmental"
PUBKEY_ENVVAR = 'MICROSETTA_INTERFACE_DEBUG_JWT_PUB'
if os.environ.get(PUBKEY_ENVVAR, False):
PUB_KEY = open(os.environ[PUBKEY_ENVVAR]).read()
else:
PUB_KEY = pkg_resources.read_text(
'microsetta_interface',
"authrocket.pubkey")
TOKEN_KEY_NAME = 'token'
ADMIN_MODE_KEY = 'admin_mode'
LOGIN_INFO_KEY = 'login_info'
LANG_KEY = "language"
RECONSENT_DECLINED_KEY = "reconsent_declined"
SOURCE_ID = "source_id"
HOME_URL = "/home"
HELP_EMAIL = "microsetta@ucsd.edu"
REROUTE_KEY = "reroute"
ACTIVATION_CODE_KEY = "code"
KIT_NAME_KEY = "kit_name"
EMAIL_CHECK_KEY = "email_checked"
ACCT_FNAME_KEY = "first_name"
ACCT_LNAME_KEY = "last_name"
ACCT_EMAIL_KEY = "email"
ACCT_ADDR_KEY = "address"
ACCT_ADDR_STREET_KEY = "street"
ACCT_ADDR_STREET2_KEY = "street2"
ACCT_ADDR_CITY_KEY = "city"
ACCT_ADDR_STATE_KEY = "state"
ACCT_ADDR_POST_CODE_KEY = "post_code"
ACCT_ADDR_COUNTRY_CODE_KEY = "country_code"
ACCT_LANG_KEY = "language"
ACCT_TERMS_KEY = "consent_privacy_terms"
ACCT_WRITEABLE_KEYS = [ACCT_FNAME_KEY, ACCT_LNAME_KEY, ACCT_EMAIL_KEY,
ACCT_ADDR_KEY, ACCT_LANG_KEY, ACCT_TERMS_KEY]
# States
NEEDS_REROUTE = "NeedsReroute"
NEEDS_LOGIN = "NeedsLogin"
NEEDS_ACCOUNT = "NeedsAccount"
NEEDS_EMAIL_CHECK = "NeedsEmailCheck"
NEEDS_PRIMARY_SURVEYS = "NeedsPrimarySurveys"
HOME_PREREQS_MET = "TokenPrereqsMet"
ACCT_PREREQS_MET = "AcctPrereqsMet"
SOURCE_PREREQS_MET = "SourcePrereqsMet"
NEEDS_BIOSPECIMEN_CONSENT = "NeedsBiospecimenConsent"
BIOSPECIMEN_PREREQS_MET = "BiospecimenPrereqsMet"
# TODO FIXME HACK: VIOSCREEN_ID is just hardcoded. Api does not specify what
# special handling is required. API must specify per-sample survey templates
# in some way, as well as any special handling for external surveys.
BASIC_INFO_ID = 10
AT_HOME_ID = 11
LIFESTYLE_ID = 12
GUT_ID = 13
GENERAL_HEALTH_ID = 14
HEALTH_DIAG_ID = 15
ALLERGIES_ID = 16
DIET_ID = 17
DETAILED_DIET_ID = 18
MIGRAINE_ID = 19
SURFERS_ID = 20
COVID19_ID = 21
OTHER_ID = 22
VIOSCREEN_ID = 10001
MYFOODREPO_ID = 10002
POLYPHENOL_FFQ_ID = 10003
SPAIN_FFQ_ID = 10004
SYSTEM_MSG_DICTIONARY = {
"going_down": {
EN_US_KEY: "The system is going down at ",
ES_MX_KEY: "El sistema se apaga a las ",
ES_ES_KEY: "El sistema se apaga a las ",
JA_JP_KEY: "システムは にダウンしています "
},
"test_mode": {
EN_US_KEY: 'The system is currently undergoing maintenance and '
'testing. Please refrain from using the site and check '
'back later, or <a href="mailto:microsetta@ucsd.edu">'
'contact us</a> with any questions.',
ES_MX_KEY: 'Por el momento, el sistema se encuentra en mantenimiento '
'y pruebas. Por favor no use el sitio web y vuelva a '
'consultar más tarde, o '
'<a href="mailto:microsetta@ucsd.edu">contáctenos</a> si '
'tiene alguna pregunta.',
ES_MX_KEY: 'Por el momento, el sistema se encuentra en mantenimiento '
'y pruebas. Por favor no use el sitio web y vuelva a '
'consultar más tarde, o '
'<a href="mailto:microsetta@ucsd.edu">contáctenos</a> si '
'tiene alguna pregunta.',
JA_JP_KEY: 'The system is currently undergoing maintenance and '
'testing. Please refrain from using the site and check '
'back later, or <a href="mailto:microsetta@ucsd.edu">'
'contact us</a> with any questions.'
'-- REAL TRANSLATION PENDING --',
}
}
client_state = RedisCache()
# Countries allowed to view the contents of the My Kits tab
KITS_TAB_WHITELIST = {'US', 'ES', 'JP'}
# Countries allowed to view the contents of the My Nutrition tab
NUTRITION_TAB_WHITELIST = {'US'}
# Description of MelissaData error codes to use on the /update_address path.
# https://wiki.melissadata.com/?title=Result_Code_Details#Global_Address_Ver\
# ification
ADDRESS_ERRORS = {
EN_US_KEY: {
'AE01': 'The address could not be verified at least up to the postal '
'code level.',
'AE02': 'Could not match the input street to a unique street name. '
'Either no matches or too many matches found.',
'AE03': 'The combination of directionals (N, E, SW, etc) and the '
'suffix (AVE, ST, BLVD) is not correct and produced multiple '
'possible matches.',
'AE05': 'The address was matched to multiple records. There is not '
'enough information available in the address to break the tie '
'between multiple records.',
'AE08': 'An address element after the house number, in most cases the '
'sub-premise, was not valid.',
'AE09': 'An address element after the house number, in most cases the '
'sub-premise, was missing.',
'AE10': 'The premise (house or building) number for the address is '
'not valid.',
'AE11': 'The premise (house or building) number for the address is '
'missing.',
'AE12': 'The PO (Post Office Box), RR (Rural Route), or HC (Highway '
'Contract) Box number is invalid.',
'AE13': 'The PO (Post Office Box), RR (Rural Route), or HC (Highway '
'Contract) Box number is missing.',
'AE14': 'US Only. The address is a Commercial Mail Receiving Agency '
'(CMRA) and the Private Mail Box (PMB or #) number is '
'missing.'
},
ES_MX_KEY: {
'AE01': 'La dirección no se pudo verificar al menos hasta el nivel '
'del código postal.',
'AE02': 'La dirección ingresada no coincide con una dirección única.'
' Ya sea porque no se encontró una dirección coincidente o '
'se encontraron varias coincidencias.',
'AE03': 'La combinación de la direccional (N, E, SW, etc.) y el '
'sufijo (AVE, ST, BLVD) no es correcta y produce múltiples '
'coincidencias.',
'AE05': 'La dirección coincidió con múltiples registros. No hay '
'suficientes datos disponibles en la dirección para '
'diferenciarla entre los múltiples registros.',
'AE08': 'Un dato de la dirección después del número de la casa, en '
'la mayoría de los casos el sublocal (por ejemplo Unit A, '
'#10), no era válido.',
'AE09': 'Un dato de la dirección después del número de la casa, en '
'la mayoría de los casos el sublocal (por ejemplo Unit A, '
'#10), faltaba.',
'AE10': 'El número del local (casa o edificio) para la dirección no '
'es válido.',
'AE11': 'Falta el número del local (casa o edificio) para la '
'dirección.',
'AE12': 'El número de apartado PO (Apartado postal), RR (Ruta rural) '
'o HC (Contrato de carretera) no es válido.',
'AE13': 'Falta el número del apartado PO (Apartado postal), RR (Ruta '
'rural) o HC (Contrato de carretera).',
'AE14': 'La dirección es una Agencia receptora de correo comercial '
'(CMRA) y falta el número del buzón de correo privado (PMB '
'o #).'
},
ES_ES_KEY: {
'AE01': 'La dirección no se pudo verificar al menos hasta el nivel '
'del código postal.',
'AE02': 'La dirección ingresada no coincide con una dirección única.'
' Ya sea porque no se encontró una dirección coincidente o '
'se encontraron varias coincidencias.',
'AE03': 'La combinación de la direccional (N, E, SW, etc.) y el '
'sufijo (AVE, ST, BLVD) no es correcta y produce múltiples '
'coincidencias.',
'AE05': 'La dirección coincidió con múltiples registros. No hay '
'suficientes datos disponibles en la dirección para '
'diferenciarla entre los múltiples registros.',
'AE08': 'Un dato de la dirección después del número de la casa, en '
'la mayoría de los casos el sublocal (por ejemplo Unit A, '
'#10), no era válido.',
'AE09': 'Un dato de la dirección después del número de la casa, en '
'la mayoría de los casos el sublocal (por ejemplo Unit A, '
'#10), faltaba.',
'AE10': 'El número del local (casa o edificio) para la dirección no '
'es válido.',
'AE11': 'Falta el número del local (casa o edificio) para la '
'dirección.',
'AE12': 'El número de apartado PO (Apartado postal), RR (Ruta rural) '
'o HC (Contrato de carretera) no es válido.',
'AE13': 'Falta el número del apartado PO (Apartado postal), RR (Ruta '
'rural) o HC (Contrato de carretera).',
'AE14': 'La dirección es una Agencia receptora de correo comercial '
'(CMRA) y falta el número del buzón de correo privado (PMB '
'o #).'
},
JA_JP_KEY: {
'AE01': 'The address could not be verified at least up to the postal '
'code level.',
'AE02': 'Could not match the input street to a unique street name. '
'Either no matches or too many matches found.',
'AE03': 'The combination of directionals (N, E, SW, etc) and the '
'suffix (AVE, ST, BLVD) is not correct and produced multiple '
'possible matches.',
'AE05': 'The address was matched to multiple records. There is not '
'enough information available in the address to break the tie '
'between multiple records.',
'AE08': 'An address element after the house number, in most cases the '
'sub-premise, was not valid.',
'AE09': 'An address element after the house number, in most cases the '
'sub-premise, was missing.',
'AE10': 'The premise (house or building) number for the address is '
'not valid.',
'AE11': 'The premise (house or building) number for the address is '
'missing.',
'AE12': 'The PO (Post Office Box), RR (Rural Route), or HC (Highway '
'Contract) Box number is invalid.',
'AE13': 'The PO (Post Office Box), RR (Rural Route), or HC (Highway '
'Contract) Box number is missing.',
'AE14': 'US Only. The address is a Commercial Mail Receiving Agency '
'(CMRA) and the Private Mail Box (PMB or #) number is '
'missing.'
},
}
# TODO: Move this sort of survey info ino the database
SURVEY_INFO = {
BASIC_INFO_ID: {
'description': '',
'est_minutes': '2',
'icon': 'survey_basic_information.svg'
},
AT_HOME_ID: {
'description': '',
'est_minutes': '2',
'icon': 'survey_at_home.svg'
},
LIFESTYLE_ID: {
'description': '',
'est_minutes': '8',
'icon': 'survey_lifestyle.svg'
},
GUT_ID: {
'description': '',
'est_minutes': '4',
'icon': 'survey_gut.svg'
},
GENERAL_HEALTH_ID: {
'description': '',
'est_minutes': '8',
'icon': 'survey_general_health.svg'
},
HEALTH_DIAG_ID: {
'description': '',
'est_minutes': '8',
'icon': 'survey_health_diagnosis.svg'
},
ALLERGIES_ID: {
'description': '',
'est_minutes': '2',
'icon': 'survey_allergies.svg'
},
DIET_ID: {
'description': '',
'est_minutes': '5',
'icon': 'survey_diet.svg'
},
DETAILED_DIET_ID: {
'description': '',
'est_minutes': '18',
'icon': 'survey_detailed_diet.svg'
},
COVID19_ID: {
'description': '',
'est_minutes': '8',
'icon': 'survey_covid_19.svg'
},
OTHER_ID: {
'description': '',
'est_minutes': '2',
'icon': 'survey_other.svg'
},
VIOSCREEN_ID: {
'description': 'Our standard food frequency questionnaire',
'est_minutes': '30',
'icon': 'survey_external.svg'
},
MYFOODREPO_ID: {
'description': '<strong>Only for US Participants:</strong><br />'
'By sharing photos of all the food you eat via a '
'mobile app for <strong>seven days</strong>, you '
'will help us learn more about the microbes in the '
'gut.<br /><br />'
'<font color="red"><strong>Important!</strong></font> '
'Before taking part, please read more from the '
'following link: '
'<a href="https://microsetta.ucsd.edu/myfoodrepo/" '
'target="_blank">How to complete participation</a>.'
'<br /><br /><strong>Availability is limited</strong>: '
'Once you click on the "Start" button, you will be '
'directed to a site containing a unique code for you '
'to use to activate the app on your phone. <strong>'
'Please note</strong> - The code will only be '
'available to view once, so please keep a record of it '
'if you are not able to use it immediately. You will '
'have <strong>two weeks</strong> to use the app before '
'your access expires.',
'est_minutes': 'N/A',
'icon': 'survey_external.svg'
},
POLYPHENOL_FFQ_ID: {
'description': 'Polyphenols are chemical compounds naturally found in '
'plants that have been shown to provide many beneficial'
' properties. They are antioxidants, fighting aging and'
' protecting your heart, but they may also provide'
' benefits by interacting with the microbes in your '
'gut. This survey will allow us to better quantify '
'your consumption of polyphenols through your diet.',
'est_minutes': '30',
'icon': 'survey_external.svg'
},
SPAIN_FFQ_ID: {
'description': '<strong>Only for participants in Spain:</strong><br />'
'The Food Frequency Questionnaire (FFQ) will ask you '
'about your usual frequency of consumption of a list '
'of foods and beverages. The questionnaire consists of '
'28 questions, and will allow us to find out what your '
'usual diet is like.',
'est_minutes': '30',
'icon': 'survey_external.svg'
},
}
LOCAL_SURVEY_SEQUENCE = [
BASIC_INFO_ID,
AT_HOME_ID,
LIFESTYLE_ID,
GUT_ID,
GENERAL_HEALTH_ID,
HEALTH_DIAG_ID,
ALLERGIES_ID,
DIET_ID,
DETAILED_DIET_ID,
OTHER_ID
]
DAKLAPACK_KIT_RE = re.compile(r"DMK[234689ACDEFHJKMNPRTVWXY]{6}")
def _render_with_defaults(template_name, **context):
defaults = {}
admin_mode = session.get(ADMIN_MODE_KEY, False)
defaults["login_info"] = session.get(LOGIN_INFO_KEY, None)
defaults["admin_mode"] = admin_mode
msg, style, hours, minutes = client_state.get(RedisCache.SYSTEM_BANNER,
(None, None, None, None))
today = datetime.today()
if hours is None:
sys_msg_dt = datetime(today.year, today.month, today.day)
else:
sys_msg_dt = datetime(today.year, today.month, today.day, int(hours),
int(minutes))
defaults["system_msg_text"] = msg
defaults["system_msg_style"] = style
defaults["system_msg_time"] = flask_babel.format_datetime(sys_msg_dt,
'h:mm a')
defaults["system_msg_dictionary"] = SYSTEM_MSG_DICTIONARY
endpoint = SERVER_CONFIG["endpoint"]
public_endpoint = SERVER_CONFIG["public_api_endpoint"]
authrocket_url = SERVER_CONFIG["authrocket_url"]
defaults["endpoint"] = endpoint
defaults["authrocket_url"] = authrocket_url
defaults["public_endpoint"] = public_endpoint
defaults["EN_US_KEY"] = EN_US_KEY
defaults["languages"] = LANGUAGES
defaults.update(context)
return render_template(template_name, **defaults)
def _get_req_survey_templates_by_source_type(source_type):
if source_type == Source.SOURCE_TYPE_HUMAN:
return []
elif source_type == Source.SOURCE_TYPE_ANIMAL:
return []
elif source_type == Source.SOURCE_TYPE_ENVIRONMENT:
return []
else:
raise ValueError("Unknown source type: '%s'" % source_type)
def _get_opt_survey_templates_by_source_type(source_type):
if source_type == Source.SOURCE_TYPE_HUMAN:
return [3, 4, 5, 7, MYFOODREPO_ID, POLYPHENOL_FFQ_ID, SPAIN_FFQ_ID]
elif source_type == Source.SOURCE_TYPE_ANIMAL:
return []
elif source_type == Source.SOURCE_TYPE_ENVIRONMENT:
return []
else:
raise ValueError("Unknown source type: '%s'" % source_type)
def _make_path(account_id=None, source_id=None, suffix=None):
result = "/accounts"
if account_id is not None:
result = path.join(result, account_id)
if source_id is not None:
result = path.join(result, "sources", source_id)
if suffix is not None:
result = path.join(result, suffix)
return result
def _make_acct_path(account_id, suffix=None):
return _make_path(account_id=account_id, suffix=suffix)
def _make_source_path(account_id, source_id, suffix=None):
return _make_path(account_id=account_id, source_id=source_id,
suffix=suffix)
def _check_home_prereqs():
current_state = {}
if TOKEN_KEY_NAME not in session:
return NEEDS_LOGIN, current_state
if not session.get(ADMIN_MODE_KEY, False):
# Do they need to make an account? YES-> account_details.html
needs_reroute, accts_output, _ = ApiRequest.get("/accounts")
# if there's an error, reroute to error page
if needs_reroute:
current_state[REROUTE_KEY] = accts_output
return NEEDS_REROUTE, current_state
if len(accts_output) == 0:
# NB: Overwriting outputs from get call above
needs_reroute, accts_output, _ = ApiRequest.post(
"/accounts/legacies")
if needs_reroute:
current_state[REROUTE_KEY] = accts_output
return NEEDS_REROUTE, current_state
# if no legacy account found, need new account
if len(accts_output) == 0:
return NEEDS_ACCOUNT, current_state
# If you got here, you have a token and you have (at least one) account
# (True even of admins who skipped the above account check, as you can't
# be an admin unless you have a microsetta account that says you are)
return HOME_PREREQS_MET, current_state
def _check_acct_prereqs(account_id, current_state=None):
current_state = {} if current_state is None else current_state
current_state['account_id'] = account_id
# If we haven't yet checked for email mismatches and gotten user decision,
# and the user isn't an admin (who could be looking at another person's
# account and thus have that email not match their login one):
if not session.get(EMAIL_CHECK_KEY, False) and \
not session.get(ADMIN_MODE_KEY, False):
# Does email in our accounts table match email in authrocket?
needs_reroute, email_match, _ = ApiRequest.get(
'/accounts/{0}/email_match'.format(account_id))
if needs_reroute:
current_state[REROUTE_KEY] = email_match
return NEEDS_REROUTE, current_state
# if they don't match AND the user hasn't already refused update
if not email_match["email_match"]:
return NEEDS_EMAIL_CHECK, current_state
# IF we decide that every acct needs at least one source,
# this is where that check would go
return ACCT_PREREQS_MET, current_state
def _check_source_prereqs(acct_id, source_id, current_state=None):
SURVEY_TEMPLATE_ID_KEY = "survey_template_id"
current_state = {} if current_state is None else current_state
current_state[SOURCE_ID] = source_id
if not session.get(ADMIN_MODE_KEY, False):
# Get the input source
needs_reroute, source_output, _ = ApiRequest.get(
'/accounts/%s/sources/%s' %
(acct_id, source_id))
if needs_reroute:
current_state[REROUTE_KEY] = source_output
return NEEDS_REROUTE, current_state
# Get all required survey template ids for this source type
req_survey_template_ids = _get_req_survey_templates_by_source_type(
source_output["source_type"])
# Get all the current answered surveys for this source
needs_reroute, surveys_output, _ = ApiRequest.get(
'/accounts/{0}/sources/{1}/surveys'.format(acct_id, source_id))
if needs_reroute:
current_state[REROUTE_KEY] = surveys_output
return NEEDS_REROUTE, current_state
template_ids_of_answered_surveys = [x[SURVEY_TEMPLATE_ID_KEY] for x
in surveys_output]
# Get next required survey
# NOTE: current_state is updated *inplace*
needs_reroute = _update_needed_survey(req_survey_template_ids,
template_ids_of_answered_surveys,
current_state)
if needs_reroute is not None:
return needs_reroute, current_state
return SOURCE_PREREQS_MET, current_state
def _check_biospecimen_prereqs(acct_id, source_id, current_state=None):
current_state = {} if current_state is None else current_state
current_state[SOURCE_ID] = source_id
if not session.get(ADMIN_MODE_KEY, False):
# Get the input source
needs_reroute, source_output, _ = ApiRequest.get(
'/accounts/%s/sources/%s' %
(acct_id, source_id))
if needs_reroute:
current_state[REROUTE_KEY] = source_output
return NEEDS_REROUTE, current_state
# Test if biospecimen consent is required! If Required,
# route user to biospecimen consent
needs_reroute, consent_output, _ = ApiRequest.get(
'/accounts/%s/source/%s/consent/%s' %
(acct_id, source_id, 'biospecimen'))
if needs_reroute:
current_state[REROUTE_KEY] = consent_output
return NEEDS_REROUTE, current_state
if consent_output["result"]:
session[SOURCE_ID] = source_id
return NEEDS_BIOSPECIMEN_CONSENT, current_state
return BIOSPECIMEN_PREREQS_MET, current_state
def _update_needed_survey(survey_template_ids, ids_of_answered, current_state):
# For each required survey template id for this source type
for curr_survey_template_id in survey_template_ids:
# Does this source LACK an answered survey with this template id?
if curr_survey_template_id not in ids_of_answered:
current_state["needed_survey_template_id"] = \
curr_survey_template_id
return NEEDS_PRIMARY_SURVEYS
return None
def _check_relevant_prereqs(acct_id=None, source_id=None):
# Check home prereqs
prereq_step, current_state = _check_home_prereqs()
if prereq_step != HOME_PREREQS_MET:
return prereq_step, current_state
# Check acct prereqs
if acct_id is None:
return prereq_step, current_state
prereq_step, current_state = _check_acct_prereqs(acct_id, current_state)
if prereq_step != ACCT_PREREQS_MET:
return prereq_step, current_state
# Check source prereqs
if source_id is None:
return prereq_step, current_state
prereq_step, current_state = _check_source_prereqs(
acct_id, source_id, current_state
)
if prereq_step != SOURCE_PREREQS_MET:
return prereq_step, current_state
prereq_step, current_state = _check_biospecimen_prereqs(
acct_id, source_id, current_state
)
if prereq_step != BIOSPECIMEN_PREREQS_MET:
return SOURCE_PREREQS_MET, current_state
else:
return prereq_step, current_state
# To send arguments to a decorator, you define a factory method with those args
# that returns a decorator. The decorator then takes a function and returns
# a wrapper that you want to call instead. Thus there should be three layers.
def prerequisite(allowed_states: list, **parameter_overrides):
"""
Usage
@prerequisite([NEEDS_EMAIL_CHECK])
def get_update_email(account_id):
# If client is not in the NEEDS_EMAIL_CHECK state, they will be
# redirected rather than reaching get_update_email.
@prerequisite([State1, State2, State3])
def crazy_function(account_id, source_id):
# If client is not in one of State1, State2, State3 stats, they will
# be redirected.
@prerequisite([State1, State2], survey_template_id=VIOSCREEN_ID)
def vioscreen_callback(account_id, source_id, key):
# If client is not in one of State1, State2, they will be redirected
# Further, if they are determined to be in NEEDS_PRIMARY_SURVEYS, but
# their required survey template id is not VIOSCREEN_ID, they will be
# redirected. Note that this makes use of the parameter_overrides to
# set a specific parameter (survey_template_id) when the wrapped
# function knows what would be sent, but does not expose it within its
# method signature. (You might encounter this when the wrapped function
# is a callback function that must match some defined signature)
:param allowed_states: A list of states that are valid for
entry to the decorated function
:param parameter_overrides: A set of keyword arguments added or replacing
the wrapped function's input args for the purpose of determining prereqs
The wrapped function itself will never see these overridden values.
"""
if not isinstance(allowed_states, list):
raise TypeError("allowed_states must be a list")
allowed_states = set(allowed_states)
def decorator(func):
if has_non_keyword_arguments(func):
raise TypeError("Only functions with solely keyword arguments are "
"supported by this decorator. "
"Example: f(*, a=1, b=2, c=3)")
# Calling functools.wraps preserves information about the wrapped func
# so introspection/reflection can pull the original documentation even
# when passed the wrapper function.
@functools.wraps(func)
def wrapper(**kwargs):
kwargs_copy = dict(kwargs)
kwargs_copy.update(parameter_overrides)
# Check relevant prereqs from those arguments
prereqs_step, curr_state = _check_relevant_prereqs(
kwargs_copy.get('account_id'),
kwargs_copy.get(SOURCE_ID)
)
# Route to closest sink if state doesn't match a required state
if prereqs_step not in allowed_states:
return _route_to_closest_sink(prereqs_step, curr_state)
# For any states that require checking additional parameters, we do
# so here. (Remember to lookup from kwargs_copy)
# TODO: Ensure state specific checks don't grow unwieldy
if prereqs_step == NEEDS_PRIMARY_SURVEYS:
passed_id = kwargs_copy.get('survey_template_id')
needed_id = curr_state.get("needed_survey_template_id")
if passed_id != needed_id:
return _route_to_closest_sink(prereqs_step, curr_state)
# Add new state specific checks here
# if prereqs_state == XXX:
# if something's not right, reroute.
return func(**kwargs)
return wrapper
return decorator
# Client might not technically care who the user is, but if they do, they
# get the token, validate it, and pull email out of it.
def _parse_jwt(token):
decoded = jwt.decode(token, PUB_KEY, algorithms=['RS256'], verify=True)
email_verified = decoded.get('email_verified', False)
return decoded["email"], email_verified
def _route_to_closest_sink(prereqs_step, current_state):
# print("Current Prereq Step:", prereqs_step)
acct_id = current_state.get("account_id", None)
source_id = current_state.get(SOURCE_ID, None)
if prereqs_step == NEEDS_REROUTE:
# where you get rerouted to depends on why you need
# rerouting: api authorization errors go back to home page,
# all other api errors go to error page
return current_state[REROUTE_KEY]
elif prereqs_step == NEEDS_LOGIN or prereqs_step == HOME_PREREQS_MET:
return redirect(HOME_URL)
elif prereqs_step == NEEDS_ACCOUNT:
return redirect("/create_account")
elif prereqs_step == NEEDS_EMAIL_CHECK:
return redirect(_make_acct_path(acct_id, suffix="update_email"))
elif prereqs_step == NEEDS_PRIMARY_SURVEYS:
needed_survey_template_id = current_state["needed_survey_template_id"]
return redirect(_make_source_path(
acct_id, source_id, suffix="take_survey?survey_template_id=%s"
% needed_survey_template_id))
elif prereqs_step == ACCT_PREREQS_MET:
# redirect to the account details page (showing all the sources)
return redirect(_make_acct_path(acct_id))
elif prereqs_step == SOURCE_PREREQS_MET:
# redirect to the source details page (showing all samples)
return redirect(_make_source_path(acct_id, source_id))
elif prereqs_step == NEEDS_BIOSPECIMEN_CONSENT:
return render_consent_page(acct_id, source_id, "biospecimen")
elif prereqs_step == BIOSPECIMEN_PREREQS_MET:
return redirect(_make_source_path(acct_id, source_id, suffix="kits"))
else:
return get_show_error_page(
"Unknown prereq_step: '{0}'".format(prereqs_step))
def _refresh_state_and_route_to_sink(account_id=None, source_id=None):
prereqs_step, curr_state = _check_relevant_prereqs(account_id, source_id)
return _route_to_closest_sink(prereqs_step, curr_state)
def _get_kit(kit_name):
unable_to_validate_msg = gettext(
"The provided Kit ID is not in our system or has already been used."
)
error_msg = None
response = None
try:
# call api and find out if kit name has unclaimed samples.
# NOT doing this through ApiRequest.get bc in this case
# DON'T want the automated error-handling
response = requests.get(
ApiRequest.API_URL + '/kits/', # appending slash saves a 308 redir
auth=BearerAuth(session[TOKEN_KEY_NAME]),
verify=ApiRequest.CAfile,
params=ApiRequest.build_params({KIT_NAME_KEY: kit_name}))
if response.status_code == 404:
error_msg = unable_to_validate_msg
elif response.status_code > 200:
error_msg = unable_to_validate_msg
except: # noqa
error_msg = unable_to_validate_msg
if error_msg is not None:
if response is None:
return None, error_msg, 500
else:
return None, error_msg, response.status_code
return response.json(), None, response.status_code
def get_ajax_check_ffq_code(ffq_code):
try:
response = requests.get(
ApiRequest.API_URL + '/check_ffq_code',
auth=BearerAuth(session[TOKEN_KEY_NAME]),
verify=ApiRequest.CAfile,
params=ApiRequest.build_params({'ffq_code': ffq_code})
)
if response.status_code == 200:
return_val = True
else:
return_val = False
except: # noqa
return_val = False
return return_val
def _associate_sample_to_survey(account_id, source_id, sample_id, survey_id):
# Associate the input answered surveys with this sample.
has_error, sample_survey_output, _ = ApiRequest.post(
'/accounts/{0}/sources/{1}/samples/{2}/surveys'.format(
account_id, source_id, sample_id
), json={"survey_id": survey_id}
)
if has_error:
return sample_survey_output
return None
# Error display does not require any prereqs, so this method doesn't check any
def get_show_error_page(error_msg):
# output is general error page
error_txt = quote(error_msg)
mailto_url = "mailto:{0}?subject={1}&body={2}".format(
HELP_EMAIL, quote("minimal interface error"), error_txt)
output = _render_with_defaults('error.jinja2',
mailto_url=mailto_url,
error_msg=error_msg)
return output
def get_home():
email_verified = False
accts_output = None
has_session = TOKEN_KEY_NAME in session
if has_session:
try:
# If user leaves the page open, the token can expire before the
# session, so if our token goes back we need to force them to login
# again.
email, email_verified = _parse_jwt(session[TOKEN_KEY_NAME])
except jwt.exceptions.ExpiredSignatureError:
return redirect('/logout')
if email_verified:
home_step, curr_state = _check_home_prereqs()
if home_step == NEEDS_REROUTE:
return curr_state[REROUTE_KEY]
has_error, accts_output, _ = ApiRequest.get("/accounts")
# if there's an error, reroute to error page
if has_error:
return accts_output
else:
return _render_with_defaults('email_confirmation.jinja2')
else:
return _render_with_defaults('home.jinja2')
# Switch out home page in administrator mode
if session.get(ADMIN_MODE_KEY, False):
return _render_with_defaults('admin_home.jinja2',
accounts=[])
if accts_output is not None and len(accts_output) > 0:
account_id = accts_output[0]['account_id']
# If an account has exactly one source, we're going to redirect to
# that profile page. Otherwise, we go to the Account Dashboard
has_error, sources, _ = ApiRequest.get(
'/accounts/%s/sources' % account_id
)
if has_error:
return sources
if len(sources) == 1:
return redirect(
f'/accounts/{account_id}/sources/{sources[0][SOURCE_ID]}'
)
else:
return redirect(f'/accounts/{account_id}')
else:
# Note: account_details.jinja2 sends the user directly to authrocket
# to complete the login if they aren't logged in yet.
return redirect('/create_account')
def get_rootpath():
return redirect(HOME_URL)
def get_authrocket_callback(token=None, redirect_uri=None):
if token is None:
return redirect('/home')
session[TOKEN_KEY_NAME] = token
email, _ = _parse_jwt(token)
session[LOGIN_INFO_KEY] = {
"email": email
}
do_return, accts_output, _ = ApiRequest.get('/accounts')
if do_return:
return accts_output
# new authrocket logins do not have an account yet
if len(accts_output) > 0:
primary = accts_output[0]
session[ADMIN_MODE_KEY] = primary['account_type'] == 'admin'
session[LOGIN_INFO_KEY] = {
"account_id": primary['account_id'],
"email": primary['email']
}
# NB: Disabling Japanese for the initial relaunch period until the
# Tokyo Tech team can review finalized translations
if primary["language"] == JA_JP_KEY:
session[LANG_KEY] = EN_US_KEY
else:
session[LANG_KEY] = primary["language"]
else:
session[ADMIN_MODE_KEY] = False
session[LOGIN_INFO_KEY] = {
"account_id": None,
"email": email
}
if redirect_uri:
uri = base64.urlsafe_b64decode(redirect_uri).decode()
return redirect(uri)
return redirect(HOME_URL)
def get_logout():
session.clear()
return redirect(HOME_URL)
@prerequisite([NEEDS_ACCOUNT])
def get_create_account():
email, _ = _parse_jwt(session[TOKEN_KEY_NAME])
browser_lang = session_locale()
# TODO: Need to support other countries
# and not default to US and California
default_account_values = {
ACCT_EMAIL_KEY: email,
ACCT_FNAME_KEY: '',
ACCT_LNAME_KEY: '',
ACCT_ADDR_KEY: {
ACCT_ADDR_STREET_KEY: '',
ACCT_ADDR_STREET2_KEY: '',
ACCT_ADDR_CITY_KEY: '',
ACCT_ADDR_STATE_KEY: 'CA',
ACCT_ADDR_POST_CODE_KEY: '',
ACCT_ADDR_COUNTRY_CODE_KEY: 'US'
},
ACCT_LANG_KEY: browser_lang
}
return _render_with_defaults('account_details.jinja2',
CREATE_ACCT=True,
account=default_account_values)
@prerequisite([NEEDS_ACCOUNT])
def post_create_account(*, body=None):
if "consent_privacy_terms" not in body:
exception_msg = "You must agree to the Privacy Statement and Terms "\
"and Conditions."
raise Exception(exception_msg)
# the form posts consent_privacy_terms as a string but boolean is
# more appropriate for the API
consent_privacy_terms = False
if body['consent_privacy_terms'] == "True":
consent_privacy_terms = True
api_json = {