|
| 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