-
Notifications
You must be signed in to change notification settings - Fork 8
/
models.py
3052 lines (2557 loc) · 124 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Application models."""
import copy
import csv
import json
import jsonschema
import os
import random
import re
import secrets
import string
import uuid
from collections import namedtuple
from datetime import datetime
from enum import IntFlag, IntEnum
from hashlib import md5
from io import StringIO
from itertools import groupby, zip_longest
from urllib.parse import urlencode
import validators
import yaml
from flask_login import UserMixin, current_user
from peewee import JOIN, BlobField
from peewee import BooleanField as BooleanField_
from peewee import (CharField, DateTimeField, DeferredRelation, Field, FixedCharField,
ForeignKeyField, IntegerField, Model, OperationalError, PostgresqlDatabase,
SmallIntegerField, TextField, fn)
from peewee_validates import ModelValidator
from playhouse.shortcuts import model_to_dict
from pycountry import countries
from pykwalify.core import Core
from pykwalify.errors import SchemaError
from . import app, db
from .schemas import affiliation_task_schema
ENV = app.config["ENV"]
DEFAULT_COUNTRY = app.config["DEFAULT_COUNTRY"]
SCHEMA_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "schemas"))
ORCID_ID_REGEX = re.compile(r"^([X\d]{4}-?){3}[X\d]{4}$")
PARTIAL_DATE_REGEX = re.compile(r"\d+([/\-]\d+){,2}")
AFFILIATION_TYPES = (
"student",
"education",
"staff",
"employment",
)
class ModelException(Exception):
"""Application model exception."""
pass
class NestedDict(dict):
"""Helper for traversing a nested dictionaries."""
def get(self, *keys, default=None):
"""To get the value from uploaded fields."""
d = self
for k in keys:
if d is default:
break
if not isinstance(d, dict):
return default
d = super(NestedDict, d).get(k, default)
return d
def validate_orcid_id(value):
"""Validate ORCID iD (both format and the check-sum)."""
if not value:
return
if not ORCID_ID_REGEX.match(value):
raise ValueError(
f"Invalid ORCID iD {value}. It should be in the form of 'xxxx-xxxx-xxxx-xxxx' where x is a digit."
)
check = 0
for n in value:
if n == '-':
continue
check = (2 * check + int(10 if n == 'X' else n)) % 11
if check != 1:
raise ValueError(f"Invalid ORCID iD {value} checksum. Make sure you have entered correct ORCID iD.")
def lazy_property(fn):
"""Make a property lazy-evaluated."""
attr_name = '_lazy_' + fn.__name__
@property
def _lazy_property(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazy_property
class PartialDate(namedtuple("PartialDate", ["year", "month", "day"])):
"""Partial date (without month day or both month and month day."""
def as_orcid_dict(self):
"""Return ORCID dictionary representation of the partial date."""
if self.year is None and self.month is None and self.day is None:
return None
return dict(((f, None if v is None else {
"value": ("%04d" if f == "year" else "%02d") % v
}) for (f, v) in zip(self._fields, self)))
@classmethod
def create(cls, value):
"""Create a partial date form ORCID dictionary representation or string.
>>> PartialDate.create({"year": {"value": "2003"}}).as_orcid_dict()
{'year': {'value': '2003'}, 'month': None, 'day': None}
>>> PartialDate.create({"year": {"value": "2003"}}).year
2003
>>> PartialDate.create("2003").year
2003
>>> PartialDate.create("2003-03")
2003-03
>>> PartialDate.create("2003-07-14")
2003-07-14
>>> PartialDate.create("2003/03")
2003-03
>>> PartialDate.create("2003/07/14")
2003-07-14
>>> PartialDate.create("03/2003")
2003-03
>>> PartialDate.create("14/07/2003")
2003-07-14
"""
if value is None or value == {}:
return None
if isinstance(value, str):
match = PARTIAL_DATE_REGEX.search(value)
if not match:
raise ModelException(f"Wrong partial date value '{value}'")
value0 = match[0]
if '/' in value0:
parts = value0.split('/')
return cls(*[int(v) for v in (parts[::-1] if len(parts[-1]) > 2 else parts)])
return cls(*[int(v) for v in value0.split('-')])
return cls(**{k: int(v.get("value")) if v else None for k, v in value.items()})
def as_datetime(self):
"""Get 'datetime' data representation."""
return datetime(self.year, self.month, self.day)
def __str__(self):
"""Get string representation."""
if self.year is None:
return ''
else:
res = "%04d" % int(self.year)
if self.month:
res += "-%02d" % int(self.month)
return res + "-%02d" % int(self.day) if self.day else res
PartialDate.__new__.__defaults__ = (None, ) * len(PartialDate._fields)
class OrcidIdField(FixedCharField):
"""ORCID iD value DB field."""
def __init__(self, *args, **kwargs):
"""Initialize ORCID iD data field."""
if "verbose_name" not in kwargs:
kwargs["verbose_name"] = "ORCID iD"
if "max_length" not in kwargs:
kwargs["max_length"] = 19
super().__init__(*args, **kwargs)
# TODO: figure out where to place the value validation...
# def coerce(self, value):
# validate_orcid_id(value)
# return super().coerce(value)
class BooleanField(BooleanField_):
"""BooleanField extension to support inversion in queries."""
def NOT(self): # noqa: N802
"""Negate logical value in SQL."""
return self.__invert__()
class PartialDateField(Field):
"""Partial date custom DB data field mapped to varchar(10)."""
db_field = "varchar(10)"
def db_value(self, value):
"""Convert into partial ISO date textual representation: YYYY-**-**, YYYY-MM-**, or YYYY-MM-DD."""
if value is None or not value.year:
return None
else:
res = "%04d" % int(value.year)
if value.month:
res += "-%02d" % int(value.month)
else:
return res + "-**-**"
return res + "-%02d" % int(value.day) if value.day else res + "-**"
def python_value(self, value):
"""Parse partial ISO date textual representation."""
if value is None:
return None
parts = [int(p) for p in value.split("-") if "*" not in p]
return PartialDate(**dict(zip_longest((
"year",
"month",
"day",
), parts)))
class Role(IntFlag):
"""
Enum used to represent user role.
The model provide multi role support representing role sets as bitmaps.
"""
NONE = 0 # NONE
SUPERUSER = 1 # SuperUser
ADMIN = 2 # Admin
RESEARCHER = 4 # Researcher
TECHNICAL = 8 # Technical contact
ANY = 255 # ANY
def __eq__(self, other):
if isinstance(other, Role):
return self.value == other.value
return (self.name == other or self.name == getattr(other, 'name', None))
def __hash__(self):
return hash(self.name)
class Affiliation(IntFlag):
"""
Enum used to represent user affiliation (type) to the organisation.
The model provide multiple affiliations support representing role sets as bitmaps.
"""
NONE = 0 # NONE
EDU = 1 # Education
EMP = 2 # Employment
def __eq__(self, other):
if isinstance(other, Affiliation):
return self.value == other.value
return (self.name == other or self.name == getattr(other, 'name', None))
def __hash__(self):
return hash(self.name)
def __str__(self):
return ", ".join({
self.EDU: "Education",
self.EMP: "Employment"
}[a] for a in Affiliation if a & self)
class BaseModel(Model):
"""Encapsulate common bits and pieces of the model classes."""
def field_is_updated(self, field_name):
"""Test if field is 'dirty'."""
return any(field_name == f.name for f in self.dirty_fields)
@classmethod
def get(cls, *query, **kwargs):
"""Get a single model instance."""
if query and not kwargs and len(query) == 1 and isinstance(query[0], (int, str, )):
return super().get(id=query[0])
elif not query and not kwargs:
return super().select().limit(1).first()
return super().get(*query, **kwargs)
@classmethod
def model_class_name(cls):
"""Get the class name of the model."""
return cls._meta.name
def __to_dashes(self, o):
"""Replace '_' with '-' in the dict keys."""
if isinstance(o, dict):
return {k.replace('_', '-'): self.__to_dashes(v) for k, v in o.items()}
return o
def to_dict(self,
to_dashes=False,
exclude_nulls=False,
recurse=True,
backrefs=False,
only=None,
exclude=None,
seen=None,
extra_attrs=None,
fields_from_query=None,
max_depth=None):
"""Get dictionary representation of the model."""
o = model_to_dict(
self,
recurse=recurse,
backrefs=backrefs,
only=only,
exclude=exclude,
seen=seen,
extra_attrs=extra_attrs,
fields_from_query=fields_from_query,
max_depth=max_depth)
if exclude_nulls:
o = {k: v for (k, v) in o.items() if v is not None}
for k, v in o.items():
if isinstance(v, PartialDate):
o[k] = str(v)
elif k == "task_type":
o[k] = TaskType(v).name
if to_dashes:
return self.__to_dashes(o)
return o
def reload(self):
"""Refresh the object from the DB."""
newer_self = self.get(self._meta.primary_key == self._get_pk_value())
for field_name in self._meta.fields.keys():
val = getattr(newer_self, field_name)
setattr(self, field_name, val)
self._dirty.clear()
class Meta: # noqa: D101,D106
database = db
only_save_dirty = True
class ModelDeferredRelation(DeferredRelation):
"""Fixed DefferedRelation to allow inheritance and mixins."""
def set_model(self, rel_model):
"""Include model in the generated "related_name" to make it unique."""
for model, field, name in self.fields:
if isinstance(field, ForeignKeyField) and not field._related_name:
field._related_name = "%s_%s_set" % (model.model_class_name(), name)
super().set_model(rel_model)
DeferredUser = ModelDeferredRelation()
class AuditMixin(Model):
"""Mixing for getting data necessary for data change audit trail maintenance."""
created_at = DateTimeField(default=datetime.utcnow)
updated_at = DateTimeField(null=True, default=None)
# created_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
# updated_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
def save(self, *args, **kwargs): # noqa: D102
if self.is_dirty() and self._dirty != {"orcid_updated_at"}:
self.updated_at = datetime.utcnow()
if current_user and hasattr(current_user, "id"):
if hasattr(self, "created_by") and self.created_by and hasattr(self, "updated_by"):
self.updated_by_id = current_user.id
elif hasattr(self, "created_by"):
self.created_by_id = current_user.id
return super().save(*args, **kwargs)
class File(BaseModel):
"""Uploaded image files."""
filename = CharField(max_length=100)
data = BlobField()
mimetype = CharField(max_length=30, db_column="mime_type")
token = FixedCharField(max_length=8, unique=True, default=lambda: secrets.token_urlsafe(8)[:8])
class Meta: # noqa: D101,D106
table_alias = "f"
class Organisation(BaseModel, AuditMixin):
"""Research organisation."""
country_choices = [(c.alpha_2, c.name) for c in countries]
country_choices.sort(key=lambda e: e[1])
country_choices.insert(0, ("", "Country"))
name = CharField(max_length=100, unique=True, null=True)
tuakiri_name = CharField(max_length=80, unique=True, null=True)
if ENV != "prod":
orcid_client_id = CharField(max_length=80, null=True)
orcid_secret = CharField(max_length=80, null=True)
else: # pragma: no cover
orcid_client_id = CharField(max_length=80, unique=True, null=True)
orcid_secret = CharField(max_length=80, unique=True, null=True)
confirmed = BooleanField(default=False)
city = CharField(null=True)
state = CharField(null=True, verbose_name="State/Region", max_length=100)
country = CharField(null=True, choices=country_choices, default=DEFAULT_COUNTRY)
disambiguated_id = CharField(null=True)
disambiguation_source = CharField(null=True)
is_email_sent = BooleanField(default=False)
tech_contact = ForeignKeyField(
DeferredUser,
related_name="tech_contact_of",
on_delete="SET NULL",
null=True,
help_text="Organisation technical contact")
created_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
updated_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
api_credentials_requested_at = DateTimeField(
null=True,
help_text="The time stamp when the user clicked on the button to register client API.")
api_credentials_entered_at = DateTimeField(
null=True, help_text="The time stamp when the user entered API Client ID and secret.")
can_use_api = BooleanField(null=True, help_text="The organisation can access ORCID Hub API.")
logo = ForeignKeyField(
File, on_delete="CASCADE", null=True, help_text="The logo of the organisation")
email_template = TextField(null=True)
email_template_enabled = BooleanField(null=True, default=False)
webhook_enabled = BooleanField(default=False, null=True)
webhook_url = CharField(max_length=100, null=True)
email_notifications_enabled = BooleanField(default=False, null=True)
notification_email = CharField(max_length=100, null=True, verbose_name="Notification Email Address")
@property
def invitation_sent_at(self):
"""Get the timestamp of the most recent invitation sent to the technical contact."""
row = self.orginvitation_set.select(
fn.MAX(OrgInvitation.created_at).alias("last_sent_at")).where(
OrgInvitation.invitee_id == self.tech_contact_id).first()
if row:
return row.last_sent_at
@property
def invitation_confirmed_at(self):
"""Get the timestamp when the invitation link was opened."""
row = self.orginvitation_set.select(
fn.MAX(OrgInvitation.created_at).alias("last_confirmed_at")).where(
OrgInvitation.invitee_id == self.tech_contact_id).where(
OrgInvitation.confirmed_at.is_null(False)).first()
if row:
return row.last_confirmed_at
@property
def users(self):
"""Get organisation's user query."""
return User.select().join(
UserOrg, on=(UserOrg.user_id == User.id)).where(UserOrg.org == self)
@property
def admins(self):
"""Get organisation's administrator query."""
return self.users.where(UserOrg.is_admin)
def __repr__(self):
return self.name or self.tuakiri_name
def save(self, *args, **kwargs):
"""Handle data consistency validation and saving."""
if self.is_dirty():
if self.name is None:
self.name = self.tuakiri_name
if self.field_is_updated("tech_contact") and self.tech_contact:
if not self.tech_contact.has_role(Role.TECHNICAL):
self.tech_contact.roles |= Role.TECHNICAL
self.tech_contact.save()
app.logger.info(f"Added TECHNICAL role to user {self.tech_contact}")
super().save(*args, **kwargs)
class Meta: # noqa: D101,D106
table_alias = "o"
class OrgInfo(BaseModel):
"""Preloaded organisation data."""
name = CharField(max_length=100, unique=True, verbose_name="Organisation")
tuakiri_name = CharField(max_length=100, unique=True, null=True, verbose_name="TUAKIRI Name")
title = CharField(null=True, verbose_name="Contact Person Tile")
first_name = CharField(null=True, verbose_name="Contact Person's First Name")
last_name = CharField(null=True, verbose_name="Contact Person's Last Name")
role = CharField(null=True, verbose_name="Contact Person's Role")
email = CharField(null=True, verbose_name="Contact Person's Email Address")
phone = CharField(null=True, verbose_name="Contact Person's Phone")
is_public = BooleanField(
null=True, default=False, help_text="Permission to post contact information to WEB")
country = CharField(null=True, verbose_name="Country Code", default=DEFAULT_COUNTRY)
city = CharField(null=True, verbose_name="City of Home Campus")
disambiguated_id = CharField(
null=True, verbose_name="common:disambiguated-organization-identifier")
disambiguation_source = CharField(null=True, verbose_name="common:disambiguation-source")
def __repr__(self):
return self.name or self.disambiguated_id or super().__repr__()
class Meta: # noqa: D101,D106
db_table = "org_info"
table_alias = "oi"
@classmethod
def load_from_csv(cls, source):
"""Load data from CSV file or a string."""
if isinstance(source, str):
source = StringIO(source)
reader = csv.reader(source)
header = next(reader)
assert len(header) >= 3, \
"Wrong number of fields. Expected at least 3 fields " \
"(name, disambiguated organisation ID, and disambiguation source). " \
"Read header: %s" % header
header_rexs = [
re.compile(ex, re.I)
for ex in ("organisation|name", "title", r"first\s*(name)?", r"last\s*(name)?", "role",
"email", "phone", "public|permission to post to web", r"country\s*(code)?",
"city", "(common:)?disambiguated.*identifier",
"(common:)?disambiguation.*source", r"tuakiri\s*(name)?")
]
def index(rex):
"""Return first header column index matching the given regex."""
for i, column in enumerate(header):
if rex.match(column):
return i
else:
return None
idxs = [index(rex) for rex in header_rexs]
def val(row, i, default=None):
if idxs[i] is None:
return default
else:
v = row[idxs[i]].strip()
return None if v == '' else v
for row in reader:
# skip empty lines:
if not row or row is None or len(row) == 0 or (len(row) == 1 and row[0].strip() == ''):
continue
name = val(row, 0)
oi, _ = cls.get_or_create(name=name)
oi.title = val(row, 1)
oi.first_name = val(row, 2)
oi.last_name = val(row, 3)
oi.role = val(row, 4)
oi.email = val(row, 5)
oi.phone = val(row, 6)
oi.is_public = val(row, 7) and val(row, 7).upper() == "YES"
oi.country = val(row, 8) or DEFAULT_COUNTRY
oi.city = val(row, 9)
oi.disambiguated_id = val(row, 10)
oi.disambiguation_source = val(row, 11)
oi.tuakiri_name = val(row, 12)
oi.save()
return reader.line_num - 1
class User(BaseModel, UserMixin, AuditMixin):
"""
ORCiD Hub user.
It's a generic user including researchers, organisation administrators, hub administrators, etc.
"""
name = CharField(max_length=64, null=True)
first_name = CharField(null=True, verbose_name="First Name")
last_name = CharField(null=True, verbose_name="Last Name")
email = CharField(max_length=120, unique=True, null=True, verbose_name="Email Address")
eppn = CharField(max_length=120, unique=True, null=True, verbose_name="EPPN")
orcid = OrcidIdField(null=True, verbose_name="ORCID iD", help_text="User's ORCID iD")
confirmed = BooleanField(default=False)
# Role bit-map:
roles = SmallIntegerField(default=0)
is_locked = BooleanField(default=False)
webhook_enabled = BooleanField(default=False, null=True)
orcid_updated_at = DateTimeField(null=True, default=None)
# TODO: many-to-many
# NB! Deprecated!
# TODO: we still need to remember the organisation that last authenticated the user
organisation = ForeignKeyField(
Organisation, related_name="members", on_delete="SET NULL", null=True)
created_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
updated_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
def __repr__(self):
if self.name and (self.eppn or self.email):
return "%s (%s)" % (self.name, self.email or self.eppn)
return self.name or self.email or self.orcid or super().__repr__()
@property
def organisations(self):
"""Get all linked to the user organisation query."""
return (Organisation.select(
Organisation, (Organisation.tech_contact_id == self.id).alias("is_tech_contact"),
((UserOrg.is_admin.is_null(False)) & (UserOrg.is_admin)).alias("is_admin")).join(
UserOrg, on=((UserOrg.org_id == Organisation.id) & (UserOrg.user_id == self.id)))
.naive())
@lazy_property
def org_links(self):
"""Get all user organisation linked directly and indirectly."""
if self.orcid:
q = UserOrg.select().join(
User,
on=((User.id == UserOrg.user_id)
& ((User.email == self.email)
| (User.orcid == self.orcid)))).where((UserOrg.user_id == self.id)
| (User.email == self.email)
| (User.orcid == self.orcid))
else:
q = self.userorg_set
return [
r for r in q.select(UserOrg.id, UserOrg.org_id, Organisation.name.alias("org_name"))
.join(Organisation, on=(
Organisation.id == UserOrg.org_id)).order_by(Organisation.name).naive()
]
@property
def available_organisations(self):
"""Get all not yet linked to the user organisation query."""
return (Organisation.select(Organisation).where(UserOrg.id.is_null()).join(
UserOrg,
JOIN.LEFT_OUTER,
on=((UserOrg.org_id == Organisation.id) & (UserOrg.user_id == self.id))))
@property
def admin_for(self):
"""Get organisations the user is admin for (query)."""
return self.organisations.where(UserOrg.is_admin)
@property
def is_active(self):
"""Get 'is_active' based on confirmed for Flask-Login.
TODO: confirmed - user that email is confirmed either by IdP or by confirmation email
isn't the same as "is active".
"""
return self.confirmed
def has_role(self, role):
"""Return `True` if the user identifies with the specified role.
:param role: A role name, `Role` instance, or integer value.
"""
if isinstance(role, Role):
return bool(role & Role(self.roles))
elif isinstance(role, str):
try:
return bool(Role[role.upper()] & Role(self.roles))
except Exception:
False
elif type(role) is int:
return bool(role & self.roles)
else:
return False
@property
def is_superuser(self):
"""Test if the user is a HUB admin."""
return bool(self.roles & Role.SUPERUSER)
@is_superuser.setter
def is_superuser(self, value): # noqa: D401
"""Sets user as a HUB admin."""
if value:
self.roles |= Role.SUPERUSER
else:
self.roles &= ~Role.SUPERUSER
@property
def is_admin(self):
"""Test if the user belongs to the organisation admin."""
return bool(self.roles & Role.ADMIN)
def avatar(self, size=40, default="identicon"):
"""Return Gravatar service user avatar URL."""
# TODO: default gravatar image
# default = "https://www.example.com/default.jpg"
gravatar_url = "https://www.gravatar.com/avatar/" + md5(
self.email.lower().encode()).hexdigest() + "?"
gravatar_url += urlencode({'d': default, 's': str(size)})
return gravatar_url
@property
def gravatar_profile_url(self):
"""Return Gravatar service user profile URL."""
return "https://www.gravatar.com/" + md5(self.email.lower().encode()).hexdigest()
@property
def affiliations(self):
"""Return affiliations with the current organisation."""
try:
user_org = UserOrg.get(user=self, org=self.organisation)
return Affiliation(user_org.affiliations)
except UserOrg.DoesNotExist:
return Affiliation.NONE
def is_tech_contact_of(self, org=None):
"""Indicate if the user is the technical contact of the organisation."""
if org is None:
org = self.organisation
return org and org.tech_contact and org.tech_contact_id == self.id
def is_admin_of(self, org=None):
"""Indicate if the user is the technical contact of the organisation."""
if org is None:
org = self.organisation
return org and UserOrg.select().where(UserOrg.user == self, UserOrg.org == org, UserOrg.is_admin).exists()
@property
def uuid(self):
"""Generate UUID for the user based on the primary email."""
return uuid.uuid5(uuid.NAMESPACE_URL, "mailto:" + (self.email or self.eppn))
DeferredUser.set_model(User)
class OrgInvitation(BaseModel, AuditMixin):
"""Organisation invitation to on-board the Hub."""
invitee = ForeignKeyField(
User, on_delete="CASCADE", null=True, related_name="received_org_invitations")
inviter = ForeignKeyField(
User, on_delete="SET NULL", null=True, related_name="sent_org_invitations")
org = ForeignKeyField(Organisation, on_delete="SET NULL", verbose_name="Organisation")
email = TextField(
help_text="The email address the invitation was sent to.",
verbose_name="Invitee Email Address")
token = TextField(unique=True)
confirmed_at = DateTimeField(null=True)
tech_contact = BooleanField(
null=True,
help_text="The invitee is the technical contact of the organisation.",
verbose_name="Is Tech.contact")
url = CharField(null=True)
@property
def sent_at(self):
"""Get the time the invitation was sent."""
return self.created_at
class Meta: # noqa: D101,D106
db_table = "org_invitation"
table_alias = "oi"
class UserOrg(BaseModel, AuditMixin):
"""Linking object for many-to-many relationship."""
user = ForeignKeyField(User, on_delete="CASCADE", index=True)
org = ForeignKeyField(
Organisation, on_delete="CASCADE", index=True, verbose_name="Organisation")
is_admin = BooleanField(
null=True, default=False, help_text="User is an administrator for the organisation")
# Affiliation bit-map:
affiliations = SmallIntegerField(default=0, null=True, verbose_name="EDU Person Affiliations")
created_by = ForeignKeyField(
User, on_delete="SET NULL", null=True, related_name="created_user_orgs")
updated_by = ForeignKeyField(
User, on_delete="SET NULL", null=True, related_name="updated_user_orgs")
# TODO: the access token should be either here or in a separate list
# access_token = CharField(max_length=120, unique=True, null=True)
def save(self, *args, **kwargs):
"""Enforce foreign key constraints and consolidate user roles with the linked organisations.
Enforce foreign key constraints and consolidate user roles with the linked organisations
before saving data.
"""
if self.is_dirty():
if self.field_is_updated("org"):
self.org # just enforce re-querying
user = self.user
if self.is_admin != user.is_admin:
if self.is_admin or UserOrg.select().where((UserOrg.user_id == self.user_id) & (
UserOrg.org_id != self.org_id) & UserOrg.is_admin).exists(): # noqa: E125
user.roles |= Role.ADMIN
app.logger.info(f"Added ADMIN role to user {user}")
else:
user.roles &= ~Role.ADMIN
app.logger.info(f"Revoked ADMIN role from user {user}")
user.save()
return super().save(*args, **kwargs)
class Meta: # noqa: D101,D106
db_table = "user_org"
table_alias = "uo"
indexes = ((("user", "org"), True), )
class OrcidToken(BaseModel, AuditMixin):
"""For Keeping ORCID token in the table."""
user = ForeignKeyField(
User, null=True, index=True,
on_delete="CASCADE") # TODO: add validation for 3-legged authorization tokens
org = ForeignKeyField(Organisation, index=True, verbose_name="Organisation")
scope = TextField(null=True) # TODO implement property
access_token = CharField(max_length=36, unique=True, null=True)
issue_time = DateTimeField(default=datetime.utcnow)
refresh_token = CharField(max_length=36, unique=True, null=True)
expires_in = IntegerField(default=0)
created_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
updated_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
@property
def scopes(self): # noqa: D102
if self.scope:
return self.scope.split(',')
return []
@scopes.setter
def scopes(self, value): # noqa: D102
if isinstance(value, str):
self.scope = value
else:
self.scope = ','.join(value)
class Meta: # noqa: D101,D106
db_table = "orcid_token"
table_alias = "ot"
class UserOrgAffiliation(BaseModel, AuditMixin):
"""For Keeping the information about the affiliation."""
user = ForeignKeyField(User, on_delete="CASCADE")
organisation = ForeignKeyField(
Organisation, index=True, on_delete="CASCADE", verbose_name="Organisation")
disambiguated_id = CharField(verbose_name="Disambiguation ORG Id", null=True)
disambiguation_source = CharField(verbose_name="Disambiguation ORG Source", null=True)
name = TextField(null=True, verbose_name="Institution/employer")
start_date = PartialDateField(null=True)
end_date = PartialDateField(null=True)
department_name = TextField(null=True)
department_city = TextField(null=True)
role_title = TextField(null=True)
put_code = IntegerField(null=True)
path = TextField(null=True)
created_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
updated_by = ForeignKeyField(DeferredUser, on_delete="SET NULL", null=True)
class Meta: # noqa: D101,D106
db_table = "user_organisation_affiliation"
table_alias = "oua"
class OrcidApiCall(BaseModel):
"""ORCID API call audit entry."""
called_at = DateTimeField(default=datetime.utcnow)
user = ForeignKeyField(User, null=True, on_delete="SET NULL")
method = TextField()
url = TextField()
query_params = TextField(null=True)
body = TextField(null=True)
put_code = IntegerField(null=True)
response = TextField(null=True)
response_time_ms = IntegerField(null=True)
class Meta: # noqa: D101,D106
db_table = "orcid_api_call"
table_alias = "oac"
class OrcidAuthorizeCall(BaseModel):
"""ORCID Authorize call audit entry."""
called_at = DateTimeField(default=datetime.utcnow)
user = ForeignKeyField(User, null=True, on_delete="SET NULL")
method = TextField(null=True)
url = TextField(null=True)
token = TextField(null=True)
state = TextField(null=True)
response_time_ms = IntegerField(null=True)
class Meta: # noqa: D101,D106
db_table = "orcid_authorize_call"
table_alias = "oac"
class Task(BaseModel, AuditMixin):
"""Batch processing task created form CSV/TSV file."""
org = ForeignKeyField(
Organisation, index=True, verbose_name="Organisation", on_delete="CASCADE")
completed_at = DateTimeField(null=True)
filename = TextField(null=True)
created_by = ForeignKeyField(
User, on_delete="SET NULL", null=True, related_name="created_tasks")
updated_by = ForeignKeyField(
User, on_delete="SET NULL", null=True, related_name="updated_tasks")
task_type = SmallIntegerField(default=0)
expires_at = DateTimeField(null=True)
expiry_email_sent_at = DateTimeField(null=True)
completed_count = TextField(null=True, help_text="gives the status of uploaded task")
def __repr__(self):
return ("Synchronization task" if self.task_type == TaskType.SYNC else (
self.filename
or f"{TaskType(self.task_type).name.capitalize()} record processing task #{self.id}"))
@property
def is_expiry_email_sent(self):
"""Test if the expiry email is sent ot not."""
return bool(self.expiry_email_sent_at)
@lazy_property
def record_count(self):
"""Get count of the loaded recoreds."""
if self.task_type == TaskType.SYNC:
return 0
return self.records.count()
@property
def record_model(self):
"""Get record model class."""
if self.task_type == TaskType.SYNC:
return None
_, models = self.records.get_query_meta()
model, = models.keys()
return model
@lazy_property
def records(self):
"""Get all task record query."""
if self.task_type == TaskType.SYNC:
return None
return getattr(self, TaskType(self.task_type).name.lower() + "_records")
@lazy_property
def completed_count(self):
"""Get number of completed rows."""
return self.records.where(self.record_model.processed_at.is_null(False)).count()
@lazy_property
def completed_percent(self):
"""Get the percentage of completed rows."""
return (100. * self.completed_count) / self.record_count if self.record_count else 0.
@property
def error_count(self):
"""Get error count encountered during processing batch task."""
q = self.records
_, models = q.get_query_meta()
model, = models.keys()
return self.records.where(self.record_model.status ** "%error%").count()
@classmethod
def load_from_csv(cls, source, filename=None, org=None):
"""Load affiliation record data from CSV/TSV file or a string."""
if isinstance(source, str):
source = StringIO(source)
reader = csv.reader(source)
header = next(reader)
if filename is None:
if hasattr(source, "name"):
filename = source.name