-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckpoint.py
More file actions
3627 lines (3134 loc) · 134 KB
/
checkpoint.py
File metadata and controls
3627 lines (3134 loc) · 134 KB
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
"""
IAM support and troubleshooting tools
"""
import datetime
import logging
import re
import sqlite3
from base64 import b64encode
from email.errors import InvalidHeaderDefect
from email.headerregistry import Address
from hashlib import file_digest
from json import dumps, loads
from os import environ
from re import IGNORECASE, fullmatch
from sqlite3 import connect
from typing import Any, Dict, List, Union
from urllib.parse import urlparse, urlunparse
from zoneinfo import ZoneInfo
from authlib.integrations.flask_client import OAuth
from authlib.integrations.requests_client import OAuth2Session
from flask import Flask, g, render_template, request, session
from flask.helpers import get_debug_flag, redirect, url_for
from flask_caching import Cache
from google.oauth2 import service_account
from googleapiclient.discovery import build # type: ignore
from ldap3 import (
Connection,
DEREF_ALWAYS,
SUBTREE,
Server,
)
from ldap3.operation.search import search_operation
from ldap3.utils.log import EXTENDED, set_library_log_detail_level
from requests import get, post
import sentry_sdk
from sentry_sdk import set_user
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.pure_eval import PureEvalIntegration
from slack_sdk import WebClient
from slack_sdk.signature import SignatureVerifier
from werkzeug.exceptions import BadRequest, Forbidden, InternalServerError, NotFound, Unauthorized
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
req_log = logging.getLogger("urllib3")
req_log.setLevel(logging.DEBUG)
req_log.propagate = True
GEORGIA_TECH_USERNAME_REGEX = r"[a-zA-Z]+[0-9]+"
ACCESS_OVERRIDE_TIMESTAMP_REGEX = r"(?P<timestamp>\d{4}-\d{2}-\d{2})"
NUMBER_IN_QUOTES_REGEX = r"\"(?P<user_id>\d+)\""
PAYMENT_METHOD_REGEX = r"\"method\".+\"(?P<method>[a-z]+)\".+\"amount\""
CLIENT_NAME_REGEX = r"\"client_name\".+?\"(?P<client_name>.+?)\""
USER_AGENT = "Checkpoint/" + environ.get("NOMAD_SHORT_ALLOC_ID", "local")
def traces_sampler(sampling_context: Dict[str, Dict[str, str]]) -> bool:
"""
Ignore ping events, sample all other events
"""
try:
request_uri = sampling_context["wsgi_environ"]["REQUEST_URI"]
except KeyError:
return False
return request_uri != "/ping"
sentry_sdk.init(
debug=get_debug_flag(),
integrations=[
FlaskIntegration(),
PureEvalIntegration(),
],
traces_sampler=traces_sampler,
attach_stacktrace=True,
max_request_body_size="always",
in_app_include=[
"checkpoint",
],
profiles_sample_rate=1.0,
)
app = Flask(__name__)
app.config.from_prefixed_env()
oauth = OAuth(app) # type: ignore
oauth.register( # type: ignore
name="keycloak",
server_metadata_url=app.config["KEYCLOAK_METADATA_URL"],
client_kwargs={"scope": "openid email profile"},
)
keycloak = OAuth2Session(
client_id=app.config["KEYCLOAK_ADMIN_CLIENT_ID"],
client_secret=app.config["KEYCLOAK_ADMIN_CLIENT_SECRET"],
token_endpoint=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/realms/master/protocol/openid-connect/token",
"",
"",
"",
)
),
leeway=5,
)
keycloak.headers["User-Agent"] = USER_AGENT
keycloak.fetch_token()
apiary = OAuth2Session(
client_id=app.config["APIARY_CLIENT_ID"],
client_secret=app.config["APIARY_CLIENT_SECRET"],
token_endpoint=app.config["APIARY_BASE_URL"] + "/oauth/token",
)
apiary.headers["User-Agent"] = USER_AGENT
apiary.headers["Accept"] = "application/json"
apiary.fetch_token()
cache = Cache(app)
cache.clear()
slack = WebClient(token=app.config["SLACK_BOT_TOKEN"])
set_library_log_detail_level(EXTENDED)
def generate_subresource_integrity_hash(file: str) -> str:
"""
Calculate the subresource integrity hash for a given file
"""
with open(file[1:], "rb") as f:
d = file_digest(f, "sha512")
return "sha512-" + b64encode(d.digest()).decode("utf-8")
app.jinja_env.globals["calculate_integrity"] = generate_subresource_integrity_hash
@cache.cached(key_prefix="majors")
def get_majors() -> Dict[str, str]:
"""
Fetch majors from Apiary and return as a map of whitepages_ou to display_name
"""
response = apiary.get(app.config["APIARY_BASE_URL"] + "/api/v1/majors")
response.raise_for_status()
data = response.json()
return {major["whitepages_ou"]: major["display_name"] for major in data["majors"]}
@cache.cached(key_prefix="grouper_groups")
def get_grouper_groups() -> List[str]:
"""
Fetch all Grouper groups under gt:services:robojackets and return extension names
"""
response = post(
url="https://grouper.gatech.edu/grouper-ws/servicesRest/v4_0_000/groups",
auth=(app.config["GROUPER_USERNAME"], app.config["GROUPER_PASSWORD"]),
headers={
"User-Agent": USER_AGENT,
},
json={
"WsRestFindGroupsLiteRequest": {
"stemName": "gt:services:robojackets",
"queryFilterType": "FIND_BY_STEM_NAME",
}
},
timeout=(5, 30),
)
response.raise_for_status()
return [group["extension"] for group in response.json()["WsFindGroupsResults"]["groupResults"]]
def build_ldap_filter(**kwargs: str) -> str:
"""
Builds up an LDAP filter from kwargs
:param kwargs: Dict of attribute name, value pairs
:return: LDAP search filter representation of the dict
"""
search_filter = ""
for name, value in kwargs.items():
search_filter = f"{search_filter}({name}={value})"
if len(kwargs) > 1:
search_filter = f"(&{search_filter})"
return search_filter
def build_keycloak_filter(**kwargs: str) -> str:
"""
Builds up a Keycloak filter from kwargs
:param kwargs: Dict of attribute name, value pairs
:return: Keycloak search query representation of the dict
"""
filters = []
for name, value in kwargs.items():
filters.append(f"{name}:{value}")
return " ".join(filters)
def get_attribute_value(
attribute_name: str, entry: Dict[str, Dict[str, List[str]]]
) -> Union[str, None]:
"""
Get a given attribute value from a Whitepages entry or Keycloak account, if it exists
"""
if (
"attributes" in entry
and attribute_name in entry["attributes"]
and entry["attributes"][attribute_name] is not None
and len(entry["attributes"][attribute_name]) > 0
):
return entry["attributes"][attribute_name][0]
return None
def get_gted_primary_account(**kwargs: str) -> Union[Dict[str, Any], None]:
"""
Get the primary account for a user matching the provided kwargs
"""
accounts = search_gted(**kwargs)
if len(accounts) == 0:
return None
return [
account for account in accounts if account["uid"] == account["gtPrimaryGTAccountUsername"]
][0]
def search_gted(**kwargs: str) -> List[Dict[str, Any]]:
"""
Search GTED (via BuzzAPI) for accounts matching criteria specified in kwargs
"""
buzzapi_response = post(
url="https://api.gatech.edu/apiv3/central.iam.gted.accounts/search",
json={
"api_app_id": app.config["BUZZAPI_USERNAME"],
"api_app_password": app.config["BUZZAPI_PASSWORD"],
"api_request_mode": "sync",
"api_log_level": "debug",
"requested_attributes": [
"gtGTID",
"mail",
"sn",
"givenName",
"eduPersonPrimaryAffiliation",
"gtPrimaryGTAccountUsername",
"uid",
"gtEmplId",
"gtEmployeeHomeDepartmentName",
"eduPersonScopedAffiliation",
"gtCurriculum",
"gtAccessCardNumber",
"gtAccountEntitlement",
"gtSecondaryMailAddress",
],
}
| kwargs,
timeout=(5, 30),
headers={
"User-Agent": USER_AGENT,
},
)
buzzapi_response.raise_for_status()
if "api_result_data" not in buzzapi_response.json():
return []
for account in buzzapi_response.json()["api_result_data"]:
db().execute(
(
"INSERT INTO crosswalk (gt_person_directory_id, gtid, primary_username)"
" VALUES (:gt_person_directory_id, :gtid, :primary_username) ON CONFLICT DO NOTHING" # noqa
),
{
"gt_person_directory_id": account["gtPersonDirectoryId"],
"gtid": account["gtGTID"],
"primary_username": account["gtPrimaryGTAccountUsername"],
},
)
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": account["mail"],
"gt_person_directory_id": account["gtPersonDirectoryId"],
},
)
return buzzapi_response.json()["api_result_data"] # type: ignore
@cache.memoize()
def search_whitepages(**kwargs: str) -> List[Dict[str, Dict[str, List[str]]]]:
"""
Search Whitepages with a given LDAP filter
"""
with sentry_sdk.start_span(op="whitepages.connect"):
whitepages = Connection(
Server("whitepages.gatech.edu", connect_timeout=1),
auto_bind=True,
raise_exceptions=True,
receive_timeout=1,
return_empty_attributes=False,
)
with sentry_sdk.start_span(op="whitepages.search"):
# the normal .search function does not allow sending blank attributes in the request,
# which is the easiest way to get all attributes back from whitepages
# there is some munging inside the .search function, and then it calls the below two
# internal functions (among other things)
ldap_request = search_operation(
search_base="dc=whitepages,dc=gatech,dc=edu",
search_filter=build_ldap_filter(**kwargs),
search_scope=SUBTREE,
dereference_aliases=DEREF_ALWAYS,
attributes=[],
size_limit=0,
time_limit=0,
types_only=False,
auto_escape=False,
auto_encode=False,
schema=None,
validator=None,
check_names=False,
)
whitepages.post_send_search(whitepages.send("searchRequest", ldap_request, []))
records = []
for entry in whitepages.entries:
record = loads(entry.entry_to_json())
records.append(record)
username = get_attribute_value("primaryUid", record)
mail = get_attribute_value("mail", record)
if username is not None and mail is not None:
cursor = db().execute(
"SELECT gt_person_directory_id FROM crosswalk WHERE primary_username = (:username)",
{"username": username},
)
row = cursor.fetchone()
if row is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": mail,
"gt_person_directory_id": row[0],
},
)
return records
@cache.cached(key_prefix="realms")
def get_realms() -> List[Dict[str, Any]]:
"""
Get realm information from Keycloak
"""
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/realms",
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
return keycloak_response.json() # type: ignore
@cache.memoize()
def get_actor(**kwargs: str) -> Dict[str, Union[str, None]]:
"""
Get the display name and link for an event actor
"""
if (
"full_name" in kwargs
and "gtPersonDirectoryId" in kwargs
and kwargs["gtPersonDirectoryId"] is not None
):
return {
"actorDisplayName": kwargs["full_name"],
"actorLink": "/view/" + kwargs["gtPersonDirectoryId"],
}
if (
"full_name" in kwargs
and "id" in kwargs
and kwargs["id"] is not None
and "is_service_account" in kwargs
and kwargs["is_service_account"] is True # type: ignore
):
display_name = kwargs["full_name"]
if display_name.startswith("Service Account for "):
display_name = display_name[len("Service Account for ") :] # noqa
return {
"actorDisplayName": display_name,
"actorLink": app.config["APIARY_BASE_URL"] + "/nova/resources/users/" + kwargs["id"],
}
if "gtPersonDirectoryId" in kwargs or "uid" in kwargs:
gted_account = get_gted_primary_account(**kwargs)
if gted_account is None:
raise InternalServerError(
"Failed to locate GTED account with given " + list(dict.keys(kwargs))[0]
)
return {
"actorDisplayName": gted_account["givenName"] + " " + gted_account["sn"],
"actorLink": "/view/" + gted_account["gtPersonDirectoryId"],
}
if "realmId" in kwargs and "userId" in kwargs:
for realm in get_realms():
if kwargs["realmId"] == realm["id"]:
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/realms/" + realm["realm"] + "/users/" + kwargs["userId"],
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
if (
fullmatch(
GEORGIA_TECH_USERNAME_REGEX,
keycloak_response.json()["username"],
IGNORECASE,
)
is not None
):
return get_actor(uid=keycloak_response.json()["username"]) # type: ignore
return {
"actorDisplayName": keycloak_response.json()["username"],
"actorLink": urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/master/console/",
"",
"",
"/"
+ realm["realm"]
+ "/users/"
+ keycloak_response.json()["id"]
+ "/settings",
)
),
}
if "apiary_user_id" in kwargs:
apiary_response = apiary.get(
url=app.config["APIARY_BASE_URL"] + "/api/v1/users/" + str(kwargs["apiary_user_id"]),
timeout=(5, 5),
)
apiary_response.raise_for_status()
if (
"user" in apiary_response.json()
and apiary_response.json()["user"] is not None
and "full_name" in apiary_response.json()["user"]
and apiary_response.json()["user"]["full_name"] is not None
):
return {
"actorDisplayName": apiary_response.json()["user"]["full_name"],
}
if "email" in kwargs:
email_results = search_by_email(Address(addr_spec=kwargs["email"]), with_gted=False)
if len(email_results["results"]) > 0:
return {
"actorDisplayName": email_results["results"][0]["givenName"]
+ " "
+ email_results["results"][0]["surname"],
"actorLink": "/view/" + email_results["results"][0]["directoryId"],
}
if "customer_id" in kwargs:
credentials = service_account.Credentials.from_service_account_info( # type: ignore
info=app.config["GOOGLE_SERVICE_ACCOUNT_CREDENTIALS"],
scopes=[
"https://www.googleapis.com/auth/admin.directory.user.readonly",
"https://www.googleapis.com/auth/admin.directory.customer.readonly",
],
subject=app.config["GOOGLE_SUBJECT"],
)
directory = build(serviceName="admin", version="directory_v1", credentials=credentials)
customer_details = (
directory.customers().get(customerKey=kwargs["customer_id"]).execute()
)
user_details = directory.users().get(userKey=kwargs["email"]).execute()
return {
"actorDisplayName": user_details["name"]["fullName"],
"actorLink": "https://www.google.com/a/"
+ customer_details["customerDomain"]
+ "/ServiceLogin?continue=https://admin.google.com/ac/search?query="
+ user_details["primaryEmail"],
}
if (
"callerType" in kwargs
and "key" in kwargs
and kwargs["callerType"] == "KEY"
and kwargs["key"] == "SYSTEM"
):
return {
"actorDisplayName": "system",
"actorLink": None,
}
raise InternalServerError("Unable to identify actor, given: " + dumps(kwargs))
def get_client_display_name(**kwargs: str) -> str:
"""
Get the display name for a client from a Keycloak event
"""
if "realmId" in kwargs and "clientId" in kwargs:
for realm in get_realms():
if kwargs["realmId"] == realm["id"]:
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/realms/" + realm["realm"] + "/clients/" + kwargs["clientId"],
"",
"",
"",
)
),
timeout=(5, 5),
)
keycloak_response.raise_for_status()
print(keycloak_response.text)
return keycloak_response.json()["clientId"] # type: ignore
raise InternalServerError("Unable to identify client")
def search_keycloak(**kwargs: Union[str, bool]) -> List[Dict[str, Any]]:
"""
Search Keycloak for accounts matching criteria specified in kwargs
"""
keycloak_response = keycloak.get(
url=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/realms/" + app.config["KEYCLOAK_REALM"] + "/users",
"",
"",
"",
)
),
params=kwargs,
timeout=(5, 5),
)
keycloak_response.raise_for_status()
for account in keycloak_response.json():
cursor = db().execute(
"SELECT gt_person_directory_id FROM crosswalk WHERE primary_username = (:username)",
{"username": account["username"]},
)
row = cursor.fetchone()
if row is not None:
db().execute(
(
"UPDATE crosswalk SET keycloak_user_id = (:keycloak_user_id) WHERE gt_person_directory_id = (:gt_person_directory_id)" # noqa
),
{
"keycloak_user_id": account["id"],
"gt_person_directory_id": row[0],
},
)
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)"
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": account["email"],
"gt_person_directory_id": row[0],
},
)
workspace_email = get_attribute_value("googleWorkspaceAccount", account)
if workspace_email is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": workspace_email,
"gt_person_directory_id": row[0],
},
)
ramp_email = get_attribute_value("rampLoginEmailAddress", account)
if ramp_email is not None:
db().execute(
(
"INSERT INTO crosswalk_email_address (email_address, gt_person_directory_id)" # noqa
" VALUES (:email_address, :gt_person_directory_id)"
" ON CONFLICT DO UPDATE SET gt_person_directory_id = (:gt_person_directory_id) WHERE email_address = (:email_address)" # noqa
),
{
"email_address": ramp_email,
"gt_person_directory_id": row[0],
},
)
return keycloak_response.json() # type: ignore
def clean_affiliations(affiliations: List[str]) -> List[str]:
"""
Remove redundant or confusing affiliations from search results
"""
cleaned_affiliations = set()
for affiliation in affiliations:
parts = affiliation.split("@")
cleaned_affiliations.add(parts[0])
if "member" in cleaned_affiliations:
cleaned_affiliations.remove("member")
if "active-member" in cleaned_affiliations:
cleaned_affiliations.remove("active-member")
return list(cleaned_affiliations)
def format_search_result(
gted_account: Dict[str, Any], whitepages_entries: List[Dict[str, Dict[str, List[str]]]]
) -> Dict[str, Union[Any, None]]:
"""
Format a search result for the UI
"""
title = None
organizational_unit = None
if len(whitepages_entries) == 1:
title = get_attribute_value("title", whitepages_entries[0])
organizational_unit = get_attribute_value("ou", whitepages_entries[0])
elif len(whitepages_entries) > 1:
for entry in whitepages_entries:
if (
"attributes" in entry # pylint: disable=too-many-boolean-expressions
and "title" in entry["attributes"]
and entry["attributes"]["title"] is not None
and len(entry["attributes"]["title"]) > 0
and entry["attributes"]["title"][0] is not None
and "student assistant" not in entry["attributes"]["title"][0].lower()
and "research assistant" not in entry["attributes"]["title"][0].lower()
and "graduate assistant" not in entry["attributes"]["title"][0].lower()
and "graduate teaching assistant" not in entry["attributes"]["title"][0].lower()
and "research technologist" not in entry["attributes"]["title"][0].lower()
and "instructional associate" not in entry["attributes"]["title"][0].lower()
and "temp" not in entry["attributes"]["title"][0].lower()
and "work study" not in entry["attributes"]["title"][0].lower()
):
if title is not None:
raise InternalServerError(
"Selected multiple Whitepages entries to display in results for "
+ gted_account["gtPrimaryGTAccountUsername"]
)
title = entry["attributes"]["title"][0]
organizational_unit = get_attribute_value("ou", entry)
if (
organizational_unit is None
and "gtCurriculum" in gted_account
and gted_account["gtCurriculum"] is not None
and len(gted_account["gtCurriculum"]) > 0
):
for curriculum in gted_account["gtCurriculum"]:
parts = curriculum.split("/")
if len(parts) == 3:
organizational_unit = parts[2]
return {
"givenName": gted_account["givenName"],
"surname": gted_account["sn"],
"directoryId": gted_account["gtPersonDirectoryId"],
"primaryAffiliation": (
gted_account["eduPersonPrimaryAffiliation"]
if gted_account["eduPersonPrimaryAffiliation"] != "member"
else None
),
"affiliations": clean_affiliations(gted_account["eduPersonScopedAffiliation"]),
"title": title,
"organizationalUnit": organizational_unit,
}
def format_search_result_blocks(
search_results: Dict[str, Any],
) -> List[Dict[str, Any]]:
"""
Convert search results to Slack Block Kit blocks for a modal
"""
if len(search_results["results"]) == 0:
return [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "No Georgia Tech account found for this user.",
},
}
]
blocks: List[Dict[str, Any]] = []
for result in search_results["results"]:
lines = [f"*{result['givenName']} {result['surname']}*"]
detail_parts = []
if result.get("title"):
detail_parts.append(result["title"])
if result.get("organizationalUnit"):
if result["organizationalUnit"] in get_majors():
detail_parts.append(get_majors()[result["organizationalUnit"]])
else:
detail_parts.append(result["organizationalUnit"])
if detail_parts:
lines.append(" | ".join(detail_parts))
blocks.append(
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "\n".join(lines),
},
}
)
cursor = db().execute(
"SELECT primary_username FROM crosswalk WHERE gt_person_directory_id = (:directory_id)",
{"directory_id": result["directoryId"]},
)
row = cursor.fetchone()
if row is not None:
primary_username = row[0]
else:
raise InternalServerError(
"Primary username not found for directory ID: " + result["directoryId"]
)
apiary_button = []
apiary_account = get_apiary_account(result["directoryId"], is_frontend_request=False)
if (
apiary_account is not None
and "id" in apiary_account
and apiary_account["id"] is not None
):
apiary_button = [
{
"type": "button",
"text": {"type": "plain_text", "text": "View in Apiary"},
"url": app.config["APIARY_BASE_URL"]
+ "/nova/resources/users/"
+ apiary_account["id"],
}
]
keycloak_button = []
keycloak_account = get_keycloak_account(result["directoryId"], is_frontend_request=False)
if (
keycloak_account is not None
and "id" in keycloak_account
and keycloak_account["id"] is not None
):
keycloak_button = [
{
"text": {"type": "plain_text", "text": "View in Keycloak"},
"url": urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/master/console/",
"",
"",
"/"
+ app.config["KEYCLOAK_REALM"]
+ "/users/"
+ keycloak_account["id"]
+ "/settings",
)
),
}
]
google_workspace_button = []
google_workspace_account = get_google_workspace_account(
result["directoryId"], is_frontend_request=False
)
if (
google_workspace_account is not None
and "primaryEmail" in google_workspace_account
and google_workspace_account["primaryEmail"] is not None
):
google_workspace_button = [
{
"text": {"type": "plain_text", "text": "View in Google Workspace"},
"url": "https://www.google.com/a/robojackets.org/ServiceLogin?continue=https://admin.google.com/ac/search?query=" # noqa
+ google_workspace_account["primaryEmail"],
}
]
blocks.append(
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "View in Checkpoint"},
"url": "https://checkpoint.bcdc.robojackets.net/view/"
+ result["directoryId"],
"action_id": "view_in_checkpoint",
},
*apiary_button,
{
"type": "overflow",
"action_id": "overflow_menu",
"options": [
{
"text": {"type": "plain_text", "text": "View in IAT"},
"url": "https://iat.gatech.edu/prod/person/"
+ result["directoryId"],
},
{
"text": {"type": "plain_text", "text": "View in Grouper"},
"url": "https://grouper.gatech.edu/grouper/grouperUi/app/UiV2Main.index?operation=UiV2Subject.viewSubject&subjectId=" # noqa
+ primary_username
+ "&sourceId=gted-accounts",
},
*keycloak_button,
*google_workspace_button,
],
},
],
}
)
return blocks
def db() -> sqlite3.Connection:
"""
Get a connection to the database
"""
connection = getattr(g, "_database", None)
if connection is None:
connection = g._database = connect(app.config["DATABASE_LOCATION"])
connection.autocommit = True
connection.execute("PRAGMA foreign_keys = 1")
return connection
@app.teardown_appcontext
def close_connection(exception) -> None: # type: ignore # pylint: disable=unused-argument
"""
Close the connection to the database, if one is open
Automatically called at the end of a request
"""
connection = getattr(g, "_database", None)
if connection is not None:
connection.close()
@app.get("/")
@app.get("/search")
@app.get("/view/<directory_id>")
def spa(directory_id: Union[str, None] = None) -> Any: # pylint: disable=unused-argument
"""
Render the SPA, or an error page, or redirect to login, as applicable
"""
if "has_access" not in session:
if request.query_string == b"":
session["next"] = request.path
else:
session["next"] = request.path + "?" + request.query_string.decode("utf-8")
return oauth.keycloak.authorize_redirect(url_for("login", _external=True))
set_user(
{
"id": session["sub"],
"username": session["username"],
"ip_address": request.remote_addr,
}
)
if session["has_access"] is not True:
sub = str(session["sub"])
username = str(session["username"])
session.clear()
return (
render_template(
"access_denied.html",
username=username,
keycloak_user_deep_link=urlunparse(
(
urlparse(app.config["KEYCLOAK_METADATA_URL"]).scheme,
urlparse(app.config["KEYCLOAK_METADATA_URL"]).hostname,
"/admin/master/console/",
"",
"",
"/" + app.config["KEYCLOAK_REALM"] + "/users/" + sub + "/role-mapping",
)
),
),
403,
)
return render_template(
"app.html",
elm_model={