smgc commited on
Commit
7dc6e35
·
verified ·
1 Parent(s): 647ab21

Update bearer_token.py

Browse files
Files changed (1) hide show
  1. bearer_token.py +17 -8
bearer_token.py CHANGED
@@ -1,26 +1,35 @@
 
1
  import base64
2
  import hashlib
3
  import hmac
4
- import time
5
  from datetime import datetime, timezone
6
 
7
  class BearerTokenGenerator:
8
- SECRET_AUTH_PREFIX = bytes([252, 137, 185, 155, 127, 94, 106, 81, 69, 242, 189, 184, 26, 228, 174, 239])
9
- 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])
10
-
11
  @staticmethod
12
  def get_bearer(body: str, path: str = "/chats/stream") -> tuple:
 
 
 
 
 
 
 
 
 
 
 
13
  timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
14
  prefix = f"POST:{path}:{timestamp}\n".encode()
15
  to_sign = prefix + body.encode()
16
 
17
- signature = BearerTokenGenerator.generate_signature(to_sign)
18
- auth_prefix_base64 = base64.b64encode(BearerTokenGenerator.SECRET_AUTH_PREFIX).decode()
19
 
20
  bearer_token = f"Bearer {auth_prefix_base64}.{signature}"
21
  return bearer_token, timestamp
22
 
23
  @staticmethod
24
- def generate_signature(to_sign: bytes) -> str:
25
- h = hmac.new(BearerTokenGenerator.SECRET_KEY, to_sign, hashlib.sha256)
26
  return base64.b64encode(h.digest()).decode()
 
1
+ import ast
2
  import base64
3
  import hashlib
4
  import hmac
5
+ import os
6
  from datetime import datetime, timezone
7
 
8
  class BearerTokenGenerator:
 
 
 
9
  @staticmethod
10
  def get_bearer(body: str, path: str = "/chats/stream") -> tuple:
11
+ # 从环境变量获取 SECRET_AUTH_PREFIX 和 SECRET_KEY
12
+ secret_auth_prefix_str = os.environ.get('SECRET_AUTH_PREFIX')
13
+ secret_key_str = os.environ.get('SECRET_KEY')
14
+
15
+ if not secret_auth_prefix_str or not secret_key_str:
16
+ raise ValueError("SECRET_AUTH_PREFIX or SECRET_KEY environment variables are not set")
17
+
18
+ # 将字符串转换为字节列表
19
+ secret_auth_prefix = bytes(ast.literal_eval(secret_auth_prefix_str))
20
+ secret_key = bytes(ast.literal_eval(secret_key_str))
21
+
22
  timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
23
  prefix = f"POST:{path}:{timestamp}\n".encode()
24
  to_sign = prefix + body.encode()
25
 
26
+ signature = BearerTokenGenerator.generate_signature(to_sign, secret_key)
27
+ auth_prefix_base64 = base64.b64encode(secret_auth_prefix).decode()
28
 
29
  bearer_token = f"Bearer {auth_prefix_base64}.{signature}"
30
  return bearer_token, timestamp
31
 
32
  @staticmethod
33
+ def generate_signature(to_sign: bytes, secret_key: bytes) -> str:
34
+ h = hmac.new(secret_key, to_sign, hashlib.sha256)
35
  return base64.b64encode(h.digest()).decode()