Add reauthentication flow to Vitesy (#186302)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-10-14 08:38:13 +02:00
committed by GitHub
co-authored by Claude
parent a544d5a6fa
commit 63c7948bc1
6 changed files with 170 additions and 45 deletions
+60 -16
View File
@@ -1,5 +1,6 @@
"""Config flow for the Vitesy integration."""
from collections.abc import Mapping
from typing import Any, override
from aiovitesy.api import VitesyApi
@@ -18,6 +19,10 @@ from homeassistant.helpers.selector import (
from .const import DOMAIN
PASSWORD_SELECTOR = TextSelector(
TextSelectorConfig(type=TextSelectorType.PASSWORD, autocomplete="current-password")
)
STEP_USER_DATA_SCHEMA = probatio.Schema(
{
probatio.Required(CONF_EMAIL): TextSelector(
@@ -26,12 +31,13 @@ STEP_USER_DATA_SCHEMA = probatio.Schema(
autocomplete="username",
)
),
probatio.Required(probatio.Secret(CONF_PASSWORD)): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
)
),
probatio.Required(probatio.Secret(CONF_PASSWORD)): PASSWORD_SELECTOR,
}
)
STEP_REAUTH_DATA_SCHEMA = probatio.Schema(
{
probatio.Required(probatio.Secret(CONF_PASSWORD)): PASSWORD_SELECTOR,
}
)
@@ -50,6 +56,18 @@ async def _validate_credentials(hass: HomeAssistant, email: str, password: str)
class VitesyConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Vitesy."""
async def _async_validate_input(
self, email: str, password: str, errors: dict[str, str]
) -> str | None:
"""Validate the credentials, return the user id or record an error."""
try:
return await _validate_credentials(self.hass, email, password)
except CannotAuthenticate:
errors["base"] = "invalid_auth"
except VitesyError:
errors["base"] = "cannot_connect"
return None
@override
async def async_step_user(
self, user_input: dict[str, Any] | None = None
@@ -58,16 +76,10 @@ class VitesyConfigFlow(ConfigFlow, domain=DOMAIN):
errors: dict[str, str] = {}
if user_input is not None:
email = user_input[CONF_EMAIL]
try:
user_id = await _validate_credentials(
self.hass, email, user_input[CONF_PASSWORD]
)
except CannotAuthenticate:
errors["base"] = "invalid_auth"
except VitesyError:
errors["base"] = "cannot_connect"
else:
user_id = await self._async_validate_input(
email, user_input[CONF_PASSWORD], errors
)
if user_id is not None:
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=email, data=user_input)
@@ -75,3 +87,35 @@ class VitesyConfigFlow(ConfigFlow, domain=DOMAIN):
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reauthentication when the stored credentials are rejected."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Ask for a new password for the existing account."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
email = reauth_entry.data[CONF_EMAIL]
if user_input is not None:
user_id = await self._async_validate_input(
email, user_input[CONF_PASSWORD], errors
)
if user_id is not None:
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
reauth_entry,
data_updates={CONF_PASSWORD: user_input[CONF_PASSWORD]},
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_REAUTH_DATA_SCHEMA,
description_placeholders={CONF_EMAIL: email},
errors=errors,
)
+8 -13
View File
@@ -28,21 +28,11 @@ def supports_mode(device: VitesyDevice) -> bool:
@contextmanager
def _translate_errors(*, auth_recoverable: bool = False) -> Iterator[None]:
"""Convert aiovitesy errors into coordinator setup/update failures.
On a refresh, auth_recoverable must be True: the config flow has no
reauth step yet, so raising ConfigEntryAuthFailed there would stop
polling forever with no way to recover.
"""
def _translate_errors() -> Iterator[None]:
"""Convert aiovitesy errors into coordinator setup/update failures."""
try:
yield
except CannotAuthenticate as err:
if auth_recoverable:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
) from err
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
@@ -83,7 +73,7 @@ class VitesyDataUpdateCoordinator(DataUpdateCoordinator[dict[str, VitesyDevice]]
@override
async def _async_update_data(self) -> dict[str, VitesyDevice]:
"""Fetch the latest state for every device in the account."""
with _translate_errors(auth_recoverable=True):
with _translate_errors():
devices = await self.api.get_all_devices()
self.mode_status = await self._async_get_mode_status(devices)
return devices
@@ -103,6 +93,11 @@ class VitesyDataUpdateCoordinator(DataUpdateCoordinator[dict[str, VitesyDevice]]
continue
try:
mode_status[device_id] = await self.api.get_mode_status(device_id)
except CannotAuthenticate as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
) from err
except VitesyError as err:
LOGGER.debug("Could not read mode of %s: %s", device.name, err)
return mode_status
@@ -38,7 +38,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done
# Gold
+12 -1
View File
@@ -1,13 +1,24 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"unique_id_mismatch": "The credentials belong to a different Vitesy Hub account. Please reauthenticate with the account originally configured."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]"
},
"step": {
"reauth_confirm": {
"data": {
"password": "[%key:common::config_flow::data::password%]"
},
"data_description": {
"password": "[%key:component::vitesy::config::step::user::data_description::password%]"
},
"description": "The password for {email} is no longer valid. Enter the current password of your Vitesy Hub account.",
"title": "[%key:common::config_flow::title::reauth%]"
},
"user": {
"data": {
"email": "[%key:common::config_flow::data::email%]",
@@ -112,3 +112,76 @@ async def test_already_configured(
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow(
hass: HomeAssistant,
mock_vitesy_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication stores the new password."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["description_placeholders"][CONF_EMAIL] == EMAIL
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {CONF_EMAIL: EMAIL, CONF_PASSWORD: "new-password"}
@pytest.mark.parametrize(
("side_effect", "reason"),
[
pytest.param(CannotAuthenticate, "invalid_auth", id="invalid_auth"),
pytest.param(CannotConnect, "cannot_connect", id="cannot_connect"),
pytest.param(GenericResponseError, "cannot_connect", id="generic_error"),
],
)
async def test_reauth_errors_then_recovers(
hass: HomeAssistant,
mock_vitesy_client: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: type[Exception],
reason: str,
) -> None:
"""Test each reauth failure surfaces an error and the flow can recover."""
mock_config_entry.add_to_hass(hass)
mock_vitesy_client.login.side_effect = side_effect
result = await mock_config_entry.start_reauth_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_vitesy_client.login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
async def test_reauth_unique_id_mismatch(
hass: HomeAssistant,
mock_vitesy_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauth aborts when the credentials belong to another account."""
mock_config_entry.add_to_hass(hass)
mock_vitesy_client.get_user.return_value = {"id": "other-user"}
result = await mock_config_entry.start_reauth_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
assert mock_config_entry.data[CONF_PASSWORD] == "hunter2"
+16 -14
View File
@@ -4,9 +4,10 @@ from unittest.mock import AsyncMock
from aiovitesy.exceptions import CannotAuthenticate, CannotConnect, VitesyError
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.vitesy.coordinator import UPDATE_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
@@ -34,11 +35,15 @@ async def test_setup_auth_failure(
mock_vitesy_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test rejected credentials put the entry in an error state."""
"""Test rejected credentials during setup start a reauth flow."""
mock_vitesy_client.login.side_effect = CannotAuthenticate
await setup_integration(hass, mock_config_entry)
assert mock_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"] == mock_config_entry.entry_id
async def test_setup_connection_failure_is_retried(
@@ -73,27 +78,24 @@ async def test_update_failure_marks_entities_unavailable(
)
@pytest.mark.parametrize("method", ["get_all_devices", "get_mode_status"])
async def test_update_auth_failure(
hass: HomeAssistant,
mock_vitesy_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
method: str,
) -> None:
"""Test rejected credentials during a refresh keep the coordinator polling."""
"""Test rejected credentials during a refresh start a reauth flow."""
await setup_integration(hass, mock_config_entry)
mock_vitesy_client.get_all_devices.side_effect = CannotAuthenticate
getattr(mock_vitesy_client, method).side_effect = CannotAuthenticate
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
await hass.async_block_till_done(wait_background_tasks=True)
assert not mock_config_entry.runtime_data.last_update_success
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_vitesy_client.get_all_devices.side_effect = None
mock_vitesy_client.get_all_devices.return_value = {}
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_config_entry.runtime_data.last_update_success
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["context"]["source"] == SOURCE_REAUTH
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id