返回提交历史
Modified
g4f/api/__init__.py
+17
-11
XFEstudio/gpt4free
Refactor update_headers function to accept new API key and adjust authorization handling
a869844c
代码差异
1 个文件
+17
-11
@@ -193,10 +193,10 @@ class AppConfig:
193
193
if value is not None:
194
194
setattr(cls, key, value)
195
195
196
def update_headers(request: Request, delete_authorization: bool = True, user: str = None) -> Request:
196
def update_headers(request: Request, new_api_key: str = None, user: str = None) -> Request:
197
197
new_headers = request.headers.mutablecopy()
198
if delete_authorization and "authorization" in new_headers:
199
del new_headers["authorization"]
198
if new_api_key:
199
new_headers["authorization"] = f"Bearer {new_api_key}"
200
200
if user:
201
201
new_headers["x-user"] = user
202
202
request.scope["headers"] = new_headers.raw
@@ -237,24 +237,26 @@ class Api:
237
237
async def authorization(request: Request, call_next):
238
238
user = None
239
239
if request.method != "OPTIONS" and AppConfig.g4f_api_key is not None or AppConfig.demo:
240
delete_authorization = False
240
update_authorization = False
241
241
try:
242
242
user_g4f_api_key = await self.get_g4f_api_key(request)
243
243
except HTTPException:
244
244
user_g4f_api_key = getattr(await self.security(request), "credentials", None)
245
delete_authorization = True
245
update_authorization = True
246
if user_g4f_api_key:
247
user_g4f_api_key = user_g4f_api_key.split()
246
248
country = request.headers.get("Cf-Ipcountry", "")
247
249
if AppConfig.demo and user is None:
248
250
ip = request.headers.get("X-Forwarded-For", "")[:4].strip(":.")
249
251
user = request.headers.get("x-user", ip)
250
252
user = f"{country}:{user}" if country else user
251
if AppConfig.g4f_api_key is None or not user_g4f_api_key or not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key):
253
if AppConfig.g4f_api_key is None or not user_g4f_api_key or not secrets.compare_digest(AppConfig.g4f_api_key, user_g4f_api_key[0]):
252
254
if has_crypto and user_g4f_api_key:
253
255
try:
254
expires, user = decrypt_data(private_key, user_g4f_api_key).split(":", 1)
256
expires, user = decrypt_data(private_key, user_g4f_api_key[0]).split(":", 1)
255
257
except:
256
258
try:
257
data = json.loads(decrypt_data(session_key, user_g4f_api_key))
259
data = json.loads(decrypt_data(session_key, user_g4f_api_key[0]))
258
260
debug.log(f"Decrypted G4F API key data: {data}")
259
261
expires = int(decrypt_data(private_key, data.pop("data"))) + 86400
260
262
user = data.get("user", user)
@@ -282,12 +284,12 @@ class Api:
282
284
path = request.url.path
283
285
if path.startswith("/v1") or path.startswith("/api/") or (AppConfig.demo and path == '/backend-api/v2/upload_cookies'):
284
286
if request.method != "OPTIONS" and not path.endswith("/models"):
285
if user_g4f_api_key is None:
287
if not user_g4f_api_key:
286
288
return ErrorResponse.from_message("G4F API key required", HTTP_401_UNAUTHORIZED)
287
289
if AppConfig.g4f_api_key is None and user is None:
288
290
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
289
291
elif not AppConfig.demo and not path.startswith("/images/") and not path.startswith("/media/"):
290
if user_g4f_api_key is not None:
292
if user_g4f_api_key:
291
293
if user is None:
292
294
return ErrorResponse.from_message("Invalid G4F API key", HTTP_403_FORBIDDEN)
293
295
elif path.startswith("/backend-api/") or path.startswith("/chat/"):
@@ -295,7 +297,11 @@ class Api:
295
297
user = await self.get_username(request)
296
298
except HTTPException as e:
297
299
return ErrorResponse.from_message(e.detail, e.status_code, e.headers)
298
request = update_headers(request, delete_authorization, user)
300
if user_g4f_api_key and update_authorization:
301
new_api_key = user_g4f_api_key.pop()
302
else:
303
new_api_key = None
304
request = update_headers(request, new_api_key, user)
299
305
response = await call_next(request)
300
306
return response
301
307