File size: 1,145 Bytes
e51f077
647ab21
 
 
e51f077
 
 
647ab21
 
 
 
 
 
 
 
 
 
 
 
 
e51f077
 
647ab21
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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()