auth.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import requests
  2. from typing import Optional
  3. from config.settings import BASE_URL, VENT_SYS_USERNAME, VENT_SYS_PASSWORD
  4. _LOGIN_PATH = "/jeecg-system/sys/login"
  5. _REQUEST_TIMEOUT = 10
  6. class AuthService:
  7. """Manages authentication token for the ventilation system API.
  8. Uses lazy initialization: the token is fetched on first access and
  9. cached in a class-level variable for reuse across all instances.
  10. """
  11. _token: Optional[str] = None
  12. @classmethod
  13. def get_token(cls) -> str:
  14. """Return the current auth token, logging in if necessary."""
  15. if cls._token is None:
  16. cls._authenticate()
  17. return cls._token
  18. @classmethod
  19. def _authenticate(cls) -> None:
  20. login_url = f"{BASE_URL}{_LOGIN_PATH}"
  21. credentials = {"username": VENT_SYS_USERNAME, "password": VENT_SYS_PASSWORD}
  22. response = requests.post(login_url, json=credentials, timeout=_REQUEST_TIMEOUT)
  23. response.raise_for_status()
  24. payload = response.json()
  25. if not payload.get("success"):
  26. raise RuntimeError(f"登录失败: {payload.get('message')}")
  27. cls._token = payload["result"]["token"]
  28. print("✅ 登录成功,token 已获取")
  29. @classmethod
  30. def refresh_token(cls) -> None:
  31. """Force re-authentication, discarding any cached token."""
  32. cls._token = None
  33. cls.get_token()