mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
Add reauthentication flow to AirNow (#186390)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
9740450be1
commit
d32e9eb323
@@ -1,5 +1,6 @@
|
||||
"""Config flow for AirNow integration."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
import logging
|
||||
from typing import Any, override
|
||||
|
||||
@@ -62,7 +63,7 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors = {}
|
||||
errors: dict[str, str] = {}
|
||||
if user_input is not None:
|
||||
# Set a unique id based on latitude/longitude
|
||||
await self.async_set_unique_id(
|
||||
@@ -70,20 +71,7 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
try:
|
||||
# Validate inputs
|
||||
await validate_input(self.hass, user_input)
|
||||
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except InvalidLocation:
|
||||
errors["base"] = "invalid_location"
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
else:
|
||||
if not (errors := await self._async_validate_input(user_input)):
|
||||
# Create Entry
|
||||
return self.async_create_entry(
|
||||
title=(
|
||||
@@ -110,6 +98,54 @@ class AirNowConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def async_step_reauth(
|
||||
self, entry_data: Mapping[str, Any]
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reauthentication."""
|
||||
return await self.async_step_reauth_confirm()
|
||||
|
||||
async def async_step_reauth_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reauthentication confirmation."""
|
||||
errors: dict[str, str] = {}
|
||||
reauth_entry = self._get_reauth_entry()
|
||||
if user_input is not None and not (
|
||||
errors := await self._async_validate_input(
|
||||
{**reauth_entry.data, **user_input}
|
||||
)
|
||||
):
|
||||
return self.async_update_reload_and_abort(
|
||||
reauth_entry, data_updates=user_input
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=probatio.Schema(
|
||||
{probatio.Required(probatio.Secret(CONF_API_KEY)): str}
|
||||
),
|
||||
description_placeholders={
|
||||
"name": reauth_entry.title,
|
||||
"api_key_url": _API_KEY_URL,
|
||||
},
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def _async_validate_input(self, data: dict[str, Any]) -> dict[str, str]:
|
||||
"""Validate the input and return any errors."""
|
||||
try:
|
||||
await validate_input(self.hass, data)
|
||||
except CannotConnect:
|
||||
return {"base": "cannot_connect"}
|
||||
except InvalidAuth:
|
||||
return {"base": "invalid_auth"}
|
||||
except InvalidLocation:
|
||||
return {"base": "invalid_location"}
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
return {"base": "unknown"}
|
||||
return {}
|
||||
|
||||
|
||||
class CannotConnect(HomeAssistantError):
|
||||
"""Error to indicate we cannot connect."""
|
||||
|
||||
@@ -8,10 +8,11 @@ from aiohttp import ClientSession
|
||||
from aiohttp.client_exceptions import ClientConnectorError
|
||||
from pyairnow import WebServiceAPI
|
||||
from pyairnow.conv import aqi_to_concentration
|
||||
from pyairnow.errors import AirNowError, InvalidJsonError
|
||||
from pyairnow.errors import AirNowError, InvalidJsonError, InvalidKeyError
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||
|
||||
from .const import (
|
||||
@@ -77,6 +78,10 @@ class AirNowDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
|
||||
self.longitude,
|
||||
)
|
||||
|
||||
except InvalidKeyError as error:
|
||||
raise ConfigEntryAuthFailed(
|
||||
translation_domain=DOMAIN, translation_key="invalid_auth"
|
||||
) from error
|
||||
except (AirNowError, ClientConnectorError, InvalidJsonError) as error:
|
||||
raise UpdateFailed(error) from error
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ rules:
|
||||
integration-owner: todo
|
||||
log-when-unavailable: todo
|
||||
parallel-updates: done
|
||||
reauthentication-flow: todo
|
||||
reauthentication-flow: done
|
||||
test-coverage: todo
|
||||
# Gold
|
||||
devices: todo
|
||||
|
||||
@@ -10,6 +10,16 @@
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"step": {
|
||||
"reauth_confirm": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "[%key:component::airnow::config::step::user::data_description::api_key%]"
|
||||
},
|
||||
"description": "The API key for {name} is no longer valid. To generate a new API key, go to {api_key_url}.",
|
||||
"title": "[%key:common::config_flow::title::reauth%]"
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]",
|
||||
@@ -38,5 +48,10 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"invalid_auth": {
|
||||
"message": "The AirNow API key is invalid."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,3 +205,59 @@ async def test_config_migration(
|
||||
assert config_entry.version == 3
|
||||
assert CONF_RADIUS not in config_entry.data
|
||||
assert CONF_RADIUS not in config_entry.options
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("setup_airnow")
|
||||
async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
|
||||
"""Test reauthentication."""
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "new_key"}
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert config_entry.data == {
|
||||
CONF_API_KEY: "new_key",
|
||||
CONF_LATITUDE: 34.053718,
|
||||
CONF_LONGITUDE: -118.244842,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
pytest.param(InvalidKeyError, "invalid_auth", id="invalid_auth"),
|
||||
pytest.param(AirNowError, "cannot_connect", id="cannot_connect"),
|
||||
pytest.param(EmptyResponseError, "invalid_location", id="invalid_location"),
|
||||
pytest.param(RuntimeError, "unknown", id="unknown"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("setup_airnow")
|
||||
async def test_reauth_errors(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
mock_api_get: AsyncMock,
|
||||
exception: type[Exception],
|
||||
error: str,
|
||||
) -> None:
|
||||
"""Test reauthentication errors and recovery."""
|
||||
result = await config_entry.start_reauth_flow(hass)
|
||||
|
||||
mock_api_get.side_effect = exception
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "new_key"}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": error}
|
||||
|
||||
mock_api_get.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "new_key"}
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert config_entry.data[CONF_API_KEY] == "new_key"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Test the AirNow integration setup."""
|
||||
|
||||
from datetime import timedelta
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from pyairnow.errors import InvalidKeyError
|
||||
import pytest
|
||||
|
||||
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mock_api_get", [AsyncMock(side_effect=InvalidKeyError)])
|
||||
@pytest.mark.usefixtures("setup_airnow")
|
||||
async def test_setup_auth_failed(
|
||||
hass: HomeAssistant, config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test an invalid API key during setup starts a reauth flow."""
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
assert flows[0]["context"]["source"] == SOURCE_REAUTH
|
||||
assert flows[0]["context"]["entry_id"] == config_entry.entry_id
|
||||
|
||||
|
||||
async def test_update_auth_failed(
|
||||
hass: HomeAssistant,
|
||||
config_entry: MockConfigEntry,
|
||||
mock_api_get: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Test an invalid API key during a scheduled refresh starts a reauth flow."""
|
||||
# Sensor platform is needed so the coordinator has listeners and polls
|
||||
with patch("pyairnow.WebServiceAPI._get", mock_api_get):
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
mock_api_get.side_effect = InvalidKeyError
|
||||
freezer.tick(timedelta(minutes=30))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
|
||||
flows = hass.config_entries.flow.async_progress()
|
||||
assert len(flows) == 1
|
||||
assert flows[0]["context"]["source"] == SOURCE_REAUTH
|
||||
assert flows[0]["context"]["entry_id"] == config_entry.entry_id
|
||||
Reference in New Issue
Block a user