Only enable envoy inverters when the user has access (#49234)

This commit is contained in:
J. Nick Koston 2021-04-14 23:17:32 -10:00 committed by GitHub
parent d71f913a12
commit 2887eeb32f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 72 additions and 15 deletions

View file

@ -12,7 +12,7 @@ import httpx
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant 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.httpx_client import get_async_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed 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_HOST],
config[CONF_USERNAME], config[CONF_USERNAME],
config[CONF_PASSWORD], config[CONF_PASSWORD],
inverters=True,
async_client=get_async_client(hass), 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(): async def async_update_data():
"""Fetch data from API endpoint.""" """Fetch data from API endpoint."""
data = {} data = {}
async with async_timeout.timeout(30): async with async_timeout.timeout(30):
try: try:
await envoy_reader.getData() await envoy_reader.getData()
except httpx.HTTPStatusError as err:
raise ConfigEntryAuthFailed from err
except httpx.HTTPError as err: except httpx.HTTPError as err:
raise UpdateFailed(f"Error communicating with API: {err}") from 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, update_interval=SCAN_INTERVAL,
) )
envoy_reader.get_inverters = True try:
await coordinator.async_config_entry_first_refresh() 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] = { hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
COORDINATOR: coordinator, COORDINATOR: coordinator,

View file

@ -35,7 +35,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
data[CONF_HOST], data[CONF_HOST],
data[CONF_USERNAME], data[CONF_USERNAME],
data[CONF_PASSWORD], data[CONF_PASSWORD],
inverters=True, inverters=False,
async_client=get_async_client(hass), async_client=get_async_client(hass),
) )
@ -59,6 +59,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self.name = None self.name = None
self.username = None self.username = None
self.serial = None self.serial = None
self._reauth_entry = None
@callback @callback
def _async_generate_schema(self): def _async_generate_schema(self):
@ -121,6 +122,13 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return await self.async_step_user() 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( async def async_step_user(
self, user_input: dict[str, Any] | None = None self, user_input: dict[str, Any] | None = None
) -> dict[str, Any]: ) -> dict[str, Any]:
@ -128,7 +136,10 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
errors = {} errors = {}
if user_input is not None: 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") return self.async_abort(reason="already_configured")
try: try:
await validate_input(self.hass, user_input) 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}" data[CONF_NAME] = f"{ENVOY} {self.serial}"
else: else:
data[CONF_NAME] = self.name or ENVOY 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) return self.async_create_entry(title=data[CONF_NAME], data=data)
if self.serial: if self.serial:

View file

@ -16,7 +16,8 @@
"unknown": "[%key:common::config_flow::error::unknown%]" "unknown": "[%key:common::config_flow::error::unknown%]"
}, },
"abort": { "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%]"
} }
} }
} }

View file

@ -1,7 +1,8 @@
{ {
"config": { "config": {
"abort": { "abort": {
"already_configured": "Device is already configured" "already_configured": "Device is already configured",
"reauth_successful": "Re-authentication was successful"
}, },
"error": { "error": {
"cannot_connect": "Failed to connect", "cannot_connect": "Failed to connect",

View file

@ -302,3 +302,43 @@ async def test_zeroconf_host_already_exists(hass: HomeAssistant) -> None:
assert config_entry.unique_id == "1234" assert config_entry.unique_id == "1234"
assert config_entry.title == "Envoy 1234" assert config_entry.title == "Envoy 1234"
assert len(mock_setup_entry.mock_calls) == 1 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"