auth.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import logging
  2. from typing import Optional
  3. from pydantic import BaseModel
  4. from .config import get_auth_path
  5. logger = logging.getLogger("fastapi_cli")
  6. class AuthConfig(BaseModel):
  7. access_token: str
  8. def write_auth_config(auth_data: AuthConfig) -> None:
  9. auth_path = get_auth_path()
  10. logger.debug("Writing auth config to: %s", auth_path)
  11. auth_path.write_text(auth_data.model_dump_json(), encoding="utf-8")
  12. logger.debug("Auth config written successfully")
  13. def delete_auth_config() -> None:
  14. auth_path = get_auth_path()
  15. logger.debug("Deleting auth config at: %s", auth_path)
  16. if auth_path.exists():
  17. auth_path.unlink()
  18. logger.debug("Auth config deleted successfully")
  19. else:
  20. logger.debug("Auth config file doesn't exist, nothing to delete")
  21. def read_auth_config() -> Optional[AuthConfig]:
  22. auth_path = get_auth_path()
  23. logger.debug("Reading auth config from: %s", auth_path)
  24. if not auth_path.exists():
  25. logger.debug("Auth config file doesn't exist")
  26. return None
  27. logger.debug("Auth config loaded successfully")
  28. return AuthConfig.model_validate_json(auth_path.read_text(encoding="utf-8"))
  29. def get_auth_token() -> Optional[str]:
  30. logger.debug("Getting auth token")
  31. auth_data = read_auth_config()
  32. if auth_data is None:
  33. logger.debug("No auth data found")
  34. return None
  35. logger.debug("Auth token retrieved successfully")
  36. return auth_data.access_token
  37. def is_logged_in() -> bool:
  38. result = get_auth_token() is not None
  39. logger.debug("Login status: %s", result)
  40. return result