-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.py
More file actions
435 lines (335 loc) · 15.4 KB
/
helpers.py
File metadata and controls
435 lines (335 loc) · 15.4 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
from flask import request, url_for, make_response, jsonify, current_app
from werkzeug.wrappers import Response
from functools import wraps
from jose import jwt
from urllib.request import urlopen
import base64
from os import environ as env
import json
from uuid import UUID, uuid4
from datetime import datetime, time
from common.services import auth0management
import flask_limiter
import re
import marshmallow
import marshmallow_sqlalchemy
from common.constants import AuthType, API_DATATYPE_HEADER, API_DATATYPE
from common.db_schema import db
from common.exceptions import Oops, AuthError
AUTH0_DOMAIN = env.get("AUTH0_DOMAIN")
API_IDENTIFIER = env.get("API_IDENTIFIER")
ALGORITHMS = ["RS256"]
try:
#TODO: remove dependency on setting up auth0 to test the API
management_API = auth0management.Auth0ManagementService()
except Exception as e:
current_app.logger.error(e)
#TODO: need to implement better logging.
current_app.logger.warning('Auth0 is not configured correctly. Access control for requests will not be enforced.')
management_API = None
class JSONEncoder(json.JSONEncoder):
# this was copied from https://github.com/miLibris/flask-rest-jsonapi/blob/ad3f90f81955fa41aaf0fb8c49a75a5fbe334f5f/flask_rest_jsonapi/utils.py under the terms of the MIT license.
def default(self, obj):
if isinstance(obj, (datetime, time)):
return obj.isoformat()
elif isinstance(obj, UUID):
return obj.hex
elif isinstance(obj, bytearray):
return obj.decode()
return json.JSONEncoder.default(self, obj)
# status code helpers taken from https://github.com/flask-api/flask-api/blob/master/flask_api/status.py
def is_informational(code):
return code >= 100 and code <= 199
def is_success(code):
return code >= 200 and code <= 299
def is_redirect(code):
return code >= 300 and code <= 399
def is_client_error(code):
return code >= 400 and code <= 499
def is_server_error(code):
return code >= 500 and code <= 599
def register_api(api, resource, api_version, name_of_optional_param='id', type_of_optional_param='string', url_prefix=""):
name = resource.__name__.lower()
url = "/" + name + "/"
plural_url = "/" + name + "s/"
version = api_version + "_"
api.add_resource(
resource,
url_prefix + plural_url,
endpoint=version + name + "_list",
defaults={name_of_optional_param: None},
methods=['GET', ]
)
api.add_resource(
resource,
url_prefix + plural_url,
endpoint=version + "new_" + name,
methods=['POST', ]
)
api.add_resource(
resource,
'%s<%s:%s>/' % (url_prefix + url, type_of_optional_param,
name_of_optional_param),
endpoint=version + "single_" + name,
methods=['GET', 'PUT', 'PATCH', 'DELETE']
)
def make_error_object(code, error_id=None, title=None, message=None):
""" Generates an error response object
Arguments:
code {number} -- The HTTP status code to return for the error; both through HTTP and in the JSON response.
Keyword Arguments:
title {string} -- An optional title for the error (i.e. "Unauthorized", "Access Denied") (default: {None})
message {string} -- An optional message giving more details about the error (default: {None})
Returns:
an error JSON object
"""
error_data = {'status': str(code)}
if error_id is not None:
error_data['id'] = error_id
if title is not None:
error_data['title'] = title
if message is not None:
error_data['detail'] = message
return error_data
def respond(response_data=None, code=200, headers=API_DATATYPE_HEADER):
""" Forms the data into a JSON response
Arguments:
response_data {dict} -- The object dict to return in the JSON response
Keyword Arguments:
code {number} -- The optional HTTP status code to return with the response (used for errors) (default: {None})
headers {dict} -- A dict of optional headers to add to the response
Returns:
A flask Response object for the web server
"""
content = {}
if code is not None and (is_client_error(code) or is_server_error(code)):
# error
content['errors'] = response_data
else:
content["data"] = response_data
#TODO: handle if response_data is none (i.e. in case of 304 not modified)
if code is None:
return make_response(json.dumps(content, cls=JSONEncoder), headers)
else:
return make_response(json.dumps(content, cls=JSONEncoder), code, headers)
def trap_object_modified_since(obj_last_modification, since):
""" checks the If-Modified-Since header checks it to ensure that there is no data loss
:type obj_last_modification: datetime
:param obj_last_modification: the last modification time of the object being checked
:type since: datetime
:param since: the value of the header
:raises: Oops
:rtype: None
"""
if since > datetime.now():
raise Oops("The date provided to the If-Modified-Since header cannot be in the future", 412, title="No Future Modification Dates")
if since < obj_last_modification:
raise Oops("The resource you are trying to change has been modified elsewhere", 412, title="Resource has been Modified")
def handle_marshmallow_errors(errors):
error_list = []
for property_name, property_errors in errors.items():
for value_type, input_errors in property_errors.items():
for input_error in input_errors:
message = input_error[:-1] + " provided to " + \
property_name + " of type " + value_type
error = make_error_object(
400, title="Validation failure", message=message)
error_list.append(error)
return error_list, 400
def get_request_body(request):
"""
provides a central place to modify the data in the request body
"""
return request.get_json()
def get_api_client_id():
"""Returns a string to group API calls together for the purposes of ratelimiting
"""
# print(client_id)
# print(type(client_id))
if hasattr(g._classclock_auth0_current_user_payload, 'current_user'):
# get the "authorized party" field of the auth token payload (which should be the client ID)
return g._classclock_auth0_current_user_payload.current_user["azp"]
else:
return "Public" # this is just a generic string to lump all unauthenticated requests together and ratelimit as one
def get_api_user_id():
"""Returns the id of the user for whom data is being accessed on behalf of
This is only set for requests to endpoints using the @requires_auth decorator
"""
if hasattr(g._classclock_auth0_current_user_payload, 'current_user'):
raw_id = g._classclock_auth0_current_user_payload.current_user["sub"]
if raw_id.endswith("@clients"):
return ""
else:
return raw_id
else:
return ""
def get_token_auth_header():
return get_valid_auth_header_of_type(AuthType.TOKEN)
def get_valid_auth_header_of_type(auth_header_type):
"""Obtains a valid Authorization Header value
"""
auth = request.headers.get("Authorization", None)
if not auth:
raise AuthError("Authorization header is expected", 401)
parts = auth.split()
if parts[0].lower() != auth_header_type.value.lower():
raise AuthError("Authorization header value must start with " +
auth_header_type.value, 401)
if len(parts) == 1:
raise AuthError("Authorization header value is missing", 401)
elif len(parts) > 2:
raise AuthError("Authorization header must be in the format \"" +
auth_header_type.value + " [value]\"", 401)
return parts[1] # return the value provided with the token
def check_permissions(user, permissions_to_check):
"""Raises an AuthError if the specified scopes are not present
Arguments:
scope {string[]} -- A list of scopes to check
Raises:
AuthError: An authentication error
"""
# g._classclock_auth0_current_user_payload.current_user
perms_not_present = []
for perm in permissions_to_check:
if perm.value not in user['permissions']:
perms_not_present.append(perm)
if perms_not_present != []:
perms_needed = " ".join(perm.value for perm in perms_not_present)
raise AuthError(
"You have not been granted the necessary permissions to access to this resource. You are missing the following permissions: " + perms_needed, 403)
def check_for_roles(roles:list, accept_any=True):
"""Performs a simple, stupid, name-based check against the roles that a user has.
This must be used after the @requires_auth decorator is applied
Args:
roles (list): a list of names of roles to check
accept_any (boolean): True to accept ANY of the provided roles. False to accept only ALL provided roles. Defaults to True.
Returns:
bool: true if the user has any of the roles provided, false if the user has none of them, and None if there is no currently authenticated user
"""
user_id = get_api_user_id()
#TODO: make management API optional and check if it is present
if management_API is None:
#TODO: need to implement better logging.
current_app.logger.warning("Because Auth0 is not configured correctly, access control is not being enforced. All requests to check a users role will automatically pass.")
return True
if user_id != "":
roles_json = management_API.get_roles_for_user(user_id)
# current_app.logger.info(roles_json)
user_role_names = [r["name"].lower() for r in roles_json]
user_role_names = set(user_role_names)
requested_roles = set([r.lower() for r in roles])
required_threshold = 1 if accept_any else len(requested_roles)
return len(requested_roles & user_role_names) >= required_threshold
else:
return None
def check_ownership(school):
if get_api_user_id() not in school.owner_id:
raise Oops("Authorizing user does not have permission to access the requested school", 401)
def list_owned_school_ids(cursor, school_id):
#TODO: remove manual SQL, also this is like horrifically broken
cursor.execute(
"SELECT UNHEX(school_id) as id FROM schools WHERE owner_id=%s", (school_id,))
# dict_keys_map defines the keys for the dictionary that is generated from the tuples returned from the database (so order matters)
# dict_keys_map = ("id", "full_name", "acronym")
return [sch_id[0] for sch_id in cursor]
#
# Decorators
#
def requires_auth(_func=None, *, permissions=None):
"""Determines if the access token is valid
"""
# https://realpython.com/primer-on-python-decorators/#decorators-with-arguments
def args_or_no(func):
@wraps(func)
def decorated(*args, **kwargs):
if not management_API:
#TODO: need to implement better logging.
current_app.logger.warning("Because Auth0 is not configured correctly, access control is not being enforced. All requests to protected endpoints will automatically succeed.")
return func(*args, **kwargs)
token = get_token_auth_header()
jsonurl = urlopen("https://"+AUTH0_DOMAIN+"/.well-known/jwks.json")
jwks = json.loads(jsonurl.read())
try:
unverified_header = jwt.get_unverified_header(token)
except jwt.JWTError:
raise AuthError(
"Invalid token. Use an RS256 signed JWT Access Token", 401)
if unverified_header["alg"] == "HS256":
raise AuthError(
"Invalid token algorithm. Use an RS256 signed JWT Access Token", 401)
rsa_key = {}
for key in jwks["keys"]:
if key["kid"] == unverified_header["kid"]:
rsa_key = {
"kty": key["kty"],
"kid": key["kid"],
"use": key["use"],
"n": key["n"],
"e": key["e"]
}
if rsa_key:
try:
payload = jwt.decode(
token,
rsa_key,
algorithms=ALGORITHMS,
audience=API_IDENTIFIER,
issuer="https://"+AUTH0_DOMAIN+"/"
)
except jwt.ExpiredSignatureError:
raise AuthError("Token has expired", 401)
except jwt.JWTClaimsError:
raise AuthError(
"Incorrect JWT claims. Please check the audience and issuer", 401)
except Exception:
raise AuthError("Unable to parse authentication token.", 401)
g._classclock_auth0_current_user_payload = payload
current_app.logger.info( "Successfully authenticated user '" + get_api_user_id() + "'" )
#this permissions check was added separately from the auth0 validation code
if permissions is not None:
check_permissions(payload, permissions)
return func(*args, **kwargs)
raise AuthError("Unable to find appropriate key", 401)
return decorated
if _func is None:
return args_or_no
else:
return args_or_no(_func)
def requires_admin(f):
"""Determines if the user has the correct admin permissions for an action
"""
@wraps(f)
def decorated(*args, **kwargs):
is_admin = check_for_roles(["admin", "school admin"])
if is_admin is None:
raise Oops("There must be a user signed in to perform this action",
400, title="No User Authorization")
elif not is_admin:
raise Oops("Authorizing user does not have the correct role to perform this action",
401, title="Incorrect User Role")
else:
return f(*args, **kwargs)
return decorated
# decorator modified from https://github.com/miLibris/flask-rest-jsonapi/blob/ad3f90f81955fa41aaf0fb8c49a75a5fbe334f5f/flask_rest_jsonapi/decorators.py
def check_headers(func):
"""decorator that provides a place to check headers
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
if request.method in ('POST', 'PATCH', 'PUT'):
if 'Content-Type' in request.headers and request.headers['Content-Type'] != API_DATATYPE:
error = make_error_object(
message='Content-Type header must be ' + API_DATATYPE, title='Invalid request header', code=415)
return respond(response_data=error, code=415)
if 'Accept' in request.headers:
for accept in request.headers['Accept'].split(','):
if accept.strip() != API_DATATYPE:
#this will error if any of the accept headers is not correct...
#TODO
error = make_error_object(
message='Accept header must be ' + API_DATATYPE, title='Invalid request header', code=406)
return respond(response_data=error, code=406)
return func(*args, **kwargs)
return wrapper