1
0

AuthAPI.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. '''
  2. That class provides the ability to authenticate an application account through the
  3. API and store these authentication tokens.
  4. Modules using the API should log in ShariX system using this class.
  5. '''
  6. import requests
  7. from core.settings import API_URL
  8. class AuthAPI:
  9. def __init__(self, login: str, password: str):
  10. self._login = login
  11. self._password = password
  12. self._token = None
  13. self._headers = None
  14. def _create_token(self):
  15. try:
  16. response = requests.post(
  17. f"{API_URL}/auth/token/login/",
  18. {
  19. "phone_number": self._login,
  20. "password": self._password
  21. }
  22. )
  23. self._token = response.json()["auth_token"]
  24. except requests.exceptions.ConnectionError:
  25. print("\033[31m" + f"{self.__class__.__name__}: Can't connect to the API." + "\033[0m")
  26. except KeyError:
  27. print("\033[31m" + f"{self.__class__.__name__}: Incorrect login data." + "\033[0m")
  28. @property
  29. def token(self):
  30. if self._token is None:
  31. self._create_token()
  32. return self._token
  33. @property
  34. def headers(self):
  35. if self._token is None:
  36. self._create_token()
  37. self._headers = {'Authorization': f'Token {self._token}'}
  38. return self._headers