64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
"""JWT 认证 + 权限控制"""
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from sqlalchemy.orm import Session
|
|
from database import get_db
|
|
from config import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES
|
|
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return pwd_context.verify(plain, hashed)
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
|
to_encode.update({"exp": expire})
|
|
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
|
|
"""从 JWT token 解析当前用户"""
|
|
from models import User
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="登录已过期,请重新登录",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
try:
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
sub = payload.get("sub")
|
|
if sub is None:
|
|
raise credentials_exception
|
|
user_id = int(sub)
|
|
except (JWTError, ValueError, TypeError):
|
|
raise credentials_exception
|
|
|
|
user = db.query(User).filter(User.id == user_id).first()
|
|
if user is None or not user.is_active:
|
|
raise credentials_exception
|
|
return user
|
|
|
|
|
|
def require_permission(*perms: str):
|
|
"""权限校验依赖:要求当前用户拥有指定权限中的至少一项"""
|
|
def perm_checker(current_user=Depends(get_current_user)):
|
|
if not current_user.role_ref:
|
|
raise HTTPException(status_code=403, detail="未分配角色")
|
|
user_perms = current_user.permissions or []
|
|
if not any(p in user_perms for p in perms):
|
|
raise HTTPException(status_code=403, detail="权限不足")
|
|
return current_user
|
|
return perm_checker
|