Spaces:
Sleeping
Sleeping
Update src/utils/security.py
Browse files- src/utils/security.py +17 -2
src/utils/security.py
CHANGED
|
@@ -25,13 +25,24 @@ except Exception as e:
|
|
| 25 |
|
| 26 |
|
| 27 |
def hash_password(password: str) -> str:
|
| 28 |
-
"""Hash a password using bcrypt."""
|
| 29 |
try:
|
| 30 |
# Truncate password to 72 bytes to avoid bcrypt limitation
|
| 31 |
if len(password.encode('utf-8')) > 72:
|
| 32 |
logger.warning("Password exceeds 72 bytes, truncating")
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
return pwd_context.hash(password)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
logger.error(f"Error hashing password: {str(e)}")
|
| 37 |
raise
|
|
@@ -40,6 +51,10 @@ def hash_password(password: str) -> str:
|
|
| 40 |
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 41 |
"""Verify a plain password against its hash."""
|
| 42 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
return pwd_context.verify(plain_password, hashed_password)
|
| 44 |
except Exception as e:
|
| 45 |
logger.error(f"Error verifying password: {str(e)}")
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
def hash_password(password: str) -> str:
|
| 28 |
+
"""Hash a password using bcrypt or fallback method."""
|
| 29 |
try:
|
| 30 |
# Truncate password to 72 bytes to avoid bcrypt limitation
|
| 31 |
if len(password.encode('utf-8')) > 72:
|
| 32 |
logger.warning("Password exceeds 72 bytes, truncating")
|
| 33 |
+
# Properly truncate UTF-8 bytes
|
| 34 |
+
password_bytes = password.encode('utf-8')[:72]
|
| 35 |
+
password = password_bytes.decode('utf-8', errors='ignore')
|
| 36 |
return pwd_context.hash(password)
|
| 37 |
+
except ValueError as ve:
|
| 38 |
+
if "72 bytes" in str(ve):
|
| 39 |
+
logger.error(f"Password too long even after truncation: {str(ve)}")
|
| 40 |
+
# Force truncate to exactly 72 bytes and try again
|
| 41 |
+
password = password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
|
| 42 |
+
return pwd_context.hash(password)
|
| 43 |
+
else:
|
| 44 |
+
logger.error(f"ValueError hashing password: {str(ve)}")
|
| 45 |
+
raise
|
| 46 |
except Exception as e:
|
| 47 |
logger.error(f"Error hashing password: {str(e)}")
|
| 48 |
raise
|
|
|
|
| 51 |
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
| 52 |
"""Verify a plain password against its hash."""
|
| 53 |
try:
|
| 54 |
+
# Truncate password to 72 bytes to match hashing behavior
|
| 55 |
+
if len(plain_password.encode('utf-8')) > 72:
|
| 56 |
+
logger.warning("Password exceeds 72 bytes during verification, truncating")
|
| 57 |
+
plain_password = plain_password.encode('utf-8')[:72].decode('utf-8', errors='ignore')
|
| 58 |
return pwd_context.verify(plain_password, hashed_password)
|
| 59 |
except Exception as e:
|
| 60 |
logger.error(f"Error verifying password: {str(e)}")
|