1616# Get Supabase configuration
1717SUPABASE_URL = os .getenv ('SUPABASE_URL' , 'http://118.31.249.152:8010' )
1818SUPABASE_KEY = os .getenv ('SUPABASE_KEY' , '' )
19- # 调试用 JWT 过期时间(秒),未设置或为 0 表示不生效
19+ # Debug JWT expiration time (seconds), not set or 0 means not effective
2020DEBUG_JWT_EXPIRE_SECONDS = int (os .getenv ('DEBUG_JWT_EXPIRE_SECONDS' , '0' ) or 0 )
2121
2222# Module logger
@@ -115,7 +115,8 @@ def verify_aksk_signature(
115115 raise SignatureValidationError ("Timestamp is invalid or expired" )
116116
117117 # TODO: get ak/sk according to tenant_id from DB
118- mock_access_key , mock_secret_key = get_aksk_config (tenant_id = "tenant_id" )
118+ mock_access_key , mock_secret_key = get_aksk_config (
119+ tenant_id = "tenant_id" )
119120
120121 if access_key != mock_access_key :
121122 logger .warning (f"Invalid access key: { access_key } " )
@@ -199,62 +200,64 @@ def validate_aksk_authentication(headers: dict, request_body: str = "") -> bool:
199200 logger .error (f"Unexpected error during AK/SK authentication: { e } " )
200201 raise UnauthorizedError ("Authentication failed" )
201202
203+
202204def get_supabase_client ():
203205 """Get Supabase client instance"""
204206 try :
205207 return create_client (SUPABASE_URL , SUPABASE_KEY )
206208 except Exception as e :
207- logging .error (f"创建Supabase客户端失败 : { str (e )} " )
209+ logging .error (f"Failed to create Supabase client : { str (e )} " )
208210 return None
209211
210212
211213def get_jwt_expiry_seconds (token : str ) -> int :
212214 """
213- 从JWT令牌中获取过期时间(秒)
215+ Get expiration time from JWT token (seconds)
214216
215217 Args:
216- token: JWT令牌字符串
218+ token: JWT token string
217219
218220 Returns:
219- int: 令牌的有效期(秒),如果解析失败则返回默认值3600
221+ int: Token validity period (seconds), returns default value 3600 if parsing fails
220222 """
221223 try :
222224 # Speed mode: treat sessions as never expiring
223225 if IS_SPEED_MODE :
224226 # 10 years in seconds
225227 return 10 * 365 * 24 * 60 * 60
226- # 确保token是纯JWT,去除可能的Bearer前缀
227- jwt_token = token .replace ("Bearer " , "" ) if token .startswith ("Bearer " ) else token
228+ # Ensure token is pure JWT, remove possible Bearer prefix
229+ jwt_token = token .replace (
230+ "Bearer " , "" ) if token .startswith ("Bearer " ) else token
228231
229- # 如果设置了调试过期时间,直接返回以便快速调试
232+ # If debug expiration time is set, return directly for quick debugging
230233 if DEBUG_JWT_EXPIRE_SECONDS > 0 :
231234 return DEBUG_JWT_EXPIRE_SECONDS
232235
233- # 解码JWT令牌(不验证签名,只解析内容 )
236+ # Decode JWT token (without signature verification, only parse content )
234237 decoded = jwt .decode (jwt_token , options = {"verify_signature" : False })
235238
236- # 从JWT声明中提取过期时间和签发时间
239+ # Extract expiration time and issued time from JWT claims
237240 exp = decoded .get ("exp" , 0 )
238241 iat = decoded .get ("iat" , 0 )
239242
240- # 计算有效期(秒)
243+ # Calculate validity period (seconds)
241244 expiry_seconds = exp - iat
242245
243246 return expiry_seconds
244247 except Exception as e :
245- logging .warning (f"从令牌获取过期时间失败 : { str (e )} " )
246- return 3600 # supabase默认设置
248+ logging .warning (f"Failed to get expiration time from token : { str (e )} " )
249+ return 3600 # supabase default setting
247250
248251
249252def calculate_expires_at (token : Optional [str ] = None ) -> int :
250253 """
251- 计算会话过期时间(与Supabase JWT过期时间保持一致)
254+ Calculate session expiration time (consistent with Supabase JWT expiration time)
252255
253256 Args:
254- token: 可选的JWT令牌,用于获取实际过期时间
257+ token: Optional JWT token to get actual expiration time
255258
256259 Returns:
257- int: 过期时间的时间戳
260+ int: Expiration time timestamp
258261 """
259262 # Speed mode: far future expiration
260263 if IS_SPEED_MODE :
@@ -275,13 +278,14 @@ def _extract_user_id_from_jwt_token(authorization: str) -> Optional[str]:
275278 Optional[str]: User ID, return None if parsing fails
276279 """
277280 try :
278- # 格式化授权头部
279- token = authorization .replace ("Bearer " , "" ) if authorization .startswith ("Bearer " ) else authorization
281+ # Format authorization header
282+ token = authorization .replace ("Bearer " , "" ) if authorization .startswith (
283+ "Bearer " ) else authorization
280284
281- # 解码JWT令牌(不验证签名,只解析内容 )
285+ # Decode JWT token (without signature verification, only parse content )
282286 decoded = jwt .decode (token , options = {"verify_signature" : False })
283287
284- # 从JWT声明中提取用户ID
288+ # Extract user ID from JWT claims
285289 user_id = decoded .get ("sub" )
286290
287291 return user_id
@@ -302,7 +306,8 @@ def get_current_user_id(authorization: Optional[str] = None) -> tuple[str, str]:
302306 """
303307 # if deploy in speed mode or authorization is None, return default user id and tenant id
304308 if IS_SPEED_MODE or authorization is None :
305- logging .debug ("Speed mode or no valid authorization header detected - returning default user ID and tenant ID" )
309+ logging .debug (
310+ "Speed mode or no valid authorization header detected - returning default user ID and tenant ID" )
306311 return DEFAULT_USER_ID , DEFAULT_TENANT_ID
307312
308313 try :
@@ -316,12 +321,13 @@ def get_current_user_id(authorization: Optional[str] = None) -> tuple[str, str]:
316321 logging .debug (f"Found tenant ID for user { user_id } : { tenant_id } " )
317322 else :
318323 tenant_id = DEFAULT_TENANT_ID
319- logging .warning (f"No tenant relationship found for user { user_id } , using default tenant" )
324+ logging .warning (
325+ f"No tenant relationship found for user { user_id } , using default tenant" )
320326
321327 return user_id , tenant_id
322328
323329 except Exception as e :
324- logging .error (f"Failed to get user ID and tanent ID: { str (e )} " )
330+ logging .error (f"Failed to get user ID and tenant ID: { str (e )} " )
325331 raise UnauthorizedError ("Invalid or expired authentication token" )
326332
327333
0 commit comments