Skip to content

Commit cd66aeb

Browse files
committed
feat: add baseline class to get users' information from azure
1 parent 6e938ab commit cd66aeb

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

.env.template

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,10 @@ export DATABASE_MASTER_KEY=<db_master_key>
1313
# export COSMOS_DATABASE_URI=AccountEndpoint=<ACCOUNT_URI>;AccountKey=<ACCOUNT_KEY>
1414
## Also specify the database name
1515
export DATABASE_NAME=<db_name>
16+
17+
## For Azure Users interaction
18+
export MSAL_AUTHORITY=
19+
export MSAL_CLIENT_ID=
20+
export MSAL_SCOPE=
21+
export MSAL_SECRET=
22+
export MSAL_ENDPOINT=

utils/azure_users.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import msal
2+
import os
3+
import requests
4+
5+
6+
class MSALConfig:
7+
MSAL_CLIENT_ID = os.environ.get('MSAL_CLIENT_ID')
8+
MSAL_AUTHORITY = os.environ.get('MSAL_AUTHORITY')
9+
MSAL_SECRET = os.environ.get('MSAL_SECRET')
10+
MSAL_SCOPE = os.environ.get('MSAL_SCOPE')
11+
MSAL_ENDPOINT = os.environ.get('MSAL_ENDPOINT')
12+
"""
13+
TODO : Add validation to ensure variables are set
14+
"""
15+
16+
17+
class AzureUsers:
18+
def __init__(self, config=MSALConfig):
19+
self.client = msal.ConfidentialClientApplication(
20+
config.MSAL_CLIENT_ID,
21+
authority=config.MSAL_AUTHORITY,
22+
client_credential=config.MSAL_SECRET,
23+
)
24+
self.config = config
25+
self.set_token()
26+
27+
def set_token(self):
28+
response = self.client.acquire_token_for_client(
29+
scopes=self.config.MSAL_SCOPE
30+
)
31+
if "access_token" in response:
32+
# Call a protected API with the access token.
33+
# print(response["access_token"])
34+
self.access_token = response['access_token']
35+
else:
36+
print(response.get("error"))
37+
print(response.get("error_description"))
38+
print(
39+
response.get("correlation_id")
40+
) # You might need this when reporting a bug
41+
42+
def get_user_info_by_id(self, id):
43+
endpoint = f"{self.config.MSAL_ENDPOINT}/users/{id}?api-version=1.6&$select=displayName,otherMails"
44+
print(endpoint)
45+
http_headers = {
46+
'Authorization': f'Bearer {self.access_token}',
47+
'Accept': 'application/json',
48+
'Content-Type': 'application/json',
49+
}
50+
data = requests.get(
51+
endpoint, headers=http_headers, stream=False
52+
).json()
53+
return data

0 commit comments

Comments
 (0)