Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/a44a2797624c6f59e1c626fdbe060504 to your computer and use it in GitHub Desktop.
Save normanlmfung/a44a2797624c6f59e1c626fdbe060504 to your computer and use it in GitHub Desktop.
python_syntax_decorator_apiguard
# REST API guard: check api key (If incorrect API key, raise exception)
def check_api_key(api_key : str, request : Any, symmetric_key : str, kms_gizmo : Any):
def decorator(method):
headers = request.headers
encrypted_api_key_from_header = headers.get("X-Api-Key")
decrypted_api_key_from_header = encrypted_api_key_from_header
if kms_gizmo:
decrypted_api_key_from_header = kms_gizmo.decrypt(decrypted_api_key_from_header)
if symmetric_key:
decrypted_api_key_from_header = cipher_gizmo.decrypt(encrypted_text=decrypted_api_key_from_header, key=symmetric_key)
decrypted_api_key_from_header = decrypted_api_key_from_header.decode('utf-8')
logger.info(f"Remote address {request.remote_addr} calling {method}")
if decrypted_api_key_from_header != api_key:
url = request.url
code=HTTPStatus.UNAUTHORIZED
msg=f"Invalid api_key from remote_add: {request.remote_addr}. path: {request.path}"
hdrs = None
fp = None
raise HTTPError(url=url, code=code, msg=msg, hdrs=hdrs, fp=fp)
def wrapper(*args, **kw):
return method(*args, **kw)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment