Work on API keys and tokens

This commit is contained in:
Scott Idem
2021-07-14 17:12:20 -04:00
parent 6f8e18750c
commit 6bb2d7f761
4 changed files with 212 additions and 6 deletions

View File

@@ -1,5 +1,5 @@
from __future__ import annotations
import datetime, pytz, redis
import datetime, jwt, pytz, redis, time
from passlib.hash import argon2
#from datetime import datetime, time, timedelta
@@ -45,8 +45,6 @@ async def get_account_header(x_account_id:str = Header(...)):
# ### END ### API Lib General ### async get_account_header() ###
def secure_hash_string(string:str):
string_hash = argon2.using(rounds=14, memory_cost=1536, parallelism=2).hash(string)
@@ -57,4 +55,55 @@ def verify_secure_hash_string(string:str, string_hash:str):
if argon2.verify(string, string_hash):
return True
else:
return False
return False
# Updated 2021-07-14
def sign_jwt(
secret_key: str, # Secret/Private/Password
public_key: str, # Will be part of the token. Use to look up secret when verifying.
ttl: int = 60, # Default to 60 seconds
max_renew: int = 0, # Default to 0
account_id: str = None,
person_id: str = None,
user_id: str = None,
) -> Dict[str, str]:
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
payload = {
'iat': time.time(), # Issued at
'eat': time.time() + ttl, # Expires at
'max_renew': max_renew, # Number of times allowed to request renew without API secret key
'public_key': public_key, # Use to lookup the secret/private/password key when verifying
'account_id': account_id,
'person_id': person_id,
'user_id': user_id,
}
secret = secret_key
algorithm = 'HS256'
token = jwt.encode(payload, secret, algorithm=algorithm)
log.debug(token)
return token
# Updated 2021-07-14
def decode_jwt(
secret_key: str,
token: str,
) -> dict:
log.setLevel(logging.DEBUG) # DEBUG, INFO, WARNING, ERROR, EXCEPTION, CRITICAL
log.debug(locals())
secret = secret_key
algorithm = 'HS256'
try:
decoded_token = jwt.decode(token, secret, algorithms=[algorithm])
log.debug(decoded_token)
if decoded_token['eat'] >= time.time(): return decoded_token
else: return False
except:
return None