From 8c832b44cd839dc5dc5bb59a7629aa2c8e604cf9 Mon Sep 17 00:00:00 2001 From: Andre Basche Date: Tue, 11 Apr 2023 17:09:02 +0200 Subject: [PATCH] Fix token refresh problems --- pyhon/connection/auth.py | 4 +++- pyhon/connection/handler.py | 12 +++++++----- pyhon/parameter.py | 2 +- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/pyhon/connection/auth.py b/pyhon/connection/auth.py index ac88fdc..6f587a2 100644 --- a/pyhon/connection/auth.py +++ b/pyhon/connection/auth.py @@ -194,7 +194,9 @@ class HonAuth: return False if not await self._get_token(url): return False + return await self._api_auth() + async def _api_auth(self): post_headers = {"id-token": self._id_token} data = self._device.get() async with self._session.post( @@ -225,4 +227,4 @@ class HonAuth: data = await response.json() self._id_token = data["id_token"] self._access_token = data["access_token"] - return True + return await self._api_auth() diff --git a/pyhon/connection/handler.py b/pyhon/connection/handler.py index f56b4b7..8895a36 100644 --- a/pyhon/connection/handler.py +++ b/pyhon/connection/handler.py @@ -75,17 +75,18 @@ class HonConnectionHandler(HonBaseConnectionHandler): self._request_headers["id-token"] = self._auth.id_token else: raise HonAuthenticationError("Can't login") - return {h: v for h, v in self._request_headers.items() if h not in headers} + return headers | self._request_headers @asynccontextmanager async def _intercept(self, method, *args, loop=0, **kwargs): kwargs["headers"] = await self._check_headers(kwargs.get("headers", {})) async with method(*args, **kwargs) as response: - if response.status == 403 and not loop: + if response.status in [401, 403] and loop == 0: _LOGGER.info("Try refreshing token...") await self._auth.refresh() - yield await self._intercept(method, *args, loop=loop + 1, **kwargs) - elif response.status == 403 and loop < 2: + async with self._intercept(method, *args, loop=loop + 1, **kwargs) as result: + yield result + elif response.status in [401, 403] and loop == 1: _LOGGER.warning( "%s - Error %s - %s", response.request_info.url, @@ -93,7 +94,8 @@ class HonConnectionHandler(HonBaseConnectionHandler): await response.text(), ) await self.create() - yield await self._intercept(method, *args, loop=loop + 1, **kwargs) + async with self._intercept(method, *args, loop=loop + 1, **kwargs) as result: + yield result elif loop >= 2: _LOGGER.error( "%s - Error %s - %s", diff --git a/pyhon/parameter.py b/pyhon/parameter.py index 31dbda1..7d9208e 100644 --- a/pyhon/parameter.py +++ b/pyhon/parameter.py @@ -5,7 +5,7 @@ def str_to_float(string): try: return int(string) except ValueError: - return float(str(string.replace(",", "."))) + return float(str(string).replace(",", ".")) class HonParameter: