from datetime import datetime, timedelta from typing import Optional from jose import JWTError, jwt from passlib.context import CryptContext from fastapi import HTTPException, Security, Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials import db SECRET_KEY = "your-secret-key-change-in-production" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") security = HTTPBearer() optional_security = HTTPBearer(auto_error=False) def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def create_access_token(data: dict): to_encode = data.copy() expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)): token = credentials.credentials try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: int = payload.get("id") if user_id is None: raise HTTPException(status_code=401, detail="无效的认证信息") except JWTError: raise HTTPException(status_code=403, detail="登录已过期,请重新登录") user = db.get_user_by_id(user_id) if user is None: raise HTTPException(status_code=404, detail="用户不存在") return user def get_optional_user(credentials: Optional[HTTPAuthorizationCredentials] = Depends(optional_security)): if not credentials: return None try: payload = jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM]) user_id = payload.get("id") if user_id: return db.get_user_by_id(user_id) except JWTError: return None return None