53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
from typing import Annotated, List, Optional
|
|
from fastapi import APIRouter, Depends, HTTPException, Header, status
|
|
from pydantic import BaseModel
|
|
|
|
router = APIRouter()
|
|
|
|
# 简易令牌验证(实际项目中应替换为 JWT/OAuth2 等)
|
|
AUTH_TOKEN = "567e33c876a2" # 预设的有效令牌
|
|
WHITE_LIST = ["/docs", "/openapi.json", "/redoc", "/api/v1/auth/login/"]
|
|
|
|
async def verify_token(authorization: Annotated[str, Header()] = None):
|
|
# 检查请求头是否存在
|
|
if not authorization:
|
|
raise HTTPException(status_code=401, detail="Authorization header missing")
|
|
|
|
# 提取 Bearer 后的令牌 (格式: Bearer <token>)
|
|
try:
|
|
token_type, token = authorization.split(" ", 1)
|
|
if token_type.lower() != "bearer":
|
|
raise ValueError
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=401, detail="Invalid authorization format. Use: Bearer <token>"
|
|
)
|
|
|
|
# 验证令牌
|
|
if token != AUTH_TOKEN:
|
|
raise HTTPException(status_code=403, detail="Invalid authentication token")
|
|
|
|
return True
|
|
|
|
def generate_access_token(username: str, password: str) -> str:
|
|
"""
|
|
根据用户名和密码生成JWT access token
|
|
|
|
参数:
|
|
username: 用户名
|
|
password: 密码
|
|
|
|
返回:
|
|
JWT access token字符串
|
|
"""
|
|
|
|
if username != "tjwater" or password != "tjwater@123":
|
|
raise ValueError("用户名或密码错误")
|
|
|
|
token = "567e33c876a2"
|
|
return token
|
|
|
|
@router.post("/login/")
|
|
async def login(username: str, password: str) -> str:
|
|
return generate_access_token(username, password)
|