import json from flask import request from .jwt_handler import decode_jwt def check_jwt(): # get header and try to get payload # this will throw an exception if the payload is missing, invalid or expired token = request.headers.get('Authorization') if not token: raise Exception('Missing access token') jwt = token.split('Bearer ')[1] try: return decode_jwt(jwt) except Exception as e: raise Exception(f'invalid access token: {e}') # magic. use this to decorate the api calls # https://brunotatsuya.dev/blog/jwt-authentication-and-authorization-for-python-flask-rest-apis def auth_guard(role=None): def wrapper(route_function): def decorated_function(*args, **kwargs): # Authentication gate try: user_data = check_jwt() except Exception as e: return json.dumps({"message" : f'{e}', "status": 401}), 401 if role and role not in user_data['roles']: return json.dumps({"message": 'Authorization required.', "status" : 403}), 403 # get on to original route return route_function(*args, **kwargs) decorated_function.__name__ = route_function.__name__ return decorated_function return wrapper