|
| 1 | +from _projects import get_mongo_db |
| 2 | +from helm.tools.dags._msgraph import MsGraph |
| 3 | + |
| 4 | + |
| 5 | +def parse_ministry_from_display_name(display_name: str): |
| 6 | + ministry = "" |
| 7 | + if display_name and len(display_name) > 0: |
| 8 | + divided_string = display_name.split() |
| 9 | + if len(divided_string) >= 2: |
| 10 | + ministry = divided_string[-1].split(":", 1)[0] |
| 11 | + return ministry |
| 12 | + |
| 13 | + |
| 14 | +def sync_db_users_with_azure_ad( |
| 15 | + mongo_conn_id, ms_graph_api_tenant_id, ms_graph_api_client_id, ms_graph_api_client_secret |
| 16 | +): |
| 17 | + try: |
| 18 | + db = get_mongo_db(mongo_conn_id) |
| 19 | + projection = {"image": 0, "lastseen": 0, "updatedAt": 0, "createdAt": 0} |
| 20 | + users_collection = db["User"] |
| 21 | + db_users = users_collection.find({"archived": {"$eq": False}}, projection) |
| 22 | + |
| 23 | + ms_graph = MsGraph(ms_graph_api_tenant_id, ms_graph_api_client_id, ms_graph_api_client_secret) |
| 24 | + |
| 25 | + for db_user in db_users: |
| 26 | + db_user_email = db_user["email"].lower() |
| 27 | + azure_user = ms_graph.fetch_azure_user(db_user_email) |
| 28 | + if azure_user is not None: |
| 29 | + update_data = { |
| 30 | + "officeLocation": azure_user.get("officeLocation", ""), |
| 31 | + "jobTitle": azure_user.get("jobTitle", ""), |
| 32 | + "upn": azure_user.get("userPrincipalName", ""), |
| 33 | + "providerUserId": azure_user.get("id", ""), |
| 34 | + "ministry": parse_ministry_from_display_name( |
| 35 | + azure_user.get("displayName", ""), |
| 36 | + ), |
| 37 | + "firstName": azure_user.get("givenName", ""), |
| 38 | + "lastName": azure_user.get("surname", ""), |
| 39 | + "email": azure_user.get("mail", "").lower(), |
| 40 | + "idirGuid": azure_user.get("idirGuid", ""), |
| 41 | + "idir": azure_user.get("onPremisesSamAccountName", ""), |
| 42 | + } |
| 43 | + |
| 44 | + update_data = {k: v for k, v in update_data.items() if v is not None} |
| 45 | + |
| 46 | + users_collection.update_one({"_id": db_user["_id"]}, {"$set": update_data}) |
| 47 | + else: |
| 48 | + users_collection.update_one({"_id": db_user["_id"]}, {"$set": {"archived": True}}) |
| 49 | + |
| 50 | + except Exception as e: |
| 51 | + print(f"[sync_users_in_db_and_azure_ad] Error: {e}") |
0 commit comments