Fix new auth system (#633)

* Fix new auth system

* Update exceptions.py

* Update exceptions.py

* Update homeassistant.py

* Update homeassistant.py

* Update homeassistant.py

* Fix some API Errors

* fix lint
This commit is contained in:
Pascal Vizeli 2018-08-09 00:05:08 +02:00 committed by GitHub
parent 398815efd8
commit 00e7d96472
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 29 additions and 29 deletions

View File

@ -57,7 +57,7 @@ class APIProxy(CoreSysAttributes):
yield resp yield resp
return return
except HomeAssistantAuthError: except HomeAssistantAPIError:
_LOGGER.error("Authenticate error on API for request %s", path) _LOGGER.error("Authenticate error on API for request %s", path)
except aiohttp.ClientError as err: except aiohttp.ClientError as err:
_LOGGER.error("Client error on API %s request %s", path, err) _LOGGER.error("Client error on API %s request %s", path, err)
@ -151,7 +151,7 @@ class APIProxy(CoreSysAttributes):
_LOGGER.error( _LOGGER.error(
"Failed authentication to Home-Assistant websocket: %s", data) "Failed authentication to Home-Assistant websocket: %s", data)
except (RuntimeError, HomeAssistantAPIError) as err: except (RuntimeError, HomeAssistantAuthError, ValueError) as err:
_LOGGER.error("Client error on websocket API %s.", err) _LOGGER.error("Client error on websocket API %s.", err)
raise HTTPBadGateway() raise HTTPBadGateway()

View File

@ -1,7 +1,4 @@
"""Core Exceptions.""" """Core Exceptions."""
import asyncio
import aiohttp
class HassioError(Exception): class HassioError(Exception):
@ -26,14 +23,13 @@ class HomeAssistantUpdateError(HomeAssistantError):
pass pass
class HomeAssistantAuthError(HomeAssistantError): class HomeAssistantAPIError(HomeAssistantError):
"""Home Assistant Auth API exception.""" """Home Assistant API exception."""
pass pass
class HomeAssistantAPIError( class HomeAssistantAuthError(HomeAssistantAPIError):
HomeAssistantAuthError, asyncio.TimeoutError, aiohttp.ClientError): """Home Assistant Auth API exception."""
"""Home Assistant API exception."""
pass pass

View File

@ -355,7 +355,7 @@ class HomeAssistant(JsonConfig, CoreSysAttributes):
return return
with suppress(asyncio.TimeoutError, aiohttp.ClientError): with suppress(asyncio.TimeoutError, aiohttp.ClientError):
async with self.sys_websession_ssl.get( async with self.sys_websession_ssl.post(
f"{self.api_url}/auth/token", f"{self.api_url}/auth/token",
timeout=30, timeout=30,
data={ data={
@ -363,15 +363,14 @@ class HomeAssistant(JsonConfig, CoreSysAttributes):
"refresh_token": self.refresh_token "refresh_token": self.refresh_token
} }
) as resp: ) as resp:
if resp.status != 200: if resp.status == 200:
_LOGGER.error("Authenticate problem with HomeAssistant!") _LOGGER.info("Updated HomeAssistant API token")
raise HomeAssistantAuthError() tokens = await resp.json()
tokens = await resp.json() self.access_token = tokens['access_token']
self.access_token = tokens['access_token'] return
return
_LOGGER.error("Can't update HomeAssistant access token!") _LOGGER.error("Can't update HomeAssistant access token!")
raise HomeAssistantAPIError() raise HomeAssistantAuthError()
@asynccontextmanager @asynccontextmanager
async def make_request(self, method, path, json=None, content_type=None, async def make_request(self, method, path, json=None, content_type=None,
@ -394,15 +393,20 @@ class HomeAssistant(JsonConfig, CoreSysAttributes):
await self.ensure_access_token() await self.ensure_access_token()
headers[hdrs.AUTHORIZATION] = f'Bearer {self.access_token}' headers[hdrs.AUTHORIZATION] = f'Bearer {self.access_token}'
async with getattr(self.sys_websession_ssl, method)( try:
url, data=data, timeout=timeout, json=json, headers=headers async with getattr(self.sys_websession_ssl, method)(
) as resp: url, data=data, timeout=timeout, json=json,
# Access token expired headers=headers
if resp.status == 401 and self.refresh_token: ) as resp:
self.access_token = None # Access token expired
continue if resp.status == 401 and self.refresh_token:
yield resp self.access_token = None
return continue
yield resp
return
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
_LOGGER.error("Error on call %s: %s", url, err)
break
raise HomeAssistantAPIError() raise HomeAssistantAPIError()

View File

@ -1,7 +1,7 @@
attr==0.3.1 attr==0.3.1
async_timeout==3.0.0 async_timeout==3.0.0
aiohttp==3.3.2 aiohttp==3.3.2
docker==3.4.0 docker==3.4.1
colorlog==3.1.2 colorlog==3.1.2
voluptuous==0.11.1 voluptuous==0.11.1
gitpython==2.1.10 gitpython==2.1.10

View File

@ -4,7 +4,7 @@ envlist = lint
[testenv] [testenv]
deps = deps =
flake8==3.5.0 flake8==3.5.0
pylint==2.0.0 pylint==2.1.1
-r{toxinidir}/requirements.txt -r{toxinidir}/requirements.txt
[testenv:lint] [testenv:lint]