This commit is contained in:
@@ -3,6 +3,7 @@ Authentication utilities for all services.
|
||||
This module provides common authentication functionality to avoid circular imports.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -14,6 +15,9 @@ from passlib.context import CryptContext
|
||||
|
||||
from shared.config import settings
|
||||
|
||||
# Suppress bcrypt version warnings
|
||||
logging.getLogger("passlib").setLevel(logging.ERROR)
|
||||
|
||||
# Password hashing
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
@@ -22,21 +26,30 @@ security = HTTPBearer()
|
||||
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""Verify password against hash. Apply same truncation as used during hashing."""
|
||||
# Apply same truncation logic as during hashing
|
||||
password_bytes = plain_password.encode('utf-8')
|
||||
if len(password_bytes) > 72:
|
||||
plain_password = password_bytes[:72].decode('utf-8', errors='ignore')
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
"""Verify a password against its hash. Handle bcrypt compatibility issues."""
|
||||
try:
|
||||
# Truncate password to 72 bytes for consistency
|
||||
password_bytes = plain_password.encode('utf-8')
|
||||
if len(password_bytes) > 72:
|
||||
plain_password = password_bytes[:72].decode('utf-8', errors='ignore')
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
except Exception as e:
|
||||
logging.error(f"Error verifying password: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Get password hash. Truncate password to 72 bytes if necessary for bcrypt compatibility."""
|
||||
# bcrypt has a 72-byte limit, so truncate if necessary
|
||||
password_bytes = password.encode('utf-8')
|
||||
if len(password_bytes) > 72:
|
||||
password = password_bytes[:72].decode('utf-8', errors='ignore')
|
||||
return pwd_context.hash(password)
|
||||
try:
|
||||
# bcrypt has a 72-byte limit, so truncate if necessary
|
||||
password_bytes = password.encode('utf-8')
|
||||
if len(password_bytes) > 72:
|
||||
password = password_bytes[:72].decode('utf-8', errors='ignore')
|
||||
return pwd_context.hash(password)
|
||||
except Exception as e:
|
||||
# Handle bcrypt compatibility issues
|
||||
logging.error(f"Error hashing password: {e}")
|
||||
raise ValueError("Password hashing failed. Please use a shorter password.")
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
|
||||
Reference in New Issue
Block a user