96 lines
3.1 KiB
Python
96 lines
3.1 KiB
Python
"""
|
|
JWT 认证工具 + 密码哈希
|
|
"""
|
|
import hashlib
|
|
import secrets
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from jose import JWTError, jwt
|
|
from sqlalchemy.orm import Session
|
|
|
|
from .config import settings
|
|
from .database import get_db
|
|
from .models import User
|
|
|
|
# 使用 HTTP Bearer Token 认证
|
|
bearer_scheme = HTTPBearer(auto_error=False)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# 密码哈希(PBKDF2-SHA256,标准库实现,无需额外依赖)
|
|
# ------------------------------------------------------------------
|
|
_PBKDF2_ITERATIONS = 120_000
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""生成 '盐$哈希' 格式的密码摘要"""
|
|
salt = secrets.token_hex(16)
|
|
digest = hashlib.pbkdf2_hmac(
|
|
"sha256", password.encode("utf-8"), salt.encode("utf-8"), _PBKDF2_ITERATIONS
|
|
).hex()
|
|
return f"{salt}${digest}"
|
|
|
|
|
|
def verify_password(password: str, stored: str) -> bool:
|
|
"""校验明文密码与存储摘要是否匹配"""
|
|
try:
|
|
salt, digest = stored.split("$", 1)
|
|
except ValueError:
|
|
return False
|
|
candidate = hashlib.pbkdf2_hmac(
|
|
"sha256", password.encode("utf-8"), salt.encode("utf-8"), _PBKDF2_ITERATIONS
|
|
).hex()
|
|
return secrets.compare_digest(candidate, digest)
|
|
|
|
|
|
# ------------------------------------------------------------------
|
|
# JWT
|
|
# ------------------------------------------------------------------
|
|
def create_access_token(user_id: int, username: str) -> str:
|
|
"""生成 JWT token"""
|
|
expire = datetime.utcnow() + timedelta(days=settings.ACCESS_TOKEN_EXPIRE_DAYS)
|
|
payload = {
|
|
"sub": str(user_id),
|
|
"username": username,
|
|
"exp": expire,
|
|
}
|
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
|
|
|
|
|
def decode_token(token: str) -> Optional[dict]:
|
|
"""解码 token,失败返回 None"""
|
|
try:
|
|
return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
|
except JWTError:
|
|
return None
|
|
|
|
|
|
def get_current_user(
|
|
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
"""
|
|
FastAPI 依赖:从请求头解析 token 并返回当前用户。
|
|
未认证时抛出 401。
|
|
"""
|
|
if credentials is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="缺少认证 token",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
payload = decode_token(credentials.credentials)
|
|
if payload is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="token 无效或已过期",
|
|
)
|
|
user_id = int(payload.get("sub", 0))
|
|
user = db.query(User).filter(User.id == user_id).first()
|
|
if user is None or not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在或已禁用")
|
|
return user
|