-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuser.py
2496 lines (2287 loc) · 79.2 KB
/
user.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
"""User API view functions"""
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from flask import (
Blueprint,
abort,
current_app,
jsonify,
make_response,
redirect,
request,
session,
url_for,
)
from flask_babel import force_locale
from flask_user import roles_required
from sqlalchemy import and_, func
from sqlalchemy.orm.exc import NoResultFound
from werkzeug.exceptions import Unauthorized
from ..audit import auditable_event
from ..cache import cache
from ..database import db
from ..date_tools import FHIR_datetime
from ..extensions import oauth, user_manager
from ..models.app_text import MailResource, UserInviteEmail_ATMA, app_text
from ..models.audit import Audit
from ..models.auth import Token
from ..models.client import Client, client_event_dispatch
from ..models.communication import load_template_args
from ..models.group import Group
from ..models.intervention import Intervention
from ..models.message import EmailMessage
from ..models.organization import Organization
from ..models.questionnaire_bank import trigger_date
from ..models.qb_timeline import QB_StatusCacheKey, invalidate_users_QBT
from ..models.questionnaire_response import QuestionnaireResponse
from ..models.relationship import Relationship
from ..models.research_study import EMPRO_RS_ID
from ..models.role import ROLE, Role
from ..models.table_preference import TablePreference
from ..models.url_token import url_token
from ..models.user import (
INVITE_PREFIX,
User,
UserRelationship,
current_user,
get_user,
permanently_delete_user,
validate_email,
)
from ..models.user_consent import UserConsent, consent_withdrawal_dates
from ..models.user_document import UserDocument
from ..type_tools import check_int
from .auth import logout
from .crossdomain import crossdomain
user_api = Blueprint('user_api', __name__, url_prefix='/api')
@user_api.route('/me')
@crossdomain()
@oauth.require_oauth()
def me():
"""Access basics for current user
returns authenticated user's id, username and email in JSON
---
tags:
- User
operationId: me
produces:
- application/json
responses:
200:
description: successful operation
schema:
id: user
required:
- id
- username
- email
properties:
id:
type: integer
format: int64
description: TrueNTH ID for user
username:
type: string
description: User's username - which will always match the email
email:
type: string
description: User's preferred email address, same as username
401:
description: if missing valid OAuth token
security:
- ServiceToken: []
"""
user = current_user()
# only return user id, if auth came from a URL such as embedded within an email
encounter = user.current_encounter(generate_failsafe_if_missing=False)
if encounter and encounter.auth_method == 'url_authenticated':
return jsonify(id=user.id)
return jsonify(
id=user.id, username=user.username, email=user.email)
@user_api.route('/account', methods=('POST',))
@crossdomain()
@oauth.require_oauth() # for service token access, oauth must come first
@roles_required(
[ROLE.APPLICATION_DEVELOPER.value, ROLE.ADMIN.value, ROLE.SERVICE.value,
ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
def account():
"""Create a user account
Due to complicated rules with respect to staff users being able to edit
the account generated by this endpoint, all data necessary to secure edit
rights on the new account must be included in the initial call. This will
typically include `organizations`, `consents` and `roles`.
On success, a simple JSON object is returned defining the new user's id.
If the user creating the account doesn't provide adequate details to secure
edit rights, a 400 will be generated.
Beyond account creation, additional endpoints may be used to adjust the
account details including:
1. PUT /api/demographics/{id}, with known details for the new user
2. PUT /api/user/{id}/roles to grant additional user role(s)
3. PUT /api/intervention/{name} grants the user access to the intervention.
---
tags:
- User
operationId: createAccount
parameters:
- in: body
name: body
schema:
id: account_args
properties:
organizations:
type: array
items:
type: object
required:
- organization_id
properties:
organization_id:
type: string
description:
Optional organization identifier defining the
organization the new user will belong to.
consents:
type: array
items:
type: object
required:
- organization_id
- agreement_url
properties:
organization_id:
type: integer
format: int64
description:
Organization identifier defining with whom the consent
agreement applies
acceptance_date:
type: string
format: date-time
description:
optional UTC date-time for when the agreement expires,
defaults to utcnow
expires:
type: string
format: date-time
description:
optional UTC date-time for when the agreement expires,
defaults to utcnow plus 5 years
agreement_url:
type: string
description: URL pointing to agreement text
staff_editable:
type: boolean
description:
set True if consenting to enable account editing by staff
include_in_reports:
type: boolean
description:
set True if consenting to share data in reports
send_reminders:
type: boolean
description:
set True if consenting to receive reminders when
assessments are due
roles:
type: array
items:
type: object
required:
- name
properties:
name:
type: string
description:
Role name, always a lower case string
with no white space.
description:
type: string
description: Plain text describing the role.
produces:
- application/json
responses:
200:
description:
"Returns {user_id: id}"
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to view requested user_id
security:
- ServiceToken: []
- OAuth2AuthzFlow: []
"""
acting_user = current_user()
if acting_user.has_role(ROLE.ADMIN.value, ROLE.SERVICE.value):
adequate_perms = True
else:
adequate_perms = False
error = ('without organizations, consents and roles, subsequent '
'calls on this user object will fail with a 401')
if not request.json:
abort(400, error)
if not all(required in request.json for required in (
'organizations', 'consents', 'roles')):
abort(400, error)
user = User()
db.session.add(user)
if request.json and 'organizations' in request.json:
try:
org_list = [Organization.query.filter_by(
id=org['organization_id']).one()
for org in request.json['organizations']]
user.update_orgs(org_list, acting_user=acting_user,
excuse_top_check=True)
if org_list:
user.timezone = org_list[0].timezone
except NoResultFound:
abort(
400,
"Organization in {} not found, check "
"/api/organization for existence.".format(
request.json['organizations']))
if request.json and 'consents' in request.json:
try:
consent_list = []
for consent in request.json['consents']:
if 'user_id' not in consent:
consent['user_id'] = user.id
elif consent['user_id'] != user.id:
raise ValueError("consent user_id differs from path")
if 'research_study_id' not in consent:
consent['research_study_id'] = 0
consent_list.append(UserConsent.from_json(consent))
user.update_consents(consent_list, acting_user=acting_user)
except ValueError as e:
abort(400, "ill formed consents:".format(e))
if request.json and 'roles' in request.json:
try:
role_list = [Role.query.filter_by(name=role.get('name')).one()
for role in request.json.get('roles')]
user.update_roles(role_list, acting_user=current_user())
except NoResultFound:
abort(400, "one or more roles ill defined "
"{}".format(request.json.get('roles')))
db.session.commit()
auditable_event(
"new account generated for {} <{}>".format(user, user._email),
user_id=current_user().id, subject_id=user.id,
context='account')
if not adequate_perms:
# Make sure acting user has permission to edit the newly
# created user, or generate a 400 and purge the user.
try:
acting_user.check_role('edit', other_id=user.id)
except Unauthorized:
permanently_delete_user(
username=user.username, user_id=user.id,
acting_user=acting_user)
abort(400, "Inaccessible user created - review consent and roles")
# Force a renewal of the visit / qb_status cache so the new user has
# accurate info. Pad by a second to get around microsecond floor problems
now = datetime.utcnow() + relativedelta(seconds=1)
QB_StatusCacheKey().update(now)
return jsonify(user_id=user.id)
@user_api.route('/user/<int:user_id>', methods=('DELETE',))
@crossdomain()
@roles_required([ROLE.ADMIN.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def delete_user(user_id):
"""Delete the named user from the system
Mark the given user as deleted. The user isn't actually deleted,
but marked as such to maintain the audit trail. After deletion,
all other operations on said user are prohibited.
---
tags:
- User
operationId: delete_user
parameters:
- name: user_id
in: path
description: TrueNTH user ID to delete
required: true
type: integer
format: int64
produces:
- application/json
responses:
200:
description: successful operation
schema:
id: response_deleted
required:
- message
properties:
message:
type: string
description: Result, typically "deleted"
400:
description:
Invalid requests, such as deleting a user owning client applications.
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to edit requested user_id
404:
description: if the user isn't found
security:
- ServiceToken: []
- OAuth2AuthzFlow: []
"""
user = get_user(user_id, 'edit')
try:
user.delete_user(acting_user=current_user())
except ValueError as v:
return jsonify(message=str(v))
return jsonify(message="deleted")
@user_api.route('/user/<int:user_id>/reactivate', methods=('POST',))
@crossdomain()
@roles_required([ROLE.ADMIN.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def reactivate_user(user_id):
"""Reactivate a previously deleted user
Reactivate a previously deleted user - brings the account back to
valid status.
---
tags:
- User
operationId: reactivate_user
parameters:
- name: user_id
in: path
description: TrueNTH user ID to reactivate
required: true
type: integer
format: int64
produces:
- application/json
responses:
200:
description: successful operation
schema:
id: response_reactivated
required:
- message
properties:
message:
type: string
description: Result, typically "reactivated"
400:
description:
Invalid requests, such as reactivating a user that wasn't in a
deleted state.
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to edit requested user_id
404:
description: if the user isn't found
security:
- ServiceToken: []
- OAuth2AuthzFlow: []
"""
user = get_user(user_id, permission='edit', include_deleted=True)
try:
user.reactivate_user(acting_user=current_user())
except ValueError as v:
response = jsonify(message="{}".format(v))
response.status_code = 400
return response
return jsonify(message="reactivated")
@user_api.route('/user/<int:user_id>/access_url')
@crossdomain()
@oauth.require_oauth() # for service token access, oauth must come first
@roles_required(
[ROLE.APPLICATION_DEVELOPER.value, ROLE.ADMIN.value, ROLE.SERVICE.value,
ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
def access_url(user_id):
"""Returns simple JSON with one-time, unique access URL for given user
Generates a single use access token for the given user as a
one click, weak authentication access to the system.
NB - user must be a member of the WRITE_ONLY role or ACCESS_ON_VERIFY,
and not a member of privileged roles, as a safeguard from abuse.
---
tags:
- User
operationId: access_url
parameters:
- name: user_id
in: path
description: TrueNTH user ID to grant access via unique URL
required: true
type: integer
format: int64
produces:
- application/json
responses:
200:
description: successful operation
schema:
id: response_unique_URL
required:
- access_url
properties:
access_url:
type: string
description: The unique URL providing one time access
400:
description:
if the user has too many privileges for weak authentication
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to view requested user_id
404:
description: if the user isn't found
security:
- ServiceToken: []
- OAuth2AuthzFlow: []
"""
user = get_user(user_id, permission='edit')
not_allowed = {
ROLE.ADMIN.value,
ROLE.APPLICATION_DEVELOPER.value,
ROLE.SERVICE.value}
has = {role.name for role in user.roles}
if not has.isdisjoint(not_allowed):
abort(400, "Access URL not provided for privileged accounts")
if {ROLE.ACCESS_ON_VERIFY.value, ROLE.WRITE_ONLY.value}.isdisjoint(has):
# KEEP this restriction. Weak authentication (which the
# returned URL provides) should only be available for these roles
abort(
400,
"Access URL restricted to ACCESS_ON_VERIFY or WRITE_ONLY roles")
# generate URL token
token = url_token(user_id)
url = url_for(
'portal.access_via_token', token=token, _external=True)
auditable_event("generated URL token {}".format(token),
user_id=current_user().id, subject_id=user.id,
context='authentication')
return jsonify(access_url=url)
@user_api.route('/user/<int:user_id>/consent')
@crossdomain()
@oauth.require_oauth()
def user_consents(user_id):
"""Returns simple JSON listing user's valid consent agreements
Returns the list of consent agreements between the requested user
and the respective organizations. Consents are ordered by
``acceptance_date``, most recent first.
NB does include deleted and expired consents. Deleted consents will
include audit details regarding the deletion. The expires timestamp in UTC
is also returned for all consents.
Consents include a number of options, each of which will only be in the
returned JSON if defined.
---
tags:
- User
- Consent
- Organization
operationId: user_consents
parameters:
- name: user_id
in: path
description: TrueNTH user ID
required: true
type: integer
format: int64
produces:
- application/json
responses:
200:
description:
Returns the list of consent agreements for the requested user.
schema:
id: consents
properties:
consent_agreements:
type: array
items:
type: object
required:
- user_id
- organization_id
- acceptance_date
- recorded
- expires
- agreement_url
- research_study_id
properties:
user_id:
type: string
description:
User identifier defining with whom the consent agreement
applies
organization_id:
type: string
description:
Organization identifier defining with whom the consent
agreement applies
acceptance_date:
type: string
format: date-time
description:
Original UTC date-time from the moment the agreement was
signed or put in place by some other workflow
recorded:
$ref: "#/definitions/audits"
expires:
type: string
format: date-time
description:
UTC date-time for when the agreement expires, typically 5
years from the original signing date
agreement_url:
type: string
description: URL pointing to agreement text
staff_editable:
type: boolean
description:
True if consenting to enable account editing by staff
include_in_reports:
type: boolean
description:
True if consenting to share data in reports
send_reminders:
type: boolean
description:
True if consenting to receive reminders when
assessments are due
research_study_id:
type: string
description:
Research Study identifier to which the consent
agreement applies
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to view requested user_id
security:
- ServiceToken: []
"""
user = get_user(user_id, 'view')
return jsonify(consent_agreements=[c.as_json() for c in
user.all_consents])
@user_api.route('/user/<int:user_id>/consent', methods=('POST',))
@crossdomain()
@oauth.require_oauth()
def set_user_consents(user_id):
"""Add a consent agreement for the user with named organization
Used to add a consent agreements between a user and an organization.
Assumed to have just been agreed to. Include 'expires' if
necessary, defaults to now and five years from now (both in UTC).
NB only one valid consent should be in place between a user and an
organization per research study. Therefore, if this POST would create
a second consent on the given (user, organization, research study), the
existing consent will be marked deleted.
Research Studies were added since the initial implementation of this API.
Therefore, exclusion of a ``research_study_id`` will implicitly use a value
of 0 (zero) as the research_study_id.
---
tags:
- User
- Consent
- Organization
operationId: post_user_consent
produces:
- application/json
parameters:
- name: user_id
in: path
description: TrueNTH user ID
required: true
type: integer
format: int64
- in: body
name: body
schema:
id: post_consent_agreement
required:
- organization_id
- agreement_url
properties:
organization_id:
type: integer
format: int64
description:
Organization identifier defining with whom the consent
agreement applies
acceptance_date:
type: string
format: date-time
description:
optional UTC date-time for when the agreement is initially
valid, defaults to utcnow. Dates in the future are not valid
expires:
type: string
format: date-time
description:
optional UTC date-time for when the agreement expires,
defaults to utcnow plus 5 years
agreement_url:
type: string
description: URL pointing to agreement text
staff_editable:
type: boolean
description:
set True if consenting to enable account editing by staff
include_in_reports:
type: boolean
description:
set True if consenting to share data in reports
send_reminders:
type: boolean
description:
set True if consenting to receive reminders when
assessments are due
research_study_id:
type: integer
format: int64
description:
Research Study identifier defining which research study the
consent agreement applies to. Include to override the default
value of 0 (zero).
responses:
200:
description: successful operation
schema:
id: response_ok
required:
- message
properties:
message:
type: string
description: Result, typically "ok"
400:
description: if the request includes invalid data
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to edit requested user_id
404:
description: if user_id doesn't exist
security:
- ServiceToken: []
"""
current_app.logger.debug('post user consent called w/: {}'.format(
request.json))
user = get_user(user_id, 'edit')
if not request.json:
abort(400, "Requires JSON with submission including "
"HEADER 'Content-Type: application/json'")
if ('acceptance_date' in request.json
and FHIR_datetime.parse(request.json['acceptance_date'])
> (relativedelta(minutes=90) + datetime.utcnow())):
abort(400, "Future `acceptance_date` not permitted")
request.json['user_id'] = user_id
try:
consent = UserConsent.from_json(request.json)
if 'research_study_id' not in request.json:
consent.research_study_id = 0
consent_list = [consent, ]
user.update_consents(
consent_list=consent_list, acting_user=current_user())
# Moving consent dates potentially invalidates
# (questionnaire_response: visit_name) associations.
cache.delete_memoized(trigger_date)
QuestionnaireResponse.purge_qb_relationship(
subject_id=user.id,
research_study_id=consent.research_study_id,
acting_user_id=current_user().id)
# The updated consent may have altered the cached assessment
# status - invalidate this user's data at this time.
invalidate_users_QBT(
user_id=user.id, research_study_id=consent.research_study_id)
except ValueError as e:
abort(400, str(e))
return jsonify(message="ok")
@user_api.route('/user/<int:user_id>/consent/withdraw',
methods=('POST', 'PUT'))
@crossdomain()
@oauth.require_oauth()
def withdraw_user_consent(user_id):
"""Withdraw existing consent agreement for the user with named organization
Used to withdraw a consent agreements between a user and an organization.
If a consent exists for the given user/org, the consent will be marked
deleted, and a matching consent (with new status/option values) will be
created in its place. If the user was already withdrawn, a new row will
be created also with status `suspended`, the prior will retain its
`suspended` status and marked deleted.
NB Invalid to request a withdrawal date prior to current consent.
---
tags:
- User
- Consent
- Organization
operationId: withdraw_user_consent
produces:
- application/json
parameters:
- name: user_id
in: path
description: TrueNTH user ID
required: true
type: integer
format: int64
- in: body
name: body
schema:
id: withdraw_consent_agreement
required:
- organization_id
properties:
acceptance_date:
type: string
format: date-time
description:
optional UTC date-time for when the withdrawal occurred if
other than the defaults of utcnow.
Dates in the future are not valid
organization_id:
type: integer
format: int64
description:
Organization identifier defining with whom the consent
agreement applies
research_study_id:
type: integer
format: int64
description:
Research Study identifier defining which research study the
consent agreement applies to. Include to override the default
value of 0 (zero).
responses:
200:
description: successful operation
schema:
id: response_ok
required:
- message
properties:
message:
type: string
description: Result, typically "ok"
400:
description: if the request includes invalid data
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to edit requested user_id
404:
description:
if user_id doesn't exist, or it no consent found
for given user org combination
security:
- ServiceToken: []
"""
current_app.logger.debug('withdraw user consent called w/: '
'{}'.format(request.json))
user = get_user(user_id, permission='edit')
if not request.json:
abort(400, "Requires JSON with submission including "
"HEADER 'Content-Type: application/json'")
org_id = request.json.get('organization_id')
if not org_id:
abort(400, "missing required organization ID")
research_study_id = int(request.json.get('research_study_id', 0))
acceptance_date = None
if 'acceptance_date' in request.json:
acceptance_date = FHIR_datetime.parse(request.json['acceptance_date'])
if acceptance_date > datetime.utcnow():
abort(400, "Future `acceptance_date` not permitted")
current_app.logger.debug('withdraw user consent called for user {} '
'and org {}'.format(user.id, org_id))
return withdraw_consent(
user=user, org_id=org_id, acceptance_date=acceptance_date,
acting_user=current_user(), research_study_id=research_study_id)
def withdraw_consent(
user, org_id, acceptance_date, acting_user, research_study_id):
"""execute consent withdrawal - view and test friendly function"""
uc = UserConsent.query.filter_by(
user_id=user.id, organization_id=org_id, status='consented',
research_study_id=research_study_id).first()
try:
if not uc:
# Possible replacement of existing withdrawal
wc = UserConsent.query.filter_by(
user_id=user.id, organization_id=org_id, status='suspended',
research_study_id=research_study_id).first()
if not wc:
abort(
404,
"no UserConsent found for user ID {}, org ID {}, research study "
"ID {}".format(user.id, org_id, research_study_id))
# replace with requested time, provided it's in a valid window
prior_consent, prior_withdrawal = consent_withdrawal_dates(user, research_study_id)
if prior_withdrawal and acceptance_date == prior_withdrawal:
# valid nop, leave.
return jsonify(wc.as_json())
if prior_consent and acceptance_date < prior_consent:
raise ValueError(
f"Can't suspend with acceptance date {acceptance_date} "
f"prior to last valid consent {prior_consent}")
if acceptance_date > datetime.utcnow() + timedelta(days=1):
raise ValueError(
"Can't suspend with acceptance date in the future")
prior_withdrawal_date = wc.acceptance_date
wc.acceptance_date = acceptance_date
db.session.commit()
# Audit the change
auditable_event(
f"Consent agreement {wc.id} updated from {prior_withdrawal_date} "
f"to {acceptance_date}",
user_id=current_user().id,
subject_id=user.id,
context="consent"
)
# As withdrawal time just changed, force recalculation
invalidate_users_QBT(
user_id=user.id, research_study_id=research_study_id)
return jsonify(wc.as_json())
if not acceptance_date:
acceptance_date = datetime.utcnow()
if acceptance_date <= uc.acceptance_date:
raise ValueError(
"Can't suspend with acceptance date prior to existing consent")
suspended = UserConsent(
user_id=user.id, organization_id=org_id, status='suspended',
acceptance_date=acceptance_date, agreement_url=uc.agreement_url,
research_study_id=research_study_id)
suspended.send_reminders = False
suspended.include_in_reports = True
suspended.staff_editable = (not current_app.config.get('GIL'))
user.update_consents(
consent_list=[suspended], acting_user=acting_user)
# NB - we do NOT call QuestionnaireResponse.purge_qb_relationship()
# in this case, as the user is withdrawing, not altering initial
# consent dates. Doing so does alter the QB_timeline from point of
# withdrawal forward, so force QB_timeline renewal
invalidate_users_QBT(
user_id=user.id, research_study_id=research_study_id)
except ValueError as e:
abort(400, str(e))
return jsonify(suspended.as_json())
@user_api.route('/user/<int:user_id>/consent', methods=('DELETE',))
@crossdomain()
@oauth.require_oauth()
def delete_user_consents(user_id):
"""Delete a consent agreement between the user and the named organization
Used to delete consent agreements between a user and an organization.
---
tags:
- User
- Consent
- Organization
operationId: delete_user_consent
produces:
- application/json
parameters:
- name: user_id
in: path
description: TrueNTH user ID
required: true
type: integer
format: int64
- in: body
name: body
schema:
id: consent_agreement
required:
- organization_id
properties:
organization_id:
type: integer
format: int64
description:
Organization identifier defining with whom the consent
agreement applies
research_study_id:
type: integer
format: int64
description:
Research Study identifier defining which research study the
consent agreement applies to. Include to override the default
value of 0 (zero).
responses:
200:
description: successful operation
schema:
id: response_ok
required:
- message
properties:
message:
type: string
description: Result, typically "ok"
400:
description: if the request includes invalid data
401:
description:
if missing valid OAuth token or if the authorized user lacks
permission to edit requested user_id