Add reconfigure flow to ring integration (#128357)

Co-authored-by: Christopher Fenner <9592452+CFenner@users.noreply.github.com>
Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
Steven B. 2024-10-21 14:30:05 +01:00 committed by GitHub
parent c0f1996478
commit f8f87ec091
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 161 additions and 2 deletions

View file

@ -9,7 +9,12 @@ from ring_doorbell import Auth, AuthenticationError, Requires2FAError
import voluptuous as vol
from homeassistant.components import dhcp
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
from homeassistant.config_entries import (
SOURCE_REAUTH,
SOURCE_RECONFIGURE,
ConfigFlow,
ConfigFlowResult,
)
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_NAME,
@ -136,6 +141,11 @@ class RingConfigFlow(ConfigFlow, domain=DOMAIN):
{**self.user_pass, **user_input}
)
if self.source == SOURCE_RECONFIGURE:
return await self.async_step_reconfigure(
{**self.user_pass, **user_input}
)
return await self.async_step_user({**self.user_pass, **user_input})
return self.async_show_form(
@ -191,6 +201,48 @@ class RingConfigFlow(ConfigFlow, domain=DOMAIN):
},
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Trigger a reconfiguration flow."""
errors: dict[str, str] = {}
reconfigure_entry = self._get_reconfigure_entry()
username = reconfigure_entry.data[CONF_USERNAME]
await self.async_set_unique_id(username)
if user_input:
user_input[CONF_USERNAME] = username
# Reconfigure will generate a new hardware id and create a new
# authorised device at ring.com.
if not self.hardware_id:
self.hardware_id = str(uuid.uuid4())
try:
assert self.hardware_id
token = await validate_input(self.hass, self.hardware_id, user_input)
except Require2FA:
self.user_pass = user_input
return await self.async_step_2fa()
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
data = {
CONF_USERNAME: username,
CONF_TOKEN: token,
CONF_DEVICE_ID: self.hardware_id,
}
return self.async_update_reload_and_abort(reconfigure_entry, data=data)
return self.async_show_form(
step_id="reconfigure",
data_schema=STEP_RECONFIGURE_DATA_SCHEMA,
errors=errors,
description_placeholders={
CONF_USERNAME: username,
},
)
class Require2FA(HomeAssistantError):
"""Error to indicate we require 2FA."""

View file

@ -20,6 +20,13 @@
"data": {
"password": "[%key:common::config_flow::data::password%]"
}
},
"reconfigure": {
"title": "Reconfigure Ring Integration",
"description": "Will create a new Authorized Device for {username} at ring.com",
"data": {
"password": "[%key:common::config_flow::data::password%]"
}
}
},
"error": {
@ -28,7 +35,8 @@
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]"
}
},
"entity": {

View file

@ -308,3 +308,102 @@ async def test_dhcp_discovery(
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reconfigure(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_ring_client: Mock,
mock_added_config_entry: MockConfigEntry,
) -> None:
"""Test the reconfigure config flow."""
assert mock_added_config_entry.data[CONF_DEVICE_ID] == MOCK_HARDWARE_ID
result = await mock_added_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
with patch("uuid.uuid4", return_value="new-hardware-id"):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"password": "test-password"},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reconfigure_successful"
assert mock_added_config_entry.data[CONF_DEVICE_ID] == "new-hardware-id"
@pytest.mark.parametrize(
("error_type", "errors_msg"),
[
(ring_doorbell.AuthenticationError, "invalid_auth"),
(Exception, "unknown"),
],
ids=["invalid-auth", "unknown-error"],
)
async def test_reconfigure_errors(
hass: HomeAssistant,
mock_added_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
mock_ring_auth: Mock,
error_type,
errors_msg,
) -> None:
"""Test errors during the reconfigure config flow."""
result = await mock_added_config_entry.start_reconfigure_flow(hass)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_ring_auth.async_fetch_token.side_effect = error_type
with patch("uuid.uuid4", return_value="new-hardware-id"):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: "error_fake_password",
},
)
await hass.async_block_till_done()
mock_ring_auth.async_fetch_token.assert_called_with(
"foo@bar.com", "error_fake_password", None
)
mock_ring_auth.async_fetch_token.side_effect = ring_doorbell.Requires2FAError
result3 = await hass.config_entries.flow.async_configure(
result2["flow_id"],
user_input={
CONF_PASSWORD: "other_fake_password",
},
)
mock_ring_auth.async_fetch_token.assert_called_with(
"foo@bar.com", "other_fake_password", None
)
assert result3["type"] is FlowResultType.FORM
assert result3["step_id"] == "2fa"
# Now test reconfigure can go on to succeed
mock_ring_auth.async_fetch_token.reset_mock(side_effect=True)
mock_ring_auth.async_fetch_token.return_value = "new-foobar"
result4 = await hass.config_entries.flow.async_configure(
result3["flow_id"],
user_input={"2fa": "123456"},
)
mock_ring_auth.async_fetch_token.assert_called_with(
"foo@bar.com", "other_fake_password", "123456"
)
assert result4["type"] is FlowResultType.ABORT
assert result4["reason"] == "reconfigure_successful"
assert mock_added_config_entry.data == {
CONF_DEVICE_ID: "new-hardware-id",
CONF_USERNAME: "foo@bar.com",
CONF_TOKEN: "new-foobar",
}
assert len(mock_setup_entry.mock_calls) == 1