diff --git a/homeassistant/components/myneomitis/config_flow.py b/homeassistant/components/myneomitis/config_flow.py index a8c6066535cc..305198010c5e 100644 --- a/homeassistant/components/myneomitis/config_flow.py +++ b/homeassistant/components/myneomitis/config_flow.py @@ -1,5 +1,6 @@ """Config flow for MyNeomitis integration.""" +from collections.abc import Mapping import logging from typing import Any, override @@ -22,6 +23,35 @@ class MyNeoConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = 1 MINOR_VERSION = 1 + async def _async_login( + self, email: str, password: str + ) -> tuple[str | None, dict[str, str]]: + """Log in and return the user ID and errors.""" + errors: dict[str, str] = {} + session = async_get_clientsession(self.hass) + api = PyAxencoAPI(session) + + try: + await api.login(email, password) + except aiohttp.ClientResponseError as e: + if e.status == 401: + errors["base"] = "invalid_auth" + elif e.status >= 500: + errors["base"] = "cannot_connect" + else: + errors["base"] = "unknown" + except aiohttp.ClientConnectionError: + errors["base"] = "cannot_connect" + except aiohttp.ClientError: + errors["base"] = "unknown" + except Exception: + _LOGGER.exception("Unexpected error during login") + errors["base"] = "unknown" + else: + return api.user_id, errors + + return None, errors + @override async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -33,29 +63,11 @@ class MyNeoConfigFlow(ConfigFlow, domain=DOMAIN): email: str = user_input[CONF_EMAIL] password: str = user_input[CONF_PASSWORD] - session = async_get_clientsession(self.hass) - api = PyAxencoAPI(session) - - try: - await api.login(email, password) - except aiohttp.ClientResponseError as e: - if e.status == 401: - errors["base"] = "invalid_auth" - elif e.status >= 500: - errors["base"] = "cannot_connect" - else: - errors["base"] = "unknown" - except aiohttp.ClientConnectionError: - errors["base"] = "cannot_connect" - except aiohttp.ClientError: - errors["base"] = "unknown" - except Exception: - _LOGGER.exception("Unexpected error during login") - errors["base"] = "unknown" + user_id, errors = await self._async_login(email, password) if not errors: # Prevent duplicate configuration with the same user ID - await self.async_set_unique_id(api.user_id) + await self.async_set_unique_id(user_id) self._abort_if_unique_id_configured() return self.async_create_entry( @@ -63,7 +75,7 @@ class MyNeoConfigFlow(ConfigFlow, domain=DOMAIN): data={ CONF_EMAIL: email, CONF_PASSWORD: password, - CONF_USER_ID: api.user_id, + CONF_USER_ID: user_id, }, ) @@ -77,3 +89,42 @@ class MyNeoConfigFlow(ConfigFlow, domain=DOMAIN): ), errors=errors, ) + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Handle re-authentication.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm re-authentication with a new password.""" + errors: dict[str, str] = {} + reauth_entry = self._get_reauth_entry() + email: str = reauth_entry.data[CONF_EMAIL] + + if user_input is not None: + password: str = user_input[CONF_PASSWORD] + + user_id, errors = await self._async_login(email, password) + + if not errors: + 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: password}, + ) + + return self.async_show_form( + step_id="reauth_confirm", + data_schema=probatio.Schema( + { + probatio.Required(probatio.Secret(CONF_PASSWORD)): str, + } + ), + description_placeholders={CONF_EMAIL: email}, + errors=errors, + ) diff --git a/homeassistant/components/myneomitis/quality_scale.yaml b/homeassistant/components/myneomitis/quality_scale.yaml index 044aba32faa8..6c5c967db79a 100644 --- a/homeassistant/components/myneomitis/quality_scale.yaml +++ b/homeassistant/components/myneomitis/quality_scale.yaml @@ -46,7 +46,7 @@ rules: parallel-updates: status: exempt comment: Integration uses WebSocket callbacks to push updates directly to entities, not coordinator-based polling. - reauthentication-flow: todo + reauthentication-flow: done test-coverage: done # Gold tier rules diff --git a/homeassistant/components/myneomitis/strings.json b/homeassistant/components/myneomitis/strings.json index e768bc7c287f..04f0b7aa7fb3 100644 --- a/homeassistant/components/myneomitis/strings.json +++ b/homeassistant/components/myneomitis/strings.json @@ -1,7 +1,8 @@ { "config": { "abort": { - "already_configured": "This integration is already configured." + "already_configured": "This integration is already configured.", + "unique_id_mismatch": "The credentials belong to a different MyNeomitis account than the one originally configured." }, "error": { "cannot_connect": "Could not connect to the MyNeomitis service. Please try again later.", @@ -9,6 +10,15 @@ "unknown": "An unexpected error occurred. Please try again." }, "step": { + "reauth_confirm": { + "data": { + "password": "[%key:common::config_flow::data::password%]" + }, + "data_description": { + "password": "[%key:component::myneomitis::config::step::user::data_description::password%]" + }, + "description": "The password for {email} is no longer valid. Please enter your current MyNeomitis password." + }, "user": { "data": { "email": "[%key:common::config_flow::data::email%]", diff --git a/tests/components/myneomitis/test_config_flow.py b/tests/components/myneomitis/test_config_flow.py index 82a0365f88da..4e26755a78ca 100644 --- a/tests/components/myneomitis/test_config_flow.py +++ b/tests/components/myneomitis/test_config_flow.py @@ -123,3 +123,98 @@ async def test_abort_if_already_configured( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_flow( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_pyaxenco_client: AsyncMock, +) -> None: + """Test successful reauthentication flow.""" + 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: TEST_EMAIL, + "name": "MyNeomitis (test@example.com)", + } + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={CONF_PASSWORD: "new-password"}, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_EMAIL: TEST_EMAIL, + CONF_PASSWORD: "new-password", + CONF_USER_ID: "user-123", + } + mock_pyaxenco_client.login.assert_awaited_with(TEST_EMAIL, "new-password") + + +@pytest.mark.parametrize( + ("side_effect", "expected_error"), + [ + pytest.param(ClientConnectionError(), "cannot_connect", id="connection"), + pytest.param(make_client_response_error(401), "invalid_auth", id="401"), + pytest.param(make_client_response_error(403), "unknown", id="403"), + pytest.param(make_client_response_error(500), "cannot_connect", id="500"), + pytest.param(ClientError("Network error"), "unknown", id="client_error"), + pytest.param(RuntimeError("boom"), "unknown", id="unexpected"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_flow_errors( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_pyaxenco_client: AsyncMock, + side_effect: Exception, + expected_error: str, +) -> None: + """Test reauthentication flow errors and recovery.""" + mock_config_entry.add_to_hass(hass) + mock_pyaxenco_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"], + user_input={CONF_PASSWORD: "new-password"}, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {"base": expected_error} + + mock_pyaxenco_client.login.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={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_flow_wrong_account( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_pyaxenco_client: AsyncMock, +) -> None: + """Test reauthentication aborts when logging in to a different account.""" + mock_config_entry.add_to_hass(hass) + mock_pyaxenco_client.user_id = "other-user" + + result = await mock_config_entry.start_reauth_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={CONF_PASSWORD: "new-password"}, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert mock_config_entry.data[CONF_PASSWORD] == TEST_PASSWORD