mirror of
https://github.com/home-assistant/core.git
synced 2026-10-06 06:15:47 -04:00
Add reauthentication to Axle Energy (#182389)
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
"""Config flow for Axle Energy."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, override
|
||||
|
||||
from aioaxlevpp import (
|
||||
@@ -12,6 +13,7 @@ import probatio
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.data_entry_flow import AbortFlow
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.selector import (
|
||||
TextSelector,
|
||||
@@ -66,3 +68,35 @@ class AxleConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
},
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
async def async_step_reauth(
|
||||
self, entry_data: Mapping[str, Any]
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle an API key that is no longer accepted."""
|
||||
return await self.async_step_reauth_confirm()
|
||||
|
||||
async def async_step_reauth_confirm(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Validate a replacement API key and reload the existing feed."""
|
||||
errors = {}
|
||||
if user_input is not None:
|
||||
try:
|
||||
self._async_abort_entries_match(
|
||||
{CONF_API_KEY: user_input[CONF_API_KEY]}
|
||||
)
|
||||
except AbortFlow:
|
||||
errors[CONF_API_KEY] = "already_configured"
|
||||
else:
|
||||
if not (errors := await self._validate(user_input)):
|
||||
return self.async_update_reload_and_abort(
|
||||
self._get_reauth_entry(), data_updates=user_input
|
||||
)
|
||||
return self.async_show_form(
|
||||
step_id="reauth_confirm",
|
||||
data_schema=STEP_SCHEMA,
|
||||
description_placeholders={
|
||||
"token_url": "https://vpp.axle.energy/app/account/home-assistant"
|
||||
},
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@@ -39,7 +39,7 @@ rules:
|
||||
integration-owner: done
|
||||
log-when-unavailable: done
|
||||
parallel-updates: done
|
||||
reauthentication-flow: todo
|
||||
reauthentication-flow: done
|
||||
test-coverage: done
|
||||
devices: done
|
||||
diagnostics: todo
|
||||
|
||||
@@ -4,11 +4,21 @@
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
|
||||
},
|
||||
"error": {
|
||||
"already_configured": "This API key is already used by another entry.",
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"cannot_retrieve": "[%key:component::axle_energy::exceptions::cannot_connect::message%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]"
|
||||
},
|
||||
"step": {
|
||||
"reauth_confirm": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "[%key:component::axle_energy::config::step::user::data_description::api_key%]"
|
||||
},
|
||||
"description": "Your Axle API key is no longer accepted. Open the [Home Assistant page in your Axle account]({token_url}) and copy your Home Assistant token. If **Generate Token** is available, select it first. Enter the token in **API key**. If the token is still rejected, contact Axle support."
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||
|
||||
@@ -6,10 +6,11 @@ from aioaxlevpp import AxleAuthenticationError, AxleConnectionError, AxleError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.axle_energy.const import DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_USER
|
||||
from homeassistant.config_entries import SOURCE_USER, ConfigEntryState
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
@@ -78,3 +79,118 @@ async def test_duplicate(
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "already_configured"
|
||||
mock_client.get_event.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_key", ["replacement-token", "test-token"])
|
||||
async def test_reauth(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: AsyncMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
api_key: str,
|
||||
) -> None:
|
||||
"""Reauthenticate the existing feed, including when no event is scheduled."""
|
||||
mock_client.get_event.return_value = None
|
||||
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"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: api_key}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert mock_config_entry.data == {CONF_API_KEY: api_key}
|
||||
assert hass.config_entries.async_entries(DOMAIN) == [mock_config_entry]
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
mock_setup_entry.assert_awaited_once_with(hass, mock_config_entry)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("error", "message"),
|
||||
[
|
||||
(AxleAuthenticationError(), "invalid_auth"),
|
||||
(AxleConnectionError(), "cannot_connect"),
|
||||
(AxleError(), "cannot_retrieve"),
|
||||
],
|
||||
)
|
||||
async def test_reauth_errors(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: AsyncMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
error: Exception,
|
||||
message: str,
|
||||
) -> None:
|
||||
"""Keep the existing key after a failed replacement and allow a retry."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
mock_client.get_event.side_effect = error
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "replacement-token"}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {"base": message}
|
||||
assert mock_config_entry.data == {CONF_API_KEY: "test-token"}
|
||||
mock_setup_entry.assert_not_called()
|
||||
|
||||
mock_client.get_event.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "replacement-token"}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert mock_config_entry.data == {CONF_API_KEY: "replacement-token"}
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
mock_setup_entry.assert_awaited_once_with(hass, mock_config_entry)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_key", ["replacement-token", "test-token"])
|
||||
async def test_reauth_duplicate(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: AsyncMock,
|
||||
mock_setup_entry: AsyncMock,
|
||||
api_key: str,
|
||||
) -> None:
|
||||
"""Keep reauthentication open after a duplicate key and allow a retry."""
|
||||
assert await async_setup_component(hass, DOMAIN, {})
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
other_entry = MockConfigEntry(domain=DOMAIN, data={CONF_API_KEY: "other-token"})
|
||||
other_entry.add_to_hass(hass)
|
||||
result = await mock_config_entry.start_reauth_flow(hass)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: "other-token"}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
assert result["errors"] == {CONF_API_KEY: "already_configured"}
|
||||
assert mock_config_entry.data == {CONF_API_KEY: "test-token"}
|
||||
assert other_entry.data == {CONF_API_KEY: "other-token"}
|
||||
mock_client.get_event.assert_not_called()
|
||||
mock_setup_entry.assert_not_called()
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_API_KEY: api_key}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert mock_config_entry.data == {CONF_API_KEY: api_key}
|
||||
assert other_entry.data == {CONF_API_KEY: "other-token"}
|
||||
assert hass.config_entries.async_entries(DOMAIN) == [mock_config_entry, other_entry]
|
||||
mock_client.get_event.assert_awaited_once()
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
mock_setup_entry.assert_awaited_once_with(hass, mock_config_entry)
|
||||
|
||||
@@ -14,7 +14,11 @@ from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.axle_energy.const import DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_REAUTH
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
|
||||
@@ -142,7 +146,7 @@ async def test_authentication_failure(
|
||||
mock_client: AsyncMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
) -> None:
|
||||
"""Stop polling after the service rejects the credentials."""
|
||||
"""Stop polling on rejected credentials and resume after reauthentication."""
|
||||
await setup(hass, mock_config_entry)
|
||||
mock_client.get_event.side_effect = AxleAuthenticationError()
|
||||
freezer.tick(timedelta(minutes=10))
|
||||
@@ -154,3 +158,22 @@ async def test_authentication_failure(
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
mock_client.get_event.assert_not_called()
|
||||
|
||||
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
|
||||
assert len(flows) == 1
|
||||
assert flows[0]["context"]["source"] == SOURCE_REAUTH
|
||||
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id
|
||||
mock_client.get_event.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
flows[0]["flow_id"], {CONF_API_KEY: "replacement-token"}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
assert hass.states.get("sensor.axle_energy_event_type").state == "export"
|
||||
|
||||
mock_client.get_event.reset_mock()
|
||||
freezer.tick(timedelta(minutes=10))
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
mock_client.get_event.assert_awaited_once()
|
||||
|
||||
Reference in New Issue
Block a user