Spaces:
Sleeping
Sleeping
from fastapi import Depends, HTTPException, status | |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
from global_state import get | |
from db.tbs_db import TbsDb | |
# 创建一个 HTTPBearer 实例 | |
security = HTTPBearer() | |
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)): | |
token = credentials.credentials | |
token = credentials.credentials | |
# 假设你有一个函数来验证Token并返回用户ID | |
user_id = validate_token(token) | |
if user_id is None: | |
raise HTTPException( | |
status_code=status.HTTP_401_UNAUTHORIZED, | |
detail="Invalid authentication credentials", | |
headers={"WWW-Authenticate": "Bearer"}, | |
) | |
return user_id | |
def validate_token(token: str): | |
db_module_filename = f"{get('project_root')}/db/cloudflare.py" | |
query = f"SELECT * FROM users where api_key='{token}'" | |
response = TbsDb(db_module_filename, "Cloudflare").get_item(query) | |
result = response['result'][0]['results'] | |
if len(result) == 0: | |
return None | |
user_id = result[0]['id'] | |
return user_id | |