Версия 0.0.3
This commit is contained in:
parent
413e9c57be
commit
8c7d0609df
189 changed files with 52063 additions and 2769 deletions
|
|
@ -9,6 +9,7 @@ from models.auth import UserCreate, UserResponse
|
|||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class JsonStorage:
|
||||
"""Хранилище пользователей в JSON-файле"""
|
||||
|
||||
|
|
@ -22,7 +23,8 @@ class JsonStorage:
|
|||
try:
|
||||
logger.info(f"Проверка существования файла {self.file_path}")
|
||||
if not os.path.exists(self.file_path):
|
||||
logger.info(f"Создание директории {os.path.dirname(self.file_path)}")
|
||||
logger.info(
|
||||
f"Создание директории {os.path.dirname(self.file_path)}")
|
||||
os.makedirs(os.path.dirname(self.file_path), exist_ok=True)
|
||||
logger.info(f"Создание файла {self.file_path}")
|
||||
with open(self.file_path, "w") as f:
|
||||
|
|
@ -32,7 +34,9 @@ class JsonStorage:
|
|||
else:
|
||||
logger.info(f"Файл {self.file_path} уже существует")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании файла {self.file_path}: {type(e).__name__} - {str(e)}")
|
||||
logger.error(
|
||||
f"Ошибка при создании файла {self.file_path}: {type(e).__name__} - {str(e)}"
|
||||
)
|
||||
raise
|
||||
|
||||
def _read_data(self) -> dict:
|
||||
|
|
@ -41,10 +45,14 @@ class JsonStorage:
|
|||
with open(self.file_path, "r") as f:
|
||||
return json.load(f)
|
||||
except FileNotFoundError:
|
||||
logger.info(f"Файл {self.file_path} не существует, возвращаем пустую структуру")
|
||||
logger.info(
|
||||
f"Файл {self.file_path} не существует, возвращаем пустую структуру"
|
||||
)
|
||||
return {"users": [], "next_id": 1}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при чтении файла {self.file_path}: {type(e).__name__} - {str(e)}")
|
||||
logger.error(
|
||||
f"Ошибка при чтении файла {self.file_path}: {type(e).__name__} - {str(e)}"
|
||||
)
|
||||
raise
|
||||
|
||||
def _write_data(self, data: dict):
|
||||
|
|
@ -53,7 +61,9 @@ class JsonStorage:
|
|||
with open(self.file_path, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при записи файла {self.file_path}: {type(e).__name__} - {str(e)}")
|
||||
logger.error(
|
||||
f"Ошибка при записи файла {self.file_path}: {type(e).__name__} - {str(e)}"
|
||||
)
|
||||
raise
|
||||
|
||||
def create_user(self, user: UserCreate) -> UserResponse:
|
||||
|
|
@ -70,22 +80,31 @@ class JsonStorage:
|
|||
"id": next_id,
|
||||
"username": user.username,
|
||||
"password_hash": password_hash,
|
||||
"is_admin": user.is_admin
|
||||
"is_admin": user.is_admin,
|
||||
}
|
||||
users.append(new_user)
|
||||
data["next_id"] = next_id + 1
|
||||
self._write_data(data)
|
||||
logger.info(f"Пользователь {user.username} успешно зарегистрирован")
|
||||
return UserResponse(id=new_user["id"], username=new_user["username"], is_admin=new_user["is_admin"])
|
||||
logger.info(
|
||||
f"Пользователь {user.username} успешно зарегистрирован")
|
||||
return UserResponse(
|
||||
id=new_user["id"],
|
||||
username=new_user["username"],
|
||||
is_admin=new_user["is_admin"],
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при создании пользователя {user.username}: {type(e).__name__} - {str(e)}")
|
||||
logger.error(
|
||||
f"Ошибка при создании пользователя {user.username}: {type(e).__name__} - {str(e)}"
|
||||
)
|
||||
raise
|
||||
|
||||
def get_user_by_username(self, username: str) -> Optional[dict]:
|
||||
"""Получает пользователя по имени"""
|
||||
try:
|
||||
if not os.path.exists(self.file_path):
|
||||
logger.info(f"Файл {self.file_path} не существует, пользователь {username} не найден")
|
||||
logger.info(
|
||||
f"Файл {self.file_path} не существует, пользователь {username} не найден"
|
||||
)
|
||||
return None
|
||||
data = self._read_data()
|
||||
for user in data["users"]:
|
||||
|
|
@ -93,9 +112,12 @@ class JsonStorage:
|
|||
return user
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при получении пользователя {username}: {type(e).__name__} - {str(e)}")
|
||||
logger.error(
|
||||
f"Ошибка при получении пользователя {username}: {type(e).__name__} - {str(e)}"
|
||||
)
|
||||
raise
|
||||
|
||||
def verify_password(self, plain_password: str, hashed_password: str) -> bool:
|
||||
def verify_password(self, plain_password: str,
|
||||
hashed_password: str) -> bool:
|
||||
"""Проверяет пароль"""
|
||||
return self.pwd_context.verify(plain_password, hashed_password)
|
||||
return self.pwd_context.verify(plain_password, hashed_password)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue