credentials.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import logging
  2. from abc import ABC, abstractmethod
  3. from typing import Any, Callable, Optional, Tuple, Union
  4. logger = logging.getLogger(__name__)
  5. class CredentialProvider:
  6. """
  7. Credentials Provider.
  8. """
  9. def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
  10. raise NotImplementedError("get_credentials must be implemented")
  11. async def get_credentials_async(self) -> Union[Tuple[str], Tuple[str, str]]:
  12. logger.warning(
  13. "This method is added for backward compatability. "
  14. "Please override it in your implementation."
  15. )
  16. return self.get_credentials()
  17. class StreamingCredentialProvider(CredentialProvider, ABC):
  18. """
  19. Credential provider that streams credentials in the background.
  20. """
  21. @abstractmethod
  22. def on_next(self, callback: Callable[[Any], None]):
  23. """
  24. Specifies the callback that should be invoked
  25. when the next credentials will be retrieved.
  26. :param callback: Callback with
  27. :return:
  28. """
  29. pass
  30. @abstractmethod
  31. def on_error(self, callback: Callable[[Exception], None]):
  32. pass
  33. @abstractmethod
  34. def is_streaming(self) -> bool:
  35. pass
  36. class UsernamePasswordCredentialProvider(CredentialProvider):
  37. """
  38. Simple implementation of CredentialProvider that just wraps static
  39. username and password.
  40. """
  41. def __init__(self, username: Optional[str] = None, password: Optional[str] = None):
  42. self.username = username or ""
  43. self.password = password or ""
  44. def get_credentials(self):
  45. if self.username:
  46. return self.username, self.password
  47. return (self.password,)
  48. async def get_credentials_async(self) -> Union[Tuple[str], Tuple[str, str]]:
  49. return self.get_credentials()