2021-01-24 23:53:28 +01:00
|
|
|
import time
|
|
|
|
import connexion
|
2021-01-27 14:13:49 +01:00
|
|
|
from werkzeug.exceptions import Unauthorized, Forbidden
|
2021-01-24 23:53:28 +01:00
|
|
|
from jose import JWTError, jwt
|
|
|
|
import os
|
|
|
|
|
|
|
|
JWT_SECRET = os.environ['JWT_SECRET']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def decode_token(token):
|
|
|
|
try:
|
2021-01-27 14:13:49 +01:00
|
|
|
print("DEBUG decode_token: try to decode")
|
|
|
|
token_info = jwt.decode(token, JWT_SECRET)
|
|
|
|
print("DEBUG decode_token: token_info: {}".format(token_info))
|
|
|
|
return token_info
|
2021-01-24 23:53:28 +01:00
|
|
|
except JWTError as e:
|
2021-01-27 14:13:49 +01:00
|
|
|
print("ERROR decode_token: error when decoding token: {}".format(e))
|
|
|
|
raise Unauthorized()
|
|
|
|
|
|
|
|
def check_token(token, key, value):
|
|
|
|
if (key in token) and ((token[key] == value) or (isinstance(token[key], list) and (value in token[key]))):
|
|
|
|
return True
|
|
|
|
print("WARN: check_token: {} -> {} required but not granted".format(key, value))
|
|
|
|
raise Forbidden()
|
|
|
|
|
|
|
|
def check_scope(token, value):
|
|
|
|
if isinstance(value, list):
|
|
|
|
for v in value:
|
|
|
|
check_token(token, "x-scope", v)
|
|
|
|
else:
|
|
|
|
check_token(token, "x-scope", value)
|
2021-01-24 23:53:28 +01:00
|
|
|
|
|
|
|
def get_secret(user, token_info) -> str:
|
|
|
|
return '''
|
|
|
|
You are user_id {user} and the secret is 'wbevuec'.
|
|
|
|
Decoded token claims: {token_info}.
|
|
|
|
'''.format(user=user, token_info=token_info)
|
|
|
|
|
|
|
|
|
2021-01-27 14:13:49 +01:00
|
|
|
|
2021-01-24 23:53:28 +01:00
|
|
|
def _current_timestamp() -> int:
|
|
|
|
return int(time.time())
|
|
|
|
|