fix: disable bcrypt truncate error

This commit is contained in:
gilesb
2026-01-07 15:53:46 +00:00
parent bfb94764e6
commit 290cb9cadc

13
auth.py
View File

@@ -16,8 +16,8 @@ from jose import JWTError, jwt
from pydantic import BaseModel
# Password hashing
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# Password hashing (truncate_error=False allows bcrypt to silently truncate)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto", bcrypt__truncate_error=False)
# JWT settings
ALGORITHM = "HS256"
@@ -93,14 +93,19 @@ def save_users(data_dir: Path, users: dict[str, dict]):
json.dump(users, f, indent=2)
def truncate_password(password: str) -> str:
"""Truncate password to 72 bytes for bcrypt."""
return password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
def hash_password(password: str) -> str:
"""Hash a password (truncate to 72 bytes for bcrypt)."""
return pwd_context.hash(password[:72])
return pwd_context.hash(truncate_password(password))
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify a password against its hash."""
return pwd_context.verify(plain_password[:72], hashed_password)
return pwd_context.verify(truncate_password(plain_password), hashed_password)
def create_user(data_dir: Path, username: str, password: str, email: Optional[str] = None) -> User: