mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add reauthentication flow to Epion (#186207)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
972c8ba899
commit
91bd5a8d2e
@@ -1,5 +1,6 @@
|
||||
"""Config flow for Epion."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
import logging
|
||||
from typing import Any, override
|
||||
|
||||
@@ -13,29 +14,44 @@ from .const import DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
STEP_USER_DATA_SCHEMA = probatio.Schema(
|
||||
{
|
||||
probatio.Required(probatio.Secret(CONF_API_KEY)): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class EpionConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for Epion."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def _async_validate_api_key(
|
||||
self, api_key: str
|
||||
) -> tuple[str | None, dict[str, str]]:
|
||||
"""Validate the API key and return the account ID and errors."""
|
||||
api = Epion(api_key)
|
||||
try:
|
||||
api_data = await self.hass.async_add_executor_job(api.get_current)
|
||||
except EpionAuthenticationError:
|
||||
return None, {"base": "invalid_auth"}
|
||||
except EpionConnectionError:
|
||||
_LOGGER.error("Unexpected problem when configuring Epion API")
|
||||
return None, {"base": "cannot_connect"}
|
||||
return api_data["accountId"], {}
|
||||
|
||||
@override
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle a flow initiated by the user."""
|
||||
errors = {}
|
||||
errors: dict[str, str] = {}
|
||||
if user_input:
|
||||
api = Epion(user_input[CONF_API_KEY])
|
||||
try:
|
||||
api_data = await self.hass.async_add_executor_job(api.get_current)
|
||||
except EpionAuthenticationError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except EpionConnectionError:
|
||||
_LOGGER.error("Unexpected problem when configuring Epion API")
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(api_data["accountId"])
|
||||
account_id, errors = await self._async_validate_api_key(
|
||||
user_input[CONF_API_KEY]
|
||||
)
|
||||
if not errors:
|
||||
await self.async_set_unique_id(account_id)
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title="Epion integration",
|
||||
@@ -44,10 +60,35 @@ class EpionConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=probatio.Schema(
|
||||
{
|
||||
probatio.Required(probatio.Secret(CONF_API_KEY)): str,
|
||||
}
|
||||
),
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
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."""
|
||||
errors: dict[str, str] = {}
|
||||
if user_input:
|
||||
account_id, errors = await self._async_validate_api_key(
|
||||
user_input[CONF_API_KEY]
|
||||
)
|
||||
if not errors:
|
||||
await self.async_set_unique_id(account_id)
|
||||
self._abort_if_unique_id_mismatch()
|
||||
return self.async_update_reload_and_abort(
|
||||
self._get_reauth_entry(),
|
||||
data_updates={CONF_API_KEY: user_input[CONF_API_KEY]},
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
{
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]"
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
|
||||
"unique_id_mismatch": "The API key belongs to a different Epion account than the one 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": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
},
|
||||
"description": "Your Epion API key is no longer valid. Please enter a new API key to continue."
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
|
||||
@@ -14,6 +14,8 @@ from homeassistant.data_entry_flow import FlowResultType
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
API_KEY = "test-key-123"
|
||||
NEW_API_KEY = "new-key-456"
|
||||
ACCOUNT_ID = "account-dupe-123"
|
||||
|
||||
|
||||
async def test_user_flow(hass: HomeAssistant, mock_epion: MagicMock) -> None:
|
||||
@@ -110,3 +112,105 @@ async def test_duplicate_entry(hass: HomeAssistant, mock_epion: MagicMock) -> No
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
|
||||
|
||||
async def test_reauth_flow(hass: HomeAssistant, mock_epion: MagicMock) -> None:
|
||||
"""Test reauthentication updates the API key."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_API_KEY: API_KEY},
|
||||
unique_id=ACCOUNT_ID,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.epion.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: NEW_API_KEY},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert entry.data == {CONF_API_KEY: NEW_API_KEY}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exception", "error"),
|
||||
[
|
||||
pytest.param(
|
||||
EpionAuthenticationError("Invalid auth"), "invalid_auth", id="invalid_auth"
|
||||
),
|
||||
pytest.param(
|
||||
EpionConnectionError("Timeout error"), "cannot_connect", id="cannot_connect"
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_reauth_flow_errors(
|
||||
hass: HomeAssistant, exception: Exception, error: str, mock_epion: MagicMock
|
||||
) -> None:
|
||||
"""Test reauthentication errors and recovery."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_API_KEY: API_KEY},
|
||||
unique_id=ACCOUNT_ID,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
|
||||
mock_epion.return_value.get_current.side_effect = exception
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: NEW_API_KEY},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {"base": error}
|
||||
|
||||
mock_epion.return_value.get_current.side_effect = None
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.epion.async_setup_entry",
|
||||
return_value=True,
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: NEW_API_KEY},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert entry.data == {CONF_API_KEY: NEW_API_KEY}
|
||||
|
||||
|
||||
async def test_reauth_flow_wrong_account(
|
||||
hass: HomeAssistant, mock_epion: MagicMock
|
||||
) -> None:
|
||||
"""Test reauthentication with an API key of a different account."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_API_KEY: API_KEY},
|
||||
unique_id="other-account-456",
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{CONF_API_KEY: NEW_API_KEY},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "unique_id_mismatch"
|
||||
assert entry.data == {CONF_API_KEY: API_KEY}
|
||||
|
||||
Reference in New Issue
Block a user