import json from pathlib import Path class AccountManager: """ Класс для управления учётными записями пользователей. """ def __init__(self, db_file: str | None): self.db_file = Path(db_file) if db_file else None if isinstance(self.db_file, Path) and not self.db_file.exists(): self._save_db({}) def set_db_file(self, db_file: str | None) -> None: self.db_file = Path(db_file) if db_file else None if isinstance(self.db_file, Path) and not self.db_file.exists(): self._save_db({}) def _load_db(self) -> dict: if not isinstance(self.db_file, Path): return {} if self.db_file.exists(): return json.loads(self.db_file.read_text(encoding="utf-8")) return {} def _save_db(self, data: dict) -> None: if not isinstance(self.db_file, Path): raise RuntimeError("База данных не открыта") self.db_file.write_text(json.dumps( data, indent=2, ensure_ascii=False), encoding="utf-8") def add_user(self, username: str, password_hash: str, salt: str) -> None: data = self._load_db() data[username] = {"hash": password_hash, "salt": salt} self._save_db(data) def update_user(self, username: str, password_hash: str, salt: str) -> bool: data = self._load_db() if username not in data: return False data[username] = {"hash": password_hash, "salt": salt} self._save_db(data) return True def delete_user(self, username: str) -> bool: data = self._load_db() if username not in data: return False del data[username] self._save_db(data) return True def get_user(self, username: str) -> dict | None: data = self._load_db() return data.get(username) def list_users(self) -> list[str]: if not isinstance(self.db_file, Path): return [] data = self._load_db() return list(data.keys())