passlib 1.7.4 has a known bug with bcrypt 4.x on Python 3.13 where detect_wrap_bug passes an over-72-byte hash as a password, causing ValueError on every login attempt. Switched to bcrypt.hashpw/checkpw directly, removing the passlib dependency entirely. Also fixed 401 page reload on /auth/login endpoint. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
56 lines
1.9 KiB
Python
56 lines
1.9 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
from typing import Optional
|
|
import secrets
|
|
|
|
import bcrypt
|
|
from jose import JWTError, jwt
|
|
from fastapi import Request, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import JWT_SECRET, ACCESS_TOKEN_EXPIRE_MINUTES
|
|
from app.models.user_settings import UserSettings
|
|
from app.utils.logger import logger
|
|
|
|
ALGORITHM = "HS256"
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
to_encode = data.copy()
|
|
expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
|
|
to_encode.update({"exp": expire})
|
|
return jwt.encode(to_encode, JWT_SECRET, algorithm=ALGORITHM)
|
|
|
|
|
|
def decode_access_token(token: str) -> dict:
|
|
return jwt.decode(token, JWT_SECRET, algorithms=[ALGORITHM])
|
|
|
|
|
|
def get_current_user(request: Request) -> dict:
|
|
token = request.cookies.get("access_token", "")
|
|
if not token:
|
|
raise HTTPException(status_code=401, detail="未登录")
|
|
try:
|
|
payload = decode_access_token(token)
|
|
return payload
|
|
except JWTError:
|
|
raise HTTPException(status_code=401, detail="登录已过期,请重新登录")
|
|
|
|
|
|
def set_default_password(db: Session, settings: UserSettings):
|
|
if not settings.password_hash:
|
|
password = secrets.token_urlsafe(8)[:8]
|
|
settings.password_hash = hash_password(password)
|
|
db.commit()
|
|
logger.warning("=" * 50)
|
|
logger.warning(f" 初始密码: {password}")
|
|
logger.warning(" 请登录后立即修改!")
|
|
logger.warning("=" * 50)
|