From 2887eeb32f00d22dd6dc67decb1c80151de8c603 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 14 Apr 2021 23:17:32 -1000 Subject: [PATCH] Only enable envoy inverters when the user has access (#49234) --- .../components/enphase_envoy/__init__.py | 20 +++++----- .../components/enphase_envoy/config_flow.py | 21 +++++++++- .../components/enphase_envoy/strings.json | 3 +- .../enphase_envoy/translations/en.json | 3 +- .../enphase_envoy/test_config_flow.py | 40 +++++++++++++++++++ 5 files changed, 72 insertions(+), 15 deletions(-) diff --git a/homeassistant/components/enphase_envoy/__init__.py b/homeassistant/components/enphase_envoy/__init__.py index faa9247b4e7..26318faa7f9 100644 --- a/homeassistant/components/enphase_envoy/__init__.py +++ b/homeassistant/components/enphase_envoy/__init__.py @@ -12,7 +12,7 @@ import httpx from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.httpx_client import get_async_client from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed @@ -33,23 +33,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: config[CONF_HOST], config[CONF_USERNAME], config[CONF_PASSWORD], + inverters=True, async_client=get_async_client(hass), ) - try: - await envoy_reader.getData() - except httpx.HTTPStatusError as err: - _LOGGER.error("Authentication failure during setup: %s", err) - return - except (RuntimeError, httpx.HTTPError) as err: - raise ConfigEntryNotReady from err - async def async_update_data(): """Fetch data from API endpoint.""" data = {} async with async_timeout.timeout(30): try: await envoy_reader.getData() + except httpx.HTTPStatusError as err: + raise ConfigEntryAuthFailed from err except httpx.HTTPError as err: raise UpdateFailed(f"Error communicating with API: {err}") from err @@ -73,8 +68,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: update_interval=SCAN_INTERVAL, ) - envoy_reader.get_inverters = True - await coordinator.async_config_entry_first_refresh() + try: + await coordinator.async_config_entry_first_refresh() + except ConfigEntryAuthFailed: + envoy_reader.get_inverters = False + await coordinator.async_config_entry_first_refresh() hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { COORDINATOR: coordinator, diff --git a/homeassistant/components/enphase_envoy/config_flow.py b/homeassistant/components/enphase_envoy/config_flow.py index 934b02be311..a47a095fde7 100644 --- a/homeassistant/components/enphase_envoy/config_flow.py +++ b/homeassistant/components/enphase_envoy/config_flow.py @@ -35,7 +35,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD], - inverters=True, + inverters=False, async_client=get_async_client(hass), ) @@ -59,6 +59,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): self.name = None self.username = None self.serial = None + self._reauth_entry = None @callback def _async_generate_schema(self): @@ -121,6 +122,13 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): return await self.async_step_user() + async def async_step_reauth(self, user_input): + """Handle configuration by re-auth.""" + self._reauth_entry = self.hass.config_entries.async_get_entry( + self.context["entry_id"] + ) + return await self.async_step_user() + async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> dict[str, Any]: @@ -128,7 +136,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): errors = {} if user_input is not None: - if user_input[CONF_HOST] in self._async_current_hosts(): + if ( + not self._reauth_entry + and user_input[CONF_HOST] in self._async_current_hosts() + ): return self.async_abort(reason="already_configured") try: await validate_input(self.hass, user_input) @@ -145,6 +156,12 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): data[CONF_NAME] = f"{ENVOY} {self.serial}" else: data[CONF_NAME] = self.name or ENVOY + if self._reauth_entry: + self.hass.config_entries.async_update_entry( + self._reauth_entry, + data=data, + ) + return self.async_abort(reason="reauth_successful") return self.async_create_entry(title=data[CONF_NAME], data=data) if self.serial: diff --git a/homeassistant/components/enphase_envoy/strings.json b/homeassistant/components/enphase_envoy/strings.json index 399358659d7..1af58a32fa7 100644 --- a/homeassistant/components/enphase_envoy/strings.json +++ b/homeassistant/components/enphase_envoy/strings.json @@ -16,7 +16,8 @@ "unknown": "[%key:common::config_flow::error::unknown%]" }, "abort": { - "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" + "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", + "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]" } } } \ No newline at end of file diff --git a/homeassistant/components/enphase_envoy/translations/en.json b/homeassistant/components/enphase_envoy/translations/en.json index 7c138727cd7..58c69e90eef 100644 --- a/homeassistant/components/enphase_envoy/translations/en.json +++ b/homeassistant/components/enphase_envoy/translations/en.json @@ -1,7 +1,8 @@ { "config": { "abort": { - "already_configured": "Device is already configured" + "already_configured": "Device is already configured", + "reauth_successful": "Re-authentication was successful" }, "error": { "cannot_connect": "Failed to connect", diff --git a/tests/components/enphase_envoy/test_config_flow.py b/tests/components/enphase_envoy/test_config_flow.py index 99efca883c8..0f48067ec6d 100644 --- a/tests/components/enphase_envoy/test_config_flow.py +++ b/tests/components/enphase_envoy/test_config_flow.py @@ -302,3 +302,43 @@ async def test_zeroconf_host_already_exists(hass: HomeAssistant) -> None: assert config_entry.unique_id == "1234" assert config_entry.title == "Envoy 1234" assert len(mock_setup_entry.mock_calls) == 1 + + +async def test_reauth(hass: HomeAssistant) -> None: + """Test we reauth auth.""" + await setup.async_setup_component(hass, "persistent_notification", {}) + config_entry = MockConfigEntry( + domain=DOMAIN, + data={ + "host": "1.1.1.1", + "name": "Envoy", + "username": "test-username", + "password": "test-password", + }, + title="Envoy", + ) + config_entry.add_to_hass(hass) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={ + "source": config_entries.SOURCE_REAUTH, + "unique_id": config_entry.unique_id, + "entry_id": config_entry.entry_id, + }, + ) + + with patch( + "homeassistant.components.enphase_envoy.config_flow.EnvoyReader.getData", + return_value=True, + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + "host": "1.1.1.1", + "username": "test-username", + "password": "test-password", + }, + ) + + assert result2["type"] == "abort" + assert result2["reason"] == "reauth_successful"