-
Notifications
You must be signed in to change notification settings - Fork 0
/
AzureAD.py
71 lines (45 loc) · 2.19 KB
/
AzureAD.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
# Taken from https://github.com/CSCI128/101GradingScript/blob/master/AzureAD.py
# Will probably eventually be integrated into that grading script
from typing import List
from azure.identity import AzureCliCredential
from azure.core.credentials import TokenCredential
from msgraph import GraphServiceClient
from msgraph.generated.users.users_request_builder import UsersRequestBuilder
class AzureAD():
SCOPES: List[str] = ["https://graph.microsoft.com/.default"]
@staticmethod
def _authenticate(tenantId: str) -> TokenCredential:
# TODO - We will need to provide hints for this
cred = AzureCliCredential(tenant_id=tenantId)
return cred
@staticmethod
def _createGraphServiceClient(cred: TokenCredential, scopes = SCOPES) -> GraphServiceClient:
client = GraphServiceClient(cred, scopes)
return client
def __init__(self, tenantId: str) -> None:
self.cred = self._authenticate(tenantId)
self.client = self._createGraphServiceClient(self.cred)
async def getCWIDFromEmail(self, username: str) -> str:
query = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select=["employeeId"],
)
requestConfig = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(query_parameters=query)
userCwid = await self.client.users.by_user_id(username).get(requestConfig)
if userCwid is None or userCwid.employee_id is None:
return ""
return userCwid.employee_id
async def getEmailFromCWID(self, cwid: str) -> str:
query = UsersRequestBuilder.UsersRequestBuilderGetQueryParameters(
select=["userPrincipalName"],
filter=f"employeeId eq '{cwid}' and accountEnabled eq true",
)
requestConfig = UsersRequestBuilder.UsersRequestBuilderGetRequestConfiguration(query_parameters=query)
user = await self.client.users.get(requestConfig)
if user is None:
return ""
if user.value is None or not len(user.value):
return ""
user = user.value[0]
if user.user_principal_name is None:
return ""
return user.user_principal_name