| 1 | from abc import ABC |
| 2 | from abc import abstractmethod |
| 3 | |
| 4 | from aiohttp import ClientResponse |
| 5 | from aiohttp import ClientSession |
| 6 | |
| 7 | |
| 8 | class AbstractAuth(ABC): |
| 9 | """Abstract class to make authenticated requests.""" |
| 10 | |
| 11 | def __init__(self, websession: ClientSession, host: str): |
| 12 | """Initialize the auth.""" |
| 13 | self.websession = websession |
| 14 | self.host = host |
| 15 | |
| 16 | @abstractmethod |
| 17 | async def async_get_access_token(self) -> str: |
| 18 | """Return a valid access token.""" |
| 19 | |
| 20 | async def request(self, method: str, url: str, **kwargs) -> ClientResponse: |
| 21 | """Make a request.""" |
| 22 | headers = kwargs.get("headers") |
| 23 | |
| 24 | if headers is None: |
| 25 | headers = {} |
| 26 | else: |
| 27 | headers = dict(headers) |
| 28 | del kwargs["headers"] |
| 29 | |
| 30 | access_token = await self.async_get_access_token() |
| 31 | headers["authorization"] = f"Bearer {access_token}" |
| 32 | |
| 33 | return await self.websession.request( |
| 34 | method, |
| 35 | f"{self.host}/{url}", |
| 36 | **kwargs, |
| 37 | headers=headers, |
| 38 | ) |