This commit is contained in:
2026-09-16 17:55:04 +08:00
parent 3f120417d1
commit 4537faf2c4
39 changed files with 986 additions and 423 deletions
+19 -4
View File
@@ -20,13 +20,28 @@ pwd_context = bcrypt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
def _require_secret_key() -> str:
"""SECRET_KEY 惰性校验:未配置时给出明确错误,而不是让 jwt.encode/decode 报晦涩 TypeError。"""
if not settings.SECRET_KEY:
raise RuntimeError("SECRET_KEY 未配置:请在 .env 中设置后重启服务(认证功能不可用)")
return settings.SECRET_KEY
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
# 比较侧按 bcrypt 语义截断到 72 字节:兼容历史上被截断存储的口令,
# 且避免 checkpw 对超长输入直接抛 ValueError(登录会变 500);
# 新口令的超长拒绝在 get_password_hash 中完成
password_bytes = plain_password.encode('utf-8')[:72]
try:
return pwd_context.checkpw(password_bytes, hashed_password.encode('utf-8'))
except ValueError:
return False
def get_password_hash(password: str) -> str:
# bcrypt 算法上限 72 字节:超长密码必须显式拒绝,静默截断会改变有效密码
if len(password.encode('utf-8')) > 72:
password = password[:72]
raise ValueError("密码长度超过 72 字节限制,请使用更短的密码")
return pwd_context.hashpw(password.encode('utf-8'), pwd_context.gensalt()).decode('utf-8')
@@ -37,7 +52,7 @@ def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -
else:
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
encoded_jwt = jwt.encode(to_encode, _require_secret_key(), algorithm=settings.ALGORITHM)
return encoded_jwt
@@ -49,7 +64,7 @@ async def get_current_user(
return None
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
payload = jwt.decode(token, _require_secret_key(), algorithms=[settings.ALGORITHM])
username: str = payload.get("sub")
if username is None:
logger.warning(f"[AUTH] Token 中缺少 sub 字段")