"""Token verification functions.""" import binascii import hashlib import hmac from feature_fm import config from feature_fm.connectors.aws_secrets_manager import get_secret def sign_token(token, shared_secret): """Sign token with secret key. Args: token (bytes): the token to be signed shared_secret (bytes): the secret key to sign the token Returns: bytes: The signed token represented as hex """ token = hmac.new(shared_secret, token, hashlib.sha1).digest() return binascii.hexlify(token) def verify_token(token, signed_token): """Verify token. Args: token (bytes): the token to verify signed_token (bytes): The signed token Returns: boolean: flag that shows if the token is verified. """ secret = bytes( get_secret().get(config.SECRET_TOKEN_KEY).encode('utf-8')) token_to_verify = sign_token(token, secret) successful_verification_from_cache = hmac.compare_digest( token_to_verify, signed_token) if successful_verification_from_cache: return successful_verification_from_cache get_secret.cache_clear() secret = bytes( get_secret().get(config.SECRET_TOKEN_KEY).encode('utf-8')) token_to_verify = sign_token(token, secret) return hmac.compare_digest(token_to_verify, signed_token)