This commit is contained in:
@@ -18,8 +18,13 @@ from shared.config import settings
|
||||
# Suppress bcrypt version warnings
|
||||
logging.getLogger("passlib").setLevel(logging.ERROR)
|
||||
|
||||
# Password hashing
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
# Password hashing - настройка bcrypt с более надежными параметрами
|
||||
pwd_context = CryptContext(
|
||||
schemes=["bcrypt"],
|
||||
deprecated="auto",
|
||||
bcrypt__rounds=12, # Стандартное количество раундов
|
||||
bcrypt__truncate_error=False # Не вызывать ошибку при длинных паролях, а просто обрезать
|
||||
)
|
||||
|
||||
# Bearer token scheme
|
||||
security = HTTPBearer()
|
||||
@@ -28,29 +33,32 @@ security = HTTPBearer()
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
"""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)
|
||||
# Увеличим подробность логов
|
||||
logging.info(f"Verifying password length: {len(plain_password)} chars")
|
||||
|
||||
# Проверяем пароль с помощью passlib и логируем результат
|
||||
result = pwd_context.verify(plain_password, hashed_password)
|
||||
logging.info(f"Password verification result: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logging.error(f"Error verifying password: {e}")
|
||||
logging.error(f"Error verifying password: {e}, hash_type: {hashed_password[:10]}...")
|
||||
return False
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Get password hash. Truncate password to 72 bytes if necessary for bcrypt compatibility."""
|
||||
"""Get password hash. Let passlib handle bcrypt compatibility."""
|
||||
try:
|
||||
# bcrypt has a 72-byte limit, so truncate if necessary
|
||||
password_bytes = password.encode('utf-8')
|
||||
if len(password_bytes) > 72:
|
||||
logging.warning("Password exceeds bcrypt limit of 72 bytes. Truncating.")
|
||||
password = password_bytes[:70].decode('utf-8', errors='ignore')
|
||||
return pwd_context.hash(password)
|
||||
# Увеличим подробность логов
|
||||
logging.info(f"Hashing password length: {len(password)} chars")
|
||||
|
||||
# bcrypt автоматически ограничит длину пароля до 72 байт
|
||||
hashed = pwd_context.hash(password)
|
||||
logging.info("Password hashed successfully")
|
||||
return hashed
|
||||
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.")
|
||||
raise ValueError(f"Password hashing failed: {str(e)}")
|
||||
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
||||
|
||||
@@ -41,6 +41,11 @@ class Settings(BaseSettings):
|
||||
|
||||
# External Services
|
||||
FCM_SERVER_KEY: Optional[str] = None
|
||||
|
||||
# FatSecret API для данных о питании
|
||||
FATSECRET_CLIENT_ID: str = "56342dd56fc74b26afb49d65b8f84c16"
|
||||
FATSECRET_CLIENT_SECRET: str = "fae178f189dc44ddb368cabe9069c0e3"
|
||||
FATSECRET_CUSTOMER_KEY: Optional[str] = None # Исправляем опечатку в имени параметра
|
||||
|
||||
# Security
|
||||
CORS_ORIGINS: list = ["*"] # Change in production
|
||||
|
||||
Reference in New Issue
Block a user