-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuser.py
1859 lines (1548 loc) · 71 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 model """
from __future__ import unicode_literals # isort:skip
from future import standard_library # isort:skip
standard_library.install_aliases() # noqa: E402
from cgi import escape
from datetime import datetime, timedelta
from io import StringIO
import time
from dateutil import parser
from flask import abort, current_app
from flask_babel import gettext as _
from flask_login import current_user as flask_login_current_user
from flask_user import UserMixin, _call_or_get
from fuzzywuzzy import fuzz
from past.builtins import basestring
import regex
from sqlalchemy import UniqueConstraint, and_, or_, text
from sqlalchemy.dialects.postgresql import ENUM
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import ColumnProperty, class_mapper, synonym
from werkzeug.exceptions import BadRequest, Forbidden, NotFound
from . import reference
from ..database import db
from ..date_tools import FHIR_datetime, as_fhir
from ..dict_tools import dict_match, strip_empties
from ..system_uri import (
IETF_LANGUAGE_TAG,
TRUENTH_EXTENSTION_NHHD_291036,
TRUENTH_EXTERNAL_STUDY_SYSTEM,
TRUENTH_ID,
TRUENTH_PROVIDER_SYSTEMS,
TRUENTH_USERNAME,
)
from .audit import Audit
from .codeable_concept import CodeableConcept
from .coding import Coding
from .encounter import Encounter
from .extension import CCExtension, TimezoneExtension
from .fhir import (
Observation,
UserObservation,
ValueQuantity,
v_or_first,
v_or_n,
)
from .identifier import Identifier
from .intervention import UserIntervention
from .organization import Organization, OrgTree
from .performer import Performer
from .practitioner import Practitioner
from .relationship import RELATIONSHIP, Relationship
from .role import ROLE, Role
from .telecom import ContactPoint, Telecom
INVITE_PREFIX = "__invite__"
NO_EMAIL_PREFIX = "__no_email__"
DELETED_PREFIX = "__deleted_{time}__"
DELETED_REGEX = r"__deleted_\d+__(.*)"
# https://www.hl7.org/fhir/valueset-administrative-gender.html
gender_types = ENUM('male', 'female', 'other', 'unknown', name='genders',
create_type=False)
internal_identifier_systems = (
TRUENTH_ID, TRUENTH_USERNAME) + TRUENTH_PROVIDER_SYSTEMS
class UserIndigenousStatusExtension(CCExtension):
# Used in place of us-core-race and us-core-ethnicity for
# Australian configurations.
def __init__(self, user, extension):
self.user, self.extension = user, extension
extension_url = TRUENTH_EXTENSTION_NHHD_291036
@property
def children(self):
return self.user.indigenous
class UserEthnicityExtension(CCExtension):
def __init__(self, user, extension):
self.user, self.extension = user, extension
extension_url =\
"http://hl7.org/fhir/StructureDefinition/us-core-ethnicity"
@property
def children(self):
return self.user.ethnicities
class UserRaceExtension(CCExtension):
def __init__(self, user, extension):
self.user, self.extension = user, extension
extension_url =\
"http://hl7.org/fhir/StructureDefinition/us-core-race"
@property
def children(self):
return self.user.races
def permanently_delete_user(
username,
user_id=None,
acting_user=None,
actor=None):
"""Given a username (email), purge the user from the system
Includes wiping out audit rows, observations, etc.
May pass either username or user_id. Will prompt for acting_user if not
provided.
:param username: username (email) for user to purge
:param user_id: id of user in liew of username
:param acting_user: user taking the action, for record keeping
"""
from .tou import ToU
if not acting_user:
acting_user = User.query.filter_by(username=actor).first()
if not acting_user:
raise ValueError("Acting user not found -- can't continue")
if not username:
if not user_id:
raise ValueError("Must provide username or user_id")
else:
user = User.query.get(user_id)
else:
user = User.query.filter_by(username=username).first()
if user_id and user.id != user_id:
raise ValueError(
"Contridicting username and user_id values given")
def purge_user(user, acting_user):
if not user:
raise ValueError("No such user: {}".format(username))
if acting_user.id == user.id:
raise ValueError(
"Actor must be a current user other than the target")
comment = "purged all trace of {}".format(user) # while format works
# purge all the types with user foreign keys, then the user itself
UserRelationship.query.filter(
or_(UserRelationship.user_id == user.id,
UserRelationship.other_user_id == user.id)).delete()
tous = ToU.query.join(Audit).filter(Audit.subject_id == user.id)
for t in tous:
db.session.delete(t)
# the rest should die on cascade rules
db.session.delete(user)
db.session.commit()
# record this event
db.session.add(
Audit(user_id=acting_user.id, comment=comment,
subject_id=acting_user.id, context='account'))
db.session.commit()
purge_user(user, acting_user)
user_extension_classes = (UserEthnicityExtension, UserRaceExtension,
TimezoneExtension, UserIndigenousStatusExtension)
def user_extension_map(user, extension):
"""Map the given extension to the User
FHIR uses extensions for elements beyond base set defined. Lookup
an adapter to handle the given extension for the user.
:param user: the user to apply to or read the extension from
:param extension: a dictionary with at least a 'url' key defining
the extension. Should include a 'valueCodeableConcept' structure
when being used in an apply context (i.e. direct FHIR data)
:returns: adapter implementing apply_fhir and as_fhir methods
:raises :py:exc:`exceptions.ValueError`: if the extension isn't recognized
"""
for kls in user_extension_classes:
if extension['url'] == kls.extension_url:
return kls(user, extension)
# still here implies an extension we don't know how to handle
raise ValueError("unknown extension: {}".format(extension.url))
def default_email(context=None):
"""Function to provide a unique, default email if none is provided
:param context: is populated by SQLAlchemy - see Context-Sensitive default
functions in http://docs.sqlalchemy.org/en/latest/core/defaults.html
:return: a unique email string to avoid unique constraints, if an email
isn't provided in the context
"""
value = None
if context:
value = context.current_parameters.get('email')
if not value or value == NO_EMAIL_PREFIX:
value = NO_EMAIL_PREFIX + str(time.time())
return value
def validate_email(email):
"""Not done at model level, as there are exceptions
We allow for placeholders and masks on email, so not all emails are valid.
This validation function is generally only used when an end user changing
an address or another use requires validation.
Furthermore, due to the complexity of valid email addresses, just
look for some obvious signs - such as the '@' symbol and at least 6 chars.
:raises :py:exc:`werkzeug.exceptions.BadRequest`: if obviously invalid
"""
if not email or '@' not in email or len(email) < 6:
raise BadRequest("requires a valid email address")
LOCKOUT_PERIOD = timedelta(minutes=30)
PERMITTED_FAILED_LOGIN_ATTEMPTS = 5
class User(db.Model, UserMixin):
# PLEASE maintain merge_with() as user model changes #
__tablename__ = 'users' # Override default 'user'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(64))
last_name = db.Column(db.String(64))
registered = db.Column(db.DateTime, default=datetime.utcnow)
_email = db.Column(
'email', db.String(120), unique=True, nullable=False,
default=default_email)
phone_id = db.Column(db.Integer, db.ForeignKey('contact_points.id',
ondelete='cascade'))
alt_phone_id = db.Column(db.Integer, db.ForeignKey('contact_points.id',
ondelete='cascade'))
gender = db.Column('gender', gender_types)
birthdate = db.Column(db.Date)
image_url = db.Column(db.Text)
active = db.Column(
'is_active', db.Boolean(), nullable=False, server_default='1')
locale_id = db.Column(db.ForeignKey('codeable_concepts.id'))
timezone = db.Column(db.String(20), default='UTC')
deleted_id = db.Column(
db.ForeignKey('audit.id', use_alter=True,
name='user_deleted_audit_id_fk'), nullable=True)
deceased_id = db.Column(
db.ForeignKey('audit.id', use_alter=True,
name='user_deceased_audit_id_fk'), nullable=True)
practitioner_id = db.Column(db.ForeignKey('practitioners.id'))
# We use email like many traditional systems use username.
# Create a synonym to simplify integration with other libraries (i.e.
# flask-user). Effectively makes the attribute email avail as username
username = synonym('email')
# Only used for local accounts
password = db.Column(db.String(255))
reset_password_token = db.Column(db.String(100))
confirmed_at = db.Column(db.DateTime())
password_verification_failures = \
db.Column(db.Integer, default=0, nullable=False)
last_password_verification_failure = db.Column(db.DateTime, nullable=True)
user_audits = db.relationship('Audit', cascade='delete',
foreign_keys=[Audit.user_id])
subject_audits = db.relationship('Audit', cascade='delete',
foreign_keys=[Audit.subject_id])
auth_providers = db.relationship('AuthProvider', lazy='dynamic',
cascade='delete')
_consents = db.relationship(
'UserConsent', lazy='dynamic', cascade='delete',
order_by="desc(UserConsent.acceptance_date)")
indigenous = db.relationship(Coding, lazy='dynamic',
secondary="user_indigenous")
encounters = db.relationship('Encounter', cascade='delete')
ethnicities = db.relationship(Coding, lazy='dynamic',
secondary="user_ethnicities")
groups = db.relationship('Group', secondary='user_groups',
backref=db.backref('users', lazy='dynamic'))
interventions = db.relationship(
'Intervention',
lazy='dynamic',
secondary="user_interventions",
backref=db.backref('users'))
questionnaire_responses = db.relationship('QuestionnaireResponse',
lazy='dynamic', cascade='delete')
races = db.relationship(Coding, lazy='dynamic',
secondary="user_races")
observations = db.relationship(
'Observation',
lazy='dynamic',
secondary="user_observations",
backref=db.backref('users'))
organizations = db.relationship(
'Organization',
lazy='dynamic',
secondary="user_organizations",
backref=db.backref('users'))
procedures = db.relationship('Procedure', lazy='dynamic',
backref=db.backref('user'), cascade='delete')
roles = db.relationship('Role', secondary='user_roles',
backref=db.backref('users', lazy='dynamic'))
_locale = db.relationship(CodeableConcept, cascade="save-update")
deleted = db.relationship('Audit', cascade="save-update",
foreign_keys=[deleted_id])
deceased = db.relationship('Audit', cascade="save-update",
foreign_keys=[deceased_id])
documents = db.relationship('UserDocument', lazy='dynamic',
cascade='save-update, delete')
_identifiers = db.relationship(
'Identifier', lazy='dynamic', secondary='user_identifiers')
_phone = db.relationship('ContactPoint', foreign_keys=phone_id,
cascade="save-update, delete")
_alt_phone = db.relationship('ContactPoint', foreign_keys=alt_phone_id,
cascade="save-update, delete")
notifications = db.relationship(
'Notification', secondary='user_notifications',
backref=db.backref('users', lazy='dynamic'))
###
# PLEASE maintain merge_with() as user model changes #
###
assessment_status = 'undetermined'
def __str__(self):
"""Print friendly format for logging, etc."""
return "user {0.id}".format(self)
def __setattr__(self, name, value):
"""Make sure deleted users aren't being updated"""
if not name.startswith('_'):
if getattr(self, 'deleted'):
raise ValueError("can not update {} on deleted {}".format(
name, self))
return super(User, self).__setattr__(name, value)
def is_registered(self):
"""Returns True if user has completed registration
Not to be confused with the ``registered`` column (which captures
the moment when the account was created), ``is_registered`` returns
true once the user has blessed their account with login credentials,
such as a password or auth_provider access.
Roles are considered in this check - special roles such as
``access_on_verify`` and ``write_only`` should never exist on
registered users, and therefore this method will return False
for any users with these roles.
"""
non_registered_roles = set(current_app.config['PRE_REGISTERED_ROLES'])
current_roles = {r.name for r in self.roles}
disjoint = current_roles.isdisjoint(non_registered_roles)
if self.password or self.auth_providers.count():
# Looks registered, confirm non-registered roles aren't present
if disjoint:
return True
else:
raise RuntimeError(
"Registered user {} has a restricted role from {}".format(
self, non_registered_roles))
# Still here implies not yet registered, enforce role presence
if not disjoint:
return False
else:
raise RuntimeError(
"Non registered user {} lacking special role".format(self))
@property
def all_consents(self):
"""Access to all consents including deleted and expired"""
return self._consents
@property
def valid_consents(self):
"""Access to consents that have neither been deleted or expired"""
now = datetime.utcnow()
return self._consents.filter(
text("expires>:now and deleted_id is null")).params(now=now)
@property
def display_name(self):
if self.first_name and self.last_name:
name = ' '.join((self.first_name, self.last_name))
else:
name = self.username
return escape(name) if name else None
@property
def current_encounter(self):
"""Shortcut to current encounter, if present
An encounter is typically bound to the logged in user, not
the subject, if a different user is performing the action.
"""
query = Encounter.query.filter(Encounter.user_id == self.id).filter(
Encounter.status == 'in-progress')
if query.count() == 0:
return None
if query.count() != 1:
# Not good - we should only have one `active` encounter for
# the current user. Log details for debugging and return the
# first
msg = "Multiple active encounters found for {}: {}".format(
self,
[(e.status, str(e.start_time), str(e.end_time))
for e in query])
current_app.logger.error(msg)
return query.first()
@property
def locale(self):
if self._locale and self._locale.codings and (
len(self._locale.codings) > 0):
return self._locale.codings[0]
return None
@property
def locale_code(self):
if self.locale:
return self.locale.code
return None
@property
def locale_name(self):
if self.locale:
return self.locale.display
return None
@locale.setter
def locale(self, lang_info):
# lang_info is a tuple of format (language_code,language_name)
# IETF BCP 47 standard uses hyphens, but we instead store w/
# underscores, to better integrate with babel/LR URLs/etc
data = {"coding": [{'code': lang_info[0], 'display': lang_info[1],
'system': IETF_LANGUAGE_TAG}]}
self._locale = CodeableConcept.from_fhir(data)
@hybrid_property
def email(self):
# Called in different contexts - only compare string
# value if it's a base string type, as opposed to when
# its being used in a query statement (email.ilike('foo'))
if isinstance(self._email, basestring):
if self._email.startswith(INVITE_PREFIX):
# strip the invite prefix for UI
return self._email[len(INVITE_PREFIX):]
if self._email.startswith(NO_EMAIL_PREFIX):
# return None as we don't have an email
return None
if self._email.startswith(DELETED_PREFIX[:10]):
match = regex.match(DELETED_REGEX, self._email)
if not match:
raise ValueError(
"Apparently deleted user's email doesn't fit "
"expected pattern {}".format(self))
return match.groups()[0]
return self._email
@email.setter
def email(self, email):
if email == NO_EMAIL_PREFIX:
self._email = default_email()
elif self._email and self._email.startswith(
NO_EMAIL_PREFIX) and not email:
# already a unique email, for a user w/o email, don't
# set to an empty string if they didn't give a value.
pass
else:
self._email = email
assert(self._email and len(self._email))
def email_ready(self):
"""Returns (True, None) IFF user has valid email and necessary criteria
As user's frequently forget their passwords or start in a state without
a valid email address, the system should NOT email invites or reminders
unless adequate data is on file for the user to perform a reset password
loop.
NB exceptions exist for systems with the NO_CHALLENGE_WO_DATA
configuration set, as those systems allow for change of password without
the verification step, if the user doesn't have a required field set.
:returns: (Success, Failure message), such as (True, None) if the user
account is "email_ready" or (False, _"invalid email") if the reason
for failure is a lack of valid email address.
"""
try:
validate_email(self.email)
except BadRequest:
valid_email = False
else:
valid_email = True
if self._email.startswith(NO_EMAIL_PREFIX) or not valid_email:
return False, _("invalid email address")
if current_app.config.get('NO_CHALLENGE_WO_DATA', False):
# Grandfather in systems that didn't capture all challenge fields
if valid_email:
return True, None
return False, _("invalid email address")
else:
# Otherwise, require all challenge fields are defined, so an emailed
# user could finish a process such as reset password, if needed.
if all((self.birthdate, self.first_name, self.last_name)):
return True, None
else:
msg = _("missing required data: ")
missing = []
for attr in 'birthdate', 'first_name', 'last_name':
if not getattr(self, attr):
missing.append(_(attr))
return False, "{} {}".format(msg, ','.join(missing))
@property
def phone(self):
if self._phone:
return self._phone.value
@phone.setter
def phone(self, val):
if self._phone:
if val:
self._phone.value = val
else:
self._phone = None
elif val:
self._phone = ContactPoint(
system='phone', use='mobile', value=val)
@property
def alt_phone(self):
if self._alt_phone:
return self._alt_phone.value
@alt_phone.setter
def alt_phone(self, val):
if self._alt_phone:
if val:
self._alt_phone.value = val
else:
self._alt_phone = None
elif val:
self._alt_phone = ContactPoint(
system='phone', use='home', value=val)
def mask_email(self, prefix=INVITE_PREFIX):
"""Mask temporary account email to avoid collision with registered
Temporary user accounts created for the purpose of invites get
in the way of the user creating a registered account. Add a hidden
prefix to the email address in the temporary account to avoid
collision.
"""
# Don't apply the invite mask to a user without email
if prefix == INVITE_PREFIX and self._email.startswith(NO_EMAIL_PREFIX):
return
if self._email:
if not self._email.startswith(prefix):
self._email = prefix + self._email
else:
self._email = prefix
def implicit_identifiers(self):
"""Generate and return the implicit identifiers
The primary key, email and auth providers are all visible in formats
such as demographics, but should never be stored as user_identifiers,
less problems of duplicate, out of sync data arise.
This method generates those on the fly for display purposes.
:returns: list of implicit identifiers
"""
def primary():
return [Identifier(
use='official', system=TRUENTH_ID, value=self.id)]
def secondary():
if self.username:
return [Identifier(
use='secondary', system=TRUENTH_USERNAME, value=self._email)]
return []
def providers():
return [
Identifier.from_fhir(provider.as_fhir())
for provider in self.auth_providers]
return primary() + secondary() + providers()
@property
def identifiers(self):
"""Return list of identifiers
Several identifiers are "implicit", such as the primary key
from the user table, and any auth_providers associated with
this user. These will be prepended to the existing identifiers
but should never be stored, as they're generated from other
fields.
:returns: list of implicit and existing identifiers
"""
return self.implicit_identifiers() + [i for i in self._identifiers]
@property
def external_study_id(self):
"""Return the value of the user's external study identifier(s)
If more than one external study identifiers are found for the user,
values will be joined by ', '
"""
ext_ids = self._identifiers.filter_by(
system=TRUENTH_EXTERNAL_STUDY_SYSTEM)
if ext_ids.count():
return ', '.join([ext_id.value for ext_id in ext_ids])
@property
def org_coding_display_options(self):
"""Collates all race/ethnicity/indigenous display options
from the user's orgs to establish which options to display"""
options = {}
orgs = self.organizations
if orgs:
options['race'] = any(o.race_codings for o in orgs)
options['ethnicity'] = any(o.ethnicity_codings for o in orgs)
options['indigenous'] = any(o.indigenous_codings for o in orgs)
else:
attrs = ('race', 'ethnicity', 'indigenous')
options = dict.fromkeys(attrs, True)
return options
@property
def locale_display_options(self):
"""Collates all the locale options from the user's orgs
to establish which should be visible to the user"""
def locale_name_from_code(locale_code):
coding = Coding.query.filter_by(system=IETF_LANGUAGE_TAG, code=locale_code).first()
return coding.display
locale_options = {}
if self.locale_code:
locale_options[self.locale_code] = self.locale_name
for org in self.organizations:
for locale in org.locales:
locale_options[locale.code] = locale.display
if org.default_locale and org.default_locale not in locale_options:
locale_options[org.default_locale] = locale_name_from_code(org.default_locale)
while org.partOf_id:
org = Organization.query.get(org.partOf_id)
for locale in org.locales:
locale_options[locale.code] = locale.display
if org.default_locale and org.default_locale not in locale_options:
locale_options[org.default_locale] = locale_name_from_code(org.default_locale)
return locale_options
@property
def is_locked_out(self):
"""tells if user is temporarily locked out
To slow down brute force password attacks we temporarily
lock users out of the system for a short period of time.
This property tells whether or not the user is locked out.
"""
if self.password_verification_failures == 0:
return False
# If we're not in the lockout window reset everything
time_since_last_failure = \
datetime.utcnow() - self.last_password_verification_failure
if time_since_last_failure >= LOCKOUT_PERIOD:
self.reset_lockout()
failures = self.password_verification_failures
return failures >= PERMITTED_FAILED_LOGIN_ATTEMPTS
def reset_lockout(self):
"""resets variables that track lockout
We track when the user fails password verification
to lockout users when they fail too many times.
This function resets those variables
"""
self.password_verification_failures = 0
self.last_password_verification_failure = None
db.session.commit()
def add_password_verification_failure(self):
"""remembers when a user fails password verification
Each time a user fails password verification
this function is called. Use user.is_locked_out
to tell whether this has been called enough times
to lock the user out of the system
:returns: total failures since last reset
"""
self.last_password_verification_failure = datetime.utcnow()
self.password_verification_failures += 1
db.session.commit()
return self.password_verification_failures
def add_organization(self, organization_name):
"""Shortcut to add a clinic/organization by name"""
org = Organization.query.filter_by(name=organization_name).one()
if org not in self.organizations:
self.organizations.append(org)
def first_top_organization(self):
"""Return first top level organization for user
NB, none of the above doesn't count and will not be retuned.
A user may have any number of organizations, but most business
decisions, assume there is only one. Arbitrarily returning the
first from the matching query in case of multiple.
:returns: a single top level organization, or None
"""
return OrgTree().find_top_level_orgs(self.organizations, first=True)
def leaf_organizations(self):
"""Return list of 'leaf' organization ids for user's orgs
Users, especially staff, have arbitrary number of organization
associations, at any level of the organization hierarchy. This
method looks up all child leaf nodes from the users existing orgs.
"""
leaves = set()
OT = OrgTree()
if self.organizations:
for org in self.organizations:
if org.id == 0:
continue
leaves.update(OT.all_leaves_below_id(org.id))
return list(leaves)
else:
return None
def add_observation(self, fhir, audit):
if 'coding' not in fhir['code']:
return 400, "requires at least one CodeableConcept"
if 'valueQuantity' not in fhir:
return 400, "missing required 'valueQuantity'"
cc = CodeableConcept.from_fhir(fhir['code']).add_if_not_found()
v = fhir['valueQuantity']
vq = ValueQuantity(value=v.get('value'),
units=v.get('units'),
system=v.get('system'),
code=v.get('code')).add_if_not_found(True)
issued = fhir.get('issued') and\
parser.parse(fhir.get('issued')) or None
status = fhir.get('status')
observation = self.save_observation(cc, vq, audit, status, issued)
if 'performer' in fhir:
for p in fhir['performer']:
performer = Performer.from_fhir(p)
observation.performers.append(performer)
return 200, "added {} to user {}".format(observation, self.id)
def add_relationship(self, other_user, relationship_name):
# confirm it's not already defined
relationship = Relationship.query.filter_by(
name=relationship_name).first()
existing = UserRelationship.query.filter_by(
user_id=self.id,
other_user_id=other_user.id,
relationship_id=relationship.id).first()
if existing:
raise ValueError("requested relationship already defined")
new_relationship = UserRelationship(user_id=self.id,
other_user_id=other_user.id,
relationship_id=relationship.id)
self.relationships.append(new_relationship)
def has_relationship(self, relationship_name, other_user):
relationship = Relationship.query.filter_by(
name=relationship_name).first()
for r in self.relationships:
if (r.relationship_id == relationship.id and
r.other_user_id == other_user.id):
return True
return False
def add_service_account(self):
"""Service account generation.
For automated, authenticated access to protected API endpoints,
a service user can be created and used to generate a long-life
bearer token. The account is a user with the service role,
attached to a sposor account - the (self) individual creating it.
Only a single service account is allowed per user. If one is
found to exist for this user, simply return it.
"""
for rel in self.relationships:
if rel.relationship.name == RELATIONSHIP.SPONSOR.value:
return User.query.get(rel.other_user_id)
service_user = User(username=('service account sponsored by {}'.
format(self.username)))
db.session.add(service_user)
add_role(service_user, ROLE.SERVICE.value)
self.add_relationship(service_user, RELATIONSHIP.SPONSOR.value)
return service_user
def concept_value(self, codeable_concept):
"""Look up logical value for given concept
Returns the most current setting for a given concept, by
interpreting the results of a matching
``fetch_value_status_for_concept()`` call.
NB - as there are states beyond true/false, such as "unknown"
for a given concept, this does NOT return a boolean but a string.
:returns: a string, typically "true", "false" or "unknown"
"""
value_quantity, status = self.fetch_value_status_for_concept(
codeable_concept)
if value_quantity and status != 'unknown':
return value_quantity.value
return 'unknown'
def fetch_value_status_for_concept(self, codeable_concept):
"""Return matching ValueQuantity & status for this user
Given the possibility of multiple matching observations, returns
the most current info available.
See also ``concept_value()``
:returns: (value_quantity, status) tuple for the observation
if found on the user, else (None, None)
"""
# User may not have persisted concept - do so now for match
codeable_concept = codeable_concept.add_if_not_found()
matching_obs = [
obs for obs in self.observations if
obs.codeable_concept_id == codeable_concept.id]
if not matching_obs:
return None, None
if len(matching_obs) > 1:
# Given multiple matches, select the most recent from the set
newest = UserObservation.query.join(Audit).filter(and_(
UserObservation.user_id == self.id,
UserObservation.observation_id.in_(
[o.id for o in matching_obs]),
UserObservation.audit_id == Audit.id)).order_by(
Audit.timestamp.desc()).first()
bestmatch = [o for o in matching_obs if o.id == newest.observation_id][0]
else:
bestmatch = matching_obs[0]
return bestmatch.value_quantity, bestmatch.status
def fetch_datetime_for_concept(self, codeable_concept):
"""Return newest issued timestamp from matching observation"""
codeable_concept = codeable_concept.add_if_not_found()
matching_observations = [
obs for obs in self.observations if
obs.codeable_concept_id == codeable_concept.id and
obs.issued is not None]
if not matching_observations:
return None
newest = max(o.issued for o in matching_observations
if o.issued is not None)
return newest
def save_observation(
self, codeable_concept, value_quantity, audit, status, issued):
"""Helper method for creating new observations"""
# avoid cyclical imports
from .assessment_status import invalidate_assessment_status_cache
# User may not have persisted concept or value - CYA
codeable_concept = codeable_concept.add_if_not_found()
value_quantity = value_quantity.add_if_not_found()
observation = Observation(
codeable_concept_id=codeable_concept.id,
status=status,
issued=issued,
value_quantity_id=value_quantity.id).add_if_not_found(True)
# The audit defines the acting user, to which the current
# encounter is attached.
encounter = get_user(audit.user_id).current_encounter
db.session.add(UserObservation(
user_id=self.id, encounter=encounter, audit=audit,
observation_id=observation.id))
invalidate_assessment_status_cache(self.id)
return observation
def clinical_history(self, requestURL=None):
now = datetime.utcnow()
fhir = {"resourceType": "Bundle",
"title": "Clinical History",
"link": [{"rel": "self", "href": requestURL}, ],
"updated": as_fhir(now),
"entry": []}
for ob in self.observations:
fhir['entry'].append({"title": "Patient Observation",
"updated": as_fhir(now),
"author": [{"name": "Truenth Portal"}, ],
"content": ob.as_fhir()})
return fhir
def procedure_history(self, requestURL=None):
now = datetime.utcnow()
fhir = {"resourceType": "Bundle",
"title": "Procedure History",
"link": [{"rel": "self", "href": requestURL}, ],
"updated": as_fhir(now),
"entry": []}
for proc in self.procedures:
fhir['entry'].append({"resource": proc.as_fhir()})
return fhir
@property
def rolelist(self):
"""Generate UI friendly string of user's roles by name"""
return ', '.join([r.name for r in self.roles])
def as_fhir(self, include_empties=True):
"""Return JSON representation of user
:param include_empties: if True, returns entire object definition;
if False, empty elements are removed from the result
:return: JSON representation of a FHIR Patient resource
"""
def careProviders():
"""build and return list of careProviders (AKA clinics)"""
orgs = []
for o in self.organizations:
orgs.append(reference.Reference.organization(o.id).as_fhir())
return orgs
def deceased():
"""FHIR spec suggests ONE of deceasedBoolean or deceasedDateTime"""
if not self.deceased_id:
return {"deceasedBoolean": False}
# We maintain an audit row from when the user was marked
# as deceased. If "time of death" is in the content, the
# audit timestamp is good - otherwise, return the boolean
audit = self.deceased
if "time of death" in audit.comment:
return {"deceasedDateTime":
FHIR_datetime.as_fhir(audit.timestamp)}