1+ import constants
2+ import datetime
3+
4+ from authentication_helper import AuthenticationHelper
5+ from models import database , Organization , DataSyncRecord , Profile
6+ from ms_graph import GraphServiceClient
7+
8+ class UserDataSyncService (object ):
9+
10+ def __init__ (self ):
11+ self ._users_query = "users"
12+ self ._auth_helper = AuthenticationHelper (constants .client_cert_path , constants .client_cert_password )
13+
14+ def sync (self ):
15+ for organization in Organization .get_consented ():
16+ self .sync_organization (organization )
17+
18+ def sync_organization (self , organization ):
19+ print ('Sync tenant ' + organization .name )
20+
21+ client = self ._get_graph_service_client (organization .tenantId )
22+
23+ record , is_new_record = DataSyncRecord .get_or_create (
24+ tenantId = organization .tenantId ,
25+ query = self ._users_query )
26+
27+ if is_new_record :
28+ query = { '$select' : 'jobTitle,department,mobilePhone' }
29+ users , next_link , delta_link = client .get_users_delta (query )
30+ else :
31+ users , next_link , delta_link = client .get_users (record .deltaLink )
32+
33+ while True :
34+ for user in users :
35+ profile = Profile .get_or_none (Profile .o365UserId == user ['id' ])
36+ if profile :
37+ self ._update_profile (profile , user )
38+ if next_link :
39+ users , next_link , delta_link = client .get_users (next_link )
40+ else :
41+ break
42+
43+ self ._update_data_sync_record (record , delta_link )
44+
45+ def _update_profile (self , profile , user ):
46+ print ('update user: ' + profile .o365Email )
47+ profile .jobTitle = user ['jobTitle' ]
48+ profile .department = user ['department' ]
49+ profile .mobilePhone = user ['mobilePhone' ]
50+ profile .save ()
51+
52+ def _update_data_sync_record (self , record , delta_link ):
53+ record .deltaLink = delta_link
54+ record .updated = datetime .datetime .now ()
55+ record .save ()
56+
57+ def _get_graph_service_client (self , tenant_id ):
58+ access_token = self ._auth_helper .get_app_only_access_token (
59+ tenant_id , constants .client_id , constants .ms_graph_resource )
60+ return GraphServiceClient (constants .ms_graph_resource , access_token )
0 commit comments