import logging from typing import Optional from config.settings import settings from .client import APIClient logger = logging.getLogger(__name__) class AuthManager: def __init__(self, client: APIClient): self.client = client self._current_role: Optional[str] = None @property def current_role(self) -> Optional[str]: return self._current_role def login(self, username: str, password: str) -> bool: resp = self.client.login(username, password) if resp.ok(): self._current_role = "custom" return True logger.error(f"登录失败: {resp.msg}") return False def logout(self): self.client.clear_token() self._current_role = None def _login_preset_account(self, role: str) -> bool: account = settings.get_account(role) if not account: raise ValueError(f"未配置 {role} 账号,请检查配置文件") if self.login(account["username"], account["password"]): self._current_role = role return True return False def as_super_admin(self) -> 'AuthManager': self._login_preset_account("super_admin") return self def as_platform_admin(self) -> 'AuthManager': self._login_preset_account("platform_admin") return self def as_agent(self, shop_id: int, username: Optional[str] = None, password: Optional[str] = None) -> 'AuthManager': if username and password: self.login(username, password) else: account = settings.get_account(f"agent_{shop_id}") if account: self.login(account["username"], account["password"]) else: raise ValueError(f"未配置 agent_{shop_id} 账号,请提供用户名密码或在配置文件中添加") self._current_role = f"agent_{shop_id}" return self def as_enterprise(self, enterprise_id: int, username: Optional[str] = None, password: Optional[str] = None) -> 'AuthManager': if username and password: self.login(username, password) else: account = settings.get_account(f"enterprise_{enterprise_id}") if account: self.login(account["username"], account["password"]) else: raise ValueError(f"未配置 enterprise_{enterprise_id} 账号,请提供用户名密码或在配置文件中添加") self._current_role = f"enterprise_{enterprise_id}" return self