2020-10-21 08:17:49 +00:00
|
|
|
"""Local Nest authentication for the legacy api."""
|
2022-02-03 05:57:44 +00:00
|
|
|
# mypy: ignore-errors
|
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
import asyncio
|
|
|
|
from functools import partial
|
2021-10-23 18:56:30 +00:00
|
|
|
from http import HTTPStatus
|
2018-06-13 15:14:52 +00:00
|
|
|
|
2019-12-09 11:08:51 +00:00
|
|
|
from nest.nest import AUTHORIZE_URL, AuthorizationError, NestAuth
|
2019-10-17 13:03:50 +00:00
|
|
|
|
2018-06-13 15:14:52 +00:00
|
|
|
from homeassistant.core import callback
|
2019-12-09 11:08:51 +00:00
|
|
|
|
2020-12-22 20:42:37 +00:00
|
|
|
from ..config_flow import CodeInvalid, NestAuthError, register_flow_implementation
|
2018-06-13 15:14:52 +00:00
|
|
|
from .const import DOMAIN
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def initialize(hass, client_id, client_secret):
|
|
|
|
"""Initialize a local auth provider."""
|
2020-12-22 20:42:37 +00:00
|
|
|
register_flow_implementation(
|
2019-07-31 19:25:30 +00:00
|
|
|
hass,
|
|
|
|
DOMAIN,
|
|
|
|
"configuration.yaml",
|
2018-09-21 12:47:52 +00:00
|
|
|
partial(generate_auth_url, client_id),
|
2019-07-31 19:25:30 +00:00
|
|
|
partial(resolve_auth_code, hass, client_id, client_secret),
|
2018-06-13 15:14:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
async def generate_auth_url(client_id, flow_id):
|
|
|
|
"""Generate an authorize url."""
|
|
|
|
return AUTHORIZE_URL.format(client_id, flow_id)
|
|
|
|
|
|
|
|
|
|
|
|
async def resolve_auth_code(hass, client_id, client_secret, code):
|
|
|
|
"""Resolve an authorization code."""
|
|
|
|
|
|
|
|
result = asyncio.Future()
|
|
|
|
auth = NestAuth(
|
|
|
|
client_id=client_id,
|
|
|
|
client_secret=client_secret,
|
|
|
|
auth_callback=result.set_result,
|
|
|
|
)
|
|
|
|
auth.pin = code
|
|
|
|
|
|
|
|
try:
|
2020-10-16 11:31:16 +00:00
|
|
|
await hass.async_add_executor_job(auth.login)
|
2018-06-13 15:14:52 +00:00
|
|
|
return await result
|
|
|
|
except AuthorizationError as err:
|
2021-10-23 18:56:30 +00:00
|
|
|
if err.response.status_code == HTTPStatus.UNAUTHORIZED:
|
2020-12-22 20:42:37 +00:00
|
|
|
raise CodeInvalid() from err
|
|
|
|
raise NestAuthError(
|
2019-09-03 18:35:00 +00:00
|
|
|
f"Unknown error: {err} ({err.response.status_code})"
|
2020-12-22 20:42:37 +00:00
|
|
|
) from err
|