Spaces:
Sleeping
Sleeping
File size: 1,399 Bytes
2e76a54 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | from passlib.context import CryptContext
import bcrypt
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""
Verify a plaintext password against a hashed password.
"""
# Decode the hashed_password if it's in bytes format
if isinstance(hashed_password, str):
hashed_password = hashed_password.encode('utf-8')
if isinstance(plain_password, str):
plain_password = plain_password.encode('utf-8')
try:
# Try using passlib first
return pwd_context.verify(plain_password.decode('utf-8'), hashed_password.decode('utf-8'))
except:
# Fallback to bcrypt directly
return bcrypt.checkpw(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
"""
Generate a hash for a plaintext password.
Truncates password to 72 characters if needed for bcrypt compatibility.
"""
# Bcrypt has a maximum password length of 72 bytes
# Truncate if necessary to avoid ValueError
if len(password) > 72:
password = password[:72]
# Try using passlib first
try:
return pwd_context.hash(password)
except:
# Fallback to bcrypt directly
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
return hashed.decode('utf-8') |