-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
139 lines (104 loc) · 3.8 KB
/
main.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python
import http.client
import json
import sys
import csv
import argparse
import os
import http
def debug(output):
print(json.dumps(output))
def debug_exit(output):
debug(output)
sys.exit()
def request(endpoint, api_version = 'v1'):
headers = {
"Content-type": "application/json",
"Accept": "application/json",
"Authorization": "SSWS {}".format(api_key)
}
return makeRequest(domain, '/api/v1/{}'.format(endpoint), headers)
def makeRequest(domain, endpoint, headers):
con = http.client.HTTPSConnection(domain)
con.set_debuglevel(0)
con.request("GET", endpoint, None, headers)
response = con.getresponse()
try:
if 400 <= response.status < 600:
raise NotImplementedError(response.status, response.reason, response.read())
elif 500 <= response.status < 600:
raise SystemError(response.status, response.reason, response.read())
else:
return json.loads(response.read())
finally:
con.close()
def getOrg():
return request("/org")
def getGroups(limit=99999):
return request("/groups?limit={}".format(limit))
def getUsers(limit=99999):
return request("/users?limit={}".format(limit))
def getGroupMembership(group_id, limit=99999):
return request("/groups/{}/users?limit={}".format(group_id, limit))
def getGroupMemberships():
groups = getGroups()
for group in groups:
group['members'] = getGroupMembership(group['id'])
return groups
def getUserGroupNames(user, groups):
matches = []
for group in groups:
if 'members' in group:
for member in group['members']:
if member['id'] == user['id']:
matches.append(group['profile']['name'])
return matches
def buildMembershipReport():
groups = getGroupMemberships()
users = getUsers()
report = []
for user in users:
user_groups = getUserGroupNames(user, groups)
report.append({
'firstName': user['profile']['firstName'],
'lastName': user['profile']['lastName'],
'email': user['profile']['email'],
'status': user['status'],
'created': user['created'],
'lastLogin': user['lastLogin'],
'lastUpdated': user['lastUpdated'],
'groups': ', '.join(user_groups)
})
return report
def generateMembershipReport():
data = buildMembershipReport()
writer = csv.DictWriter(sys.stdout, fieldnames=data[0].keys(), quoting=csv.QUOTE_NONNUMERIC)
writer.writeheader()
for item in data:
writer.writerow(item)
# @TODO allow output location to be passed so we can make the interaction with the user more friendly.
def main():
"""
Main entry into the scripting here, basically allowing for you to pass
in your domain and api-key; which is either
./main.py --domain hello --api-key blahblah
or use environment vars (OKTA_DOMAIN_NAME, OKTA_API_TOKEN)
if none are provided, the script will ask you to provide them.
"""
global domain # global because i'm too lazy to get classy.
global api_key
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--domain')
parser.add_argument('-a', '--api-key')
args = parser.parse_args()
domain = os.getenv('OKTA_DOMAIN_NAME')
api_key = os.getenv('OKTA_API_TOKEN')
# override the env vars if options passed in.
domain = args.domain if args.domain else domain
api_key = args.api_key if args.api_key else api_key
if not domain:
domain = raw_input("What is your domain name [example.okta.com]? ")
if not api_key:
api_key = raw_input("What is your API Token? ")
generateMembershipReport()
main()