chaton2api1 / bearer_token.py
smgc's picture
Update bearer_token.py
647ab21 verified
raw
history blame
1.15 kB
import base64
import hashlib
import hmac
import time
from datetime import datetime, timezone
class BearerTokenGenerator:
SECRET_AUTH_PREFIX = bytes([252, 137, 185, 155, 127, 94, 106, 81, 69, 242, 189, 184, 26, 228, 174, 239])
SECRET_KEY = bytes([14, 94, 79, 102, 38, 245, 11, 65, 100, 43, 115, 94, 15, 241, 14, 16, 66, 129, 248, 226, 98, 109, 235, 60, 62, 41, 78, 29, 72, 181, 47, 8])
@staticmethod
def get_bearer(body: str, path: str = "/chats/stream") -> tuple:
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
prefix = f"POST:{path}:{timestamp}\n".encode()
to_sign = prefix + body.encode()
signature = BearerTokenGenerator.generate_signature(to_sign)
auth_prefix_base64 = base64.b64encode(BearerTokenGenerator.SECRET_AUTH_PREFIX).decode()
bearer_token = f"Bearer {auth_prefix_base64}.{signature}"
return bearer_token, timestamp
@staticmethod
def generate_signature(to_sign: bytes) -> str:
h = hmac.new(BearerTokenGenerator.SECRET_KEY, to_sign, hashlib.sha256)
return base64.b64encode(h.digest()).decode()