This repository was archived by the owner on Jul 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle_directory_sync.py
102 lines (82 loc) · 3.73 KB
/
google_directory_sync.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import os
import httplib2
from apiclient import discovery
from models import Employee
from oauth2client import client, tools
from oauth2client.file import Storage
from sqlalchemy import create_engine
from sqlalchemy.orm.session import sessionmaker
engine = create_engine(
os.getenv('DATABASE_URL', ('postgres://account_admin_user@localhost:5433'
'/account_admin?sslmode=verify-ca')))
Session = sessionmaker(bind=engine)
SCOPES = 'https://www.googleapis.com/auth/admin.directory.user'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Directory API Python Sync'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'admin-directory_v1-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""
Simple script to fetch all OAO internal users from Google Directory API
and sync to the 'person' table in our 'account_admin' database.
Users are matched based on Google user id. Any id values appearing in the
API pull that aren't already added get a row inserted with name, gsuite_id,
and email. Manager is left to be filled in by the administrative user.
After that, and similiarly, any id values in the database table that are
not in the pull from Google have their current_employee_flag set to False
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('admin', 'directory_v1', http=http)
# Get all Google Users from Directory API
results = service.users().list(
customer='my_customer',
query="orgUnitPath='/Google Users' isSuspended=false",
orderBy='email').execute()
users = results.get('users', [])
user_ids = [user['id'] for user in users]
# Get list of Employee codes (== user['id'] from google) from database
session = Session()
person_query = session.query(Employee).all()
person_codes = [person.gsuite_id for person in person_query]
# Add any Google users to 'person' table if user['id'] not already
# in person_code
for user in users:
if user['id'] not in person_codes:
print(user['primaryEmail'], user['id'])
q = Employee(first_name=user['name']['givenName'],
last_name=user['name']['familyName'],
gsuite_id=user['id'],
email=user['primaryEmail'])
session.add(q)
session.commit()
# Set current_employee_flag to False if person's gsuite_id not found in
# list of ids from Google, as a way to "soft delete" these users
# TODO: This will keep updating users that have already been soft-deleted.
# Not a _terrible_ issue, but we should do better.
for person in person_codes:
if person not in user_ids:
q = session.query(Employee).filter_by(gsuite_id=person).first()
q.current_employee_flag = False
session.commit()
if __name__ == '__main__':
main()