api-mapper / auth.py
tanbushi's picture
mvp ok
10bcd3f
raw
history blame
1.17 kB
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from global_state import get
from db.tbs_db import TbsDb
from db_model.user import UserModel
# 创建一个 HTTPBearer 实例
security = HTTPBearer()
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
token = credentials.credentials
# 假设你有一个函数来验证Token并返回用户
user = validate_token(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
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)
if response is None:
return None
result = response['result'][0]['results']
if len(result) == 0:
return None
result = result[0]
result=UserModel(**result)
return result