Keep cloud tokens always valid (#20762)

* Keep auth token always valid

* Remove unused refresh_auth message

* Capture EndpointConnectionError

* Lint
This commit is contained in:
Paulus Schoutsen authored and Paulus Schoutsen committed 2019-02-05 08:04:41 -08:00
1 parent 7f76210549
commit 3d75e1c299
5 files changed
+122 -36

No files matched your search

+66 -7
View File
@@ -1,4 +1,10 @@
"""Package to communicate with the authentication API."""
import asyncio
import logging
import random
_LOGGER = logging.getLogger(__name__)
class CloudError(Exception):
@@ -39,6 +45,40 @@ AWS_EXCEPTIONS = {
}
async def async_setup(hass, cloud):
"""Configure the auth api."""
refresh_task = None
async def handle_token_refresh():
"""Handle Cloud access token refresh."""
sleep_time = 5
sleep_time = random.randint(2400, 3600)
while True:
try:
await asyncio.sleep(sleep_time)
await hass.async_add_executor_job(renew_access_token, cloud)
except CloudError as err:
_LOGGER.error("Can't refresh cloud token: %s", err)
except asyncio.CancelledError:
# Task is canceled, stop it.
break
sleep_time = random.randint(3100, 3600)
async def on_connect():
"""When the instance is connected."""
nonlocal refresh_task
refresh_task = hass.async_create_task(handle_token_refresh())
async def on_disconnect():
"""When the instance is disconnected."""
nonlocal refresh_task
refresh_task.cancel()
cloud.iot.register_on_connect(on_connect)
cloud.iot.register_on_disconnect(on_disconnect)
def _map_aws_exception(err):
"""Map AWS exception to our exceptions."""
ex = AWS_EXCEPTIONS.get(err.response['Error']['Code'], UnknownError)
@@ -47,7 +87,7 @@ def _map_aws_exception(err):
def register(cloud, email, password):
"""Register a new account."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
cognito = _cognito(cloud)
# Workaround for bug in Warrant. PR with fix:
@@ -55,13 +95,16 @@ def register(cloud, email, password):
cognito.add_base_attributes()
try:
cognito.register(email, password)
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def resend_email_confirm(cloud, email):
"""Resend email confirmation."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
cognito = _cognito(cloud, username=email)
@@ -72,18 +115,23 @@ def resend_email_confirm(cloud, email):
)
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def forgot_password(cloud, email):
"""Initialize forgotten password flow."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
cognito = _cognito(cloud, username=email)
try:
cognito.initiate_forgot_password()
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def login(cloud, email, password):
@@ -97,7 +145,7 @@ def login(cloud, email, password):
def check_token(cloud):
"""Check that the token is valid and verify if needed."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
cognito = _cognito(
cloud,
@@ -109,13 +157,17 @@ def check_token(cloud):
cloud.id_token = cognito.id_token
cloud.access_token = cognito.access_token
cloud.write_user_info()
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def renew_access_token(cloud):
"""Renew access token."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
cognito = _cognito(
cloud,
@@ -127,13 +179,17 @@ def renew_access_token(cloud):
cloud.id_token = cognito.id_token
cloud.access_token = cognito.access_token
cloud.write_user_info()
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def _authenticate(cloud, email, password):
"""Log in and return an authenticated Cognito instance."""
from botocore.exceptions import ClientError
from botocore.exceptions import ClientError, EndpointConnectionError
from warrant.exceptions import ForceChangePasswordException
assert not cloud.is_logged_in, 'Cannot login if already logged in.'
@@ -145,11 +201,14 @@ def _authenticate(cloud, email, password):
return cognito
except ForceChangePasswordException:
raise PasswordChangeRequired
raise PasswordChangeRequired()
except ClientError as err:
raise _map_aws_exception(err)
except EndpointConnectionError:
raise UnknownError()
def _cognito(cloud, **kwargs):
"""Get the client credentials."""