-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathauthzero.py
418 lines (369 loc) · 14 KB
/
authzero.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2021 Mozilla Corporation
# Contributors: Guillaume Destuynder <[email protected]>, Gene Wood <[email protected]>
import requests
import json
import logging
import time
class DotDict(dict):
"""return a dict.item notation for dict()'s"""
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
def __init__(self, dct):
for key, value in dct.items():
if hasattr(value, 'keys'):
value = DotDict(value)
self[key] = value
class AuthZeroRule(object):
"""Lightweight Rule Object"""
def __init__(self):
self.id = None
self.enabled = False
self.script = None
self.name = None
self.order = 0
self.stage = 'login_success'
def validate(self):
if self.script is None:
raise Exception('RuleValidationError', ('script cannot be None'))
if self.name is None:
raise Exception('RuleValidationError', ('name cannot be None'))
if self.order <= 0:
raise Exception('RuleValidationError', ('order must be greater than 0'))
return True
def json(self):
tmp = {'id': self.id, 'enabled': self.enabled, 'script': self.script,
'name': self.name, 'order': self.order, 'stage': self.stage}
# Remove id if we don't have one. It means it's a new rule.
if tmp.get('id') is None:
tmp.pop('id')
return json.dumps(tmp)
def __str__(self):
return self.json().__str__()
class AuthZero(object):
def __init__(self, config):
config = DotDict(config)
self.default_headers = {
'content-type': "application/json"
}
self.uri = config.uri
self.client_id = config.client_id
self.client_secret = config.client_secret
self.access_token = None
self.access_token_scope = None
self.access_token_valid_until = 0
self.access_token_auto_renew = False
self.access_token_auto_renew_leeway = 60
self.rules = []
self.logger = logging.getLogger('AuthZero')
def __del__(self):
self.client_secret = None
def get_rules(self):
return self._request("/api/v2/rules")
def delete_rule(self, rule_id):
"""
rule_id: string
rule: AuthZeroRule object
Deletes an Auth0 rule
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Rules/delete_rules_by_id
Auth0 API endpoint: PATH /api/v2/rules/{id}
Auth0 API parameters: id (rule_id, required)
"""
return self._request("/api/v2/rules/{}".format(rule_id), "DELETE")
def create_rule(self, rule):
"""
rule_id: string
rule: AuthZeroRule object
Creates an Auth0 rule
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Rules/post_rules
Auth0 API endpoint: PATH /api/v2/rules
Auth0 API parameters: body (required)
"""
payload = DotDict(dict())
payload.script = rule.script
payload.name = rule.name
payload.order = rule.order
payload.enabled = rule.enabled
return self._request("/api/v2/rules", "POST", payload)
def update_rule(self, rule_id, rule):
"""
rule_id: string
rule: AuthZeroRule object
Updates an Auth0 rule
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Rules/patch_rules_by_id
Auth0 API endpoint: PATH /api/v2/rules/{id}
Auth0 API parameters: id (rule_id, required), body (required)
"""
payload = DotDict(dict())
payload.script = rule.script
payload.name = rule.name
payload.order = rule.order
payload.enabled = rule.enabled
return self._request("/api/v2/rules/{}".format(rule_id), "PATCH", payload)
def get_clients(self):
"""
Get list of Auth0 clients
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Clients/get_clients
Auth0 API endpoint: PATH /api/v2/clients
Auth0 API parameters: fields (optional), ...
"""
page = 0
per_page = 100
totals = 0
done = -1
clients = []
while totals > done:
ret = self._request("/api/v2/clients?"
"&per_page={per_page}"
"&page={page}&include_totals=true"
"".format(page=page, per_page=per_page),
"GET")
clients += ret['clients']
done = done + per_page
page = page + 1
totals = ret['total']
logging.debug("Got {} clients out of {} - current page {}".format(done, totals, page))
return clients
def create_client(self, client):
"""
client: client object (dict)
Create an Auth0 client
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Clients/post_clients
Auth0 API endpoint: PATH /api/v2/clients
Auth0 API parameters: body (required)
"""
return self._request("/api/v2/clients", "POST", client)
def update_client(self, client_id, client):
"""
client_id: client id (string)
client: client object (dict)
Update an Auth0 client
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Clients/patch_clients_by_id
Auth0 API endpoint: PATH /api/v2/clients
Auth0 API parameters: id (required), body (required)
"""
# We accept clients ready by Auth0's API (GET) but updates (PATCH) use a DIFFERENT format.
# This means we need to CONVERT GET'd clients so that they will be accepted for PATCH'ing.
# That's quite annoying, by the way. Why?! :-(
patch_api_schema = """
{
"name": "",
"description": "",
"client_secret": "",
"logo_uri": "",
"callbacks": [
""
],
"allowed_origins": [
""
],
"web_origins": [
""
],
"grant_types": [
""
],
"client_aliases": [
""
],
"allowed_clients": [
""
],
"allowed_logout_urls": [
""
],
"jwt_configuration": {
"lifetime_in_seconds": 0,
"scopes": {},
"alg": ""
},
"encryption_key": {
"pub": "",
"cert": "",
"subject": ""
},
"sso": false,
"cross_origin_auth": false,
"cross_origin_loc": "",
"sso_disabled": false,
"custom_login_page_on": false,
"token_endpoint_auth_method": "",
"app_type": "",
"oidc_conformant": false,
"custom_login_page": "",
"custom_login_page_preview": "",
"form_template": "",
"addons": {
"aws": {},
"azure_blob": {},
"azure_sb": {},
"rms": {},
"mscrm": {},
"slack": {},
"sentry": {},
"box": {},
"cloudbees": {},
"concur": {},
"dropbox": {},
"echosign": {},
"egnyte": {},
"firebase": {},
"newrelic": {},
"office365": {},
"salesforce": {},
"salesforce_api": {},
"salesforce_sandbox_api": {},
"samlp": {},
"layer": {},
"sap_api": {},
"sharepoint": {},
"springcm": {},
"wams": {},
"wsfed": {},
"zendesk": {},
"zoom": {}
},
"client_metadata": {},
"mobile": {
"android": {
"app_package_name": "",
"sha256_cert_fingerprints": [
]
},
"ios": {
"team_id": "",
"app_bundle_identifier": ""
}
}
}
"""
patch_api_dict = json.loads(patch_api_schema)
payload = {}
for i in patch_api_dict:
val = client.get(i)
if (val is not None):
# Sub structure! we just check one level deep
if isinstance(val, dict) and len(patch_api_dict[i]) > 0:
for y in patch_api_dict[i]:
payload[i] = {}
try:
payload[i][y] = val[y]
except KeyError:
pass #don't have this, then ignore it
else:
payload[i] = val
return self._request("/api/v2/clients/{}".format(client_id),
"PATCH",
payload)
def delete_client(self, client_id):
"""
client_id: client id (string)
Delete an Auth0 client
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Clients/delete_clients_by_id
Auth0 API endpoint: PATH /api/v2/clients
Auth0 API parameters: id (required), body (required)
"""
return self._request("/api/v2/clients/{}".format(client_id), "DELETE")
def get_users(self, fields="username,user_id,name,email,identities,groups", query_filter=""):
"""
Returns a list of users from the Auth0 API.
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Users/get_users
query_filter: string
returns: JSON dict of the list of users
"""
page = 0
per_page = 100
totals = 0
done = -1
users = []
while totals > done:
ret = self._request("/api/v2/users?fields={fields}&"
"search_engine=v2&q={query_filter}&per_page={per_page}"
"&page={page}&include_totals=true"
"".format(fields=fields, query_filter=query_filter, page=page, per_page=per_page),
"GET")
users += ret['users']
done = done + per_page
page = page + 1
totals = ret['total']
logging.debug("Got {} users out of {} - current page {}".format(done, totals, page))
return users
def get_logs(self):
return self._request("/api/v2/logs")
def get_user(self, user_id):
"""Return user from the Auth0 API.
Auth0 API doc: https://auth0.com/docs/api/management/v2/#!/Users/get_users_by_id
user_id: string
returns: JSON dict of the user profile
"""
return self._request("/api/v2/users/{}".format(user_id), "GET")
def update_user(self, user_id, new_profile):
"""
user_id: string
new_profile: dict (can be a JSON string loaded with json.loads(str) for example)
Update a user in auth0 and return it as a dict to the caller.
Auth0 API doc: https://auth0.com/docs/api/management/v2
Auth0 API endpoint: PATCH /api/v2/users/{id}
Auth0 API parameters: id (user_id, required), body (required)
"""
payload = DotDict(dict())
assert type(new_profile) is dict
# Auth0 does not allow passing the user_id attribute
# as part of the payload (it's in the PATCH query already)
if 'user_id' in new_profile.keys():
del new_profile['user_id']
payload.app_metadata = new_profile
return self._request("/api/v2/users/{}".format(user_id),
"PATCH",
payload)
def get_access_token(self):
"""
Returns a JSON object containing an OAuth access_token.
This is also stored in this class other functions to use.
"""
payload = DotDict(dict())
payload.client_id = self.client_id
payload.client_secret = self.client_secret
payload.audience = "https://{}/api/v2/".format(self.uri)
payload.grant_type = "client_credentials"
ret = self._request("/oauth/token", "POST", payload, authorize=False)
access_token = DotDict(ret)
# Validation
if ('access_token' not in access_token.keys()):
raise Exception('InvalidAccessToken', access_token)
self.access_token = access_token.access_token
self.access_token_valid_until = time.time() + access_token.expires_in
self.access_token_scope = access_token.scope
return access_token
def _request(self, rpath, rtype="GET", payload=None, authorize=True):
if payload is None:
payload = {}
self.logger.debug('Sending Auth0 request {} {}'.format(rtype, rpath))
url = 'https://{}{}'.format(self.uri, rpath)
if authorize:
result = requests.request(rtype, url, json=payload, headers=self._authorize(self.default_headers))
else:
# Public req w/o oauth header
result = requests.request(rtype, url, json=payload, headers=self.default_headers)
try:
if not result.ok:
raise Exception('HTTPCommunicationFailed', (result.status_code, result.reason))
return result.json()
except ValueError:
return result.content
def _authorize(self, headers):
if not self.access_token:
raise Exception('InvalidAccessToken')
if self.access_token_auto_renew:
if self.access_token_valid_until < time.time() + self.access_token_auto_renew_leeway:
self.access_token = self.get_access_token()
elif self.access_token_valid_until < time.time():
raise Exception('InvalidAccessToken', 'The access token has expired')
local_headers = {}
local_headers.update(headers)
local_headers['Authorization'] = 'Bearer {}'.format(self.access_token)
return local_headers