From 3258d572b04e6d304b64709b24ca50ab7b358c72 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Tue, 31 May 2022 23:46:12 +0200 Subject: [PATCH] Add re-auth flow to Tankerkoenig (#72682) * add reauth flow * add test * use Mapping for async_step_reauth arguments * only update changed data * improve tests * use different api key to test reauth --- .../components/tankerkoenig/__init__.py | 4 +- .../components/tankerkoenig/config_flow.py | 41 ++++++++++++++ .../components/tankerkoenig/strings.json | 8 ++- .../tankerkoenig/translations/en.json | 9 ++- .../tankerkoenig/test_config_flow.py | 55 ++++++++++++++++++- 5 files changed, 112 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/tankerkoenig/__init__.py b/homeassistant/components/tankerkoenig/__init__.py index e63add83fad..b7a15e82ea8 100644 --- a/homeassistant/components/tankerkoenig/__init__.py +++ b/homeassistant/components/tankerkoenig/__init__.py @@ -23,7 +23,7 @@ from homeassistant.const import ( Platform, ) from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady import homeassistant.helpers.config_validation as cv from homeassistant.helpers.device_registry import DeviceEntryType from homeassistant.helpers.entity import DeviceInfo @@ -187,6 +187,8 @@ class TankerkoenigDataUpdateCoordinator(DataUpdateCoordinator): try: station_data = pytankerkoenig.getStationData(self._api_key, station_id) except pytankerkoenig.customException as err: + if any(x in str(err).lower() for x in ("api-key", "apikey")): + raise ConfigEntryAuthFailed(err) from err station_data = { "ok": False, "message": err, diff --git a/homeassistant/components/tankerkoenig/config_flow.py b/homeassistant/components/tankerkoenig/config_flow.py index dd5893fe35f..77baeddfce9 100644 --- a/homeassistant/components/tankerkoenig/config_flow.py +++ b/homeassistant/components/tankerkoenig/config_flow.py @@ -144,6 +144,28 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): options={CONF_SHOW_ON_MAP: True}, ) + async def async_step_reauth(self, data: Mapping[str, Any]) -> FlowResult: + """Perform reauth upon an API authentication error.""" + return await self.async_step_reauth_confirm() + + async def async_step_reauth_confirm( + self, user_input: dict[str, Any] | None = None + ) -> FlowResult: + """Perform reauth confirm upon an API authentication error.""" + if not user_input: + return self._show_form_reauth() + + entry = self.hass.config_entries.async_get_entry(self.context["entry_id"]) + assert entry + user_input = {**entry.data, **user_input} + data = await async_get_nearby_stations(self.hass, user_input) + if not data.get("ok"): + return self._show_form_reauth(user_input, {CONF_API_KEY: "invalid_auth"}) + + self.hass.config_entries.async_update_entry(entry, data=user_input) + await self.hass.config_entries.async_reload(entry.entry_id) + return self.async_abort(reason="reauth_successful") + def _show_form_user( self, user_input: dict[str, Any] | None = None, @@ -190,6 +212,25 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): errors=errors, ) + def _show_form_reauth( + self, + user_input: dict[str, Any] | None = None, + errors: dict[str, Any] | None = None, + ) -> FlowResult: + if user_input is None: + user_input = {} + return self.async_show_form( + step_id="reauth_confirm", + data_schema=vol.Schema( + { + vol.Required( + CONF_API_KEY, default=user_input.get(CONF_API_KEY, "") + ): cv.string, + } + ), + errors=errors, + ) + def _create_entry( self, data: dict[str, Any], options: dict[str, Any] ) -> FlowResult: diff --git a/homeassistant/components/tankerkoenig/strings.json b/homeassistant/components/tankerkoenig/strings.json index 5e0c367c192..e0b9b3d53e8 100644 --- a/homeassistant/components/tankerkoenig/strings.json +++ b/homeassistant/components/tankerkoenig/strings.json @@ -11,6 +11,11 @@ "radius": "Search radius" } }, + "reauth_confirm": { + "data": { + "api_key": "[%key:common::config_flow::data::api_key%]" + } + }, "select_station": { "title": "Select stations to add", "description": "found {stations_count} stations in radius", @@ -20,7 +25,8 @@ } }, "abort": { - "already_configured": "[%key:common::config_flow::abort::already_configured_location%]" + "already_configured": "[%key:common::config_flow::abort::already_configured_location%]", + "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]" }, "error": { "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", diff --git a/homeassistant/components/tankerkoenig/translations/en.json b/homeassistant/components/tankerkoenig/translations/en.json index 432ad4481c8..9a69c8c812e 100644 --- a/homeassistant/components/tankerkoenig/translations/en.json +++ b/homeassistant/components/tankerkoenig/translations/en.json @@ -1,13 +1,19 @@ { "config": { "abort": { - "already_configured": "Location is already configured" + "already_configured": "Location is already configured", + "reauth_successful": "Re-authentication was successful" }, "error": { "invalid_auth": "Invalid authentication", "no_stations": "Could not find any station in range." }, "step": { + "reauth_confirm": { + "data": { + "api_key": "API Key" + } + }, "select_station": { "data": { "stations": "Stations" @@ -31,7 +37,6 @@ "step": { "init": { "data": { - "scan_interval": "Update Interval", "show_on_map": "Show stations on map", "stations": "Stations" }, diff --git a/tests/components/tankerkoenig/test_config_flow.py b/tests/components/tankerkoenig/test_config_flow.py index f48a09fd64b..cae78a447f8 100644 --- a/tests/components/tankerkoenig/test_config_flow.py +++ b/tests/components/tankerkoenig/test_config_flow.py @@ -8,7 +8,7 @@ from homeassistant.components.tankerkoenig.const import ( CONF_STATIONS, DOMAIN, ) -from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER +from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_REAUTH, SOURCE_USER from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE, @@ -222,6 +222,59 @@ async def test_import(hass: HomeAssistant): assert mock_setup_entry.called +async def test_reauth(hass: HomeAssistant): + """Test starting a flow by user to re-auth.""" + + mock_config = MockConfigEntry( + domain=DOMAIN, + data={**MOCK_USER_DATA, **MOCK_STATIONS_DATA}, + unique_id=f"{MOCK_USER_DATA[CONF_LOCATION][CONF_LATITUDE]}_{MOCK_USER_DATA[CONF_LOCATION][CONF_LONGITUDE]}", + ) + mock_config.add_to_hass(hass) + + with patch( + "homeassistant.components.tankerkoenig.async_setup_entry", return_value=True + ) as mock_setup_entry, patch( + "homeassistant.components.tankerkoenig.config_flow.getNearbyStations", + ) as mock_nearby_stations: + # re-auth initialized + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_REAUTH, "entry_id": mock_config.entry_id}, + data=mock_config.data, + ) + assert result["type"] == RESULT_TYPE_FORM + assert result["step_id"] == "reauth_confirm" + + # re-auth unsuccessful + mock_nearby_stations.return_value = {"ok": False} + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_API_KEY: "269534f6-aaaa-bbbb-cccc-yyyyzzzzxxxx", + }, + ) + assert result["type"] == RESULT_TYPE_FORM + assert result["step_id"] == "reauth_confirm" + assert result["errors"] == {CONF_API_KEY: "invalid_auth"} + + # re-auth successful + mock_nearby_stations.return_value = MOCK_NEARVY_STATIONS_OK + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + CONF_API_KEY: "269534f6-aaaa-bbbb-cccc-yyyyzzzzxxxx", + }, + ) + assert result["type"] == RESULT_TYPE_ABORT + assert result["reason"] == "reauth_successful" + + mock_setup_entry.assert_called() + + entry = hass.config_entries.async_get_entry(mock_config.entry_id) + assert entry.data[CONF_API_KEY] == "269534f6-aaaa-bbbb-cccc-yyyyzzzzxxxx" + + async def test_options_flow(hass: HomeAssistant): """Test options flow."""