1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 21:06:19 +00:00

Actron Air Integration: Add reauthentication flow (#158246)

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Joost Lekkerkerker <joostlek@outlook.com>
This commit is contained in:
Kurt Chrisford
2025-12-16 05:08:57 +10:00
committed by GitHub
parent 64ccde6709
commit 123d573274
10 changed files with 160 additions and 32 deletions

View File

@@ -9,8 +9,9 @@ from actron_neo_api import (
from homeassistant.const import CONF_API_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from .const import _LOGGER
from .const import _LOGGER, DOMAIN
from .coordinator import (
ActronAirConfigEntry,
ActronAirRuntimeData,
@@ -29,12 +30,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ActronAirConfigEntry) ->
try:
systems = await api.get_ac_systems()
await api.update_status()
except ActronAirAuthError:
_LOGGER.error("Authentication error while setting up Actron Air integration")
raise
except ActronAirAuthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_error",
) from err
except ActronAirAPIError as err:
_LOGGER.error("API error while setting up Actron Air integration: %s", err)
raise
raise ConfigEntryNotReady from err
system_coordinators: dict[str, ActronAirSystemCoordinator] = {}
for system in systems:

View File

@@ -1,11 +1,12 @@
"""Setup config flow for Actron Air integration."""
import asyncio
from collections.abc import Mapping
from typing import Any
from actron_neo_api import ActronAirAPI, ActronAirAuthError
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_TOKEN
from homeassistant.exceptions import HomeAssistantError
@@ -95,8 +96,16 @@ class ActronAirConfigFlow(ConfigFlow, domain=DOMAIN):
unique_id = str(user_data["id"])
await self.async_set_unique_id(unique_id)
self._abort_if_unique_id_configured()
# Check if this is a reauth flow
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch(reason="wrong_account")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={CONF_API_TOKEN: self._api.refresh_token_value},
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_data["email"],
data={CONF_API_TOKEN: self._api.refresh_token_value},
@@ -114,6 +123,21 @@ class ActronAirConfigFlow(ConfigFlow, domain=DOMAIN):
del self.login_task
return await self.async_step_user()
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reauthentication request."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauth dialog."""
if user_input is not None:
return await self.async_step_user()
return self.async_show_form(step_id="reauth_confirm")
async def async_step_connection_error(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:

View File

@@ -5,16 +5,23 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
from actron_neo_api import ActronAirACSystem, ActronAirAPI, ActronAirStatus
from actron_neo_api import (
ActronAirACSystem,
ActronAirAPI,
ActronAirAuthError,
ActronAirStatus,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util import dt as dt_util
from .const import _LOGGER
from .const import _LOGGER, DOMAIN
STALE_DEVICE_TIMEOUT = timedelta(hours=24)
SCAN_INTERVAL = timedelta(seconds=30)
STALE_DEVICE_TIMEOUT = timedelta(minutes=5)
ERROR_NO_SYSTEMS_FOUND = "no_systems_found"
ERROR_UNKNOWN = "unknown_error"
@@ -29,9 +36,6 @@ class ActronAirRuntimeData:
type ActronAirConfigEntry = ConfigEntry[ActronAirRuntimeData]
AUTH_ERROR_THRESHOLD = 3
SCAN_INTERVAL = timedelta(seconds=30)
class ActronAirSystemCoordinator(DataUpdateCoordinator[ActronAirACSystem]):
"""System coordinator for Actron Air integration."""
@@ -59,7 +63,14 @@ class ActronAirSystemCoordinator(DataUpdateCoordinator[ActronAirACSystem]):
async def _async_update_data(self) -> ActronAirStatus:
"""Fetch updates and merge incremental changes into the full state."""
await self.api.update_status()
try:
await self.api.update_status()
except ActronAirAuthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_error",
) from err
self.status = self.api.state_manager.get_status(self.serial_number)
self.last_seen = dt_util.utcnow()
return self.status

View File

@@ -13,5 +13,5 @@
"integration_type": "hub",
"iot_class": "cloud_polling",
"quality_scale": "bronze",
"requirements": ["actron-neo-api==0.1.87"]
"requirements": ["actron-neo-api==0.2.0"]
}

View File

@@ -36,7 +36,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: todo
# Gold

View File

@@ -2,10 +2,12 @@
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"oauth2_error": "Failed to start OAuth2 flow"
"oauth2_error": "Failed to start authentication flow",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"wrong_account": "You must reauthenticate with the same Actron Air account that was originally configured."
},
"error": {
"oauth2_error": "Failed to start OAuth2 flow. Please try again later."
"oauth2_error": "Failed to start authentication flow. Please try again later."
},
"progress": {
"wait_for_authorization": "To authenticate, open the following URL and login at Actron Air:\n{verification_uri}\nIf the code is not automatically copied, paste the following code to authorize the integration:\n\n```{user_code}```\n\n\nThe login attempt will time out after {expires_minutes} minutes."
@@ -16,14 +18,23 @@
"description": "Failed to connect to Actron Air. Please check your internet connection and try again.",
"title": "Connection error"
},
"reauth_confirm": {
"description": "Your Actron Air authentication has expired. Select continue to reauthenticate with your Actron Air account. You will be prompted to log in again to restore the connection.",
"title": "Authentication expired"
},
"timeout": {
"data": {},
"description": "The authorization process timed out. Please try again.",
"title": "Authorization timeout"
"description": "The authentication process timed out. Please try again.",
"title": "Authentication timeout"
},
"user": {
"title": "Actron Air OAuth2 Authorization"
"title": "Actron Air Authentication"
}
}
},
"exceptions": {
"auth_error": {
"message": "Authentication failed, please reauthenticate"
}
}
}

2
requirements_all.txt generated
View File

@@ -133,7 +133,7 @@ WSDiscovery==2.1.2
accuweather==4.2.2
# homeassistant.components.actron_air
actron-neo-api==0.1.87
actron-neo-api==0.2.0
# homeassistant.components.adax
adax==0.4.0

View File

@@ -124,7 +124,7 @@ WSDiscovery==2.1.2
accuweather==4.2.2
# homeassistant.components.actron_air
actron-neo-api==0.1.87
actron-neo-api==0.2.0
# homeassistant.components.adax
adax==0.4.0

View File

@@ -6,6 +6,11 @@ from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.actron_air.const import DOMAIN
from homeassistant.const import CONF_API_TOKEN
from tests.common import MockConfigEntry
@pytest.fixture
def mock_actron_api() -> Generator[AsyncMock]:
@@ -53,3 +58,14 @@ def mock_actron_api() -> Generator[AsyncMock]:
api.get_status = AsyncMock(return_value=None)
yield api
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Return a mock config entry."""
return MockConfigEntry(
domain=DOMAIN,
title="test@example.com",
data={CONF_API_TOKEN: "test_refresh_token"},
unique_id="test_user_id",
)

View File

@@ -148,17 +148,11 @@ async def test_user_flow_token_polling_error(
async def test_user_flow_duplicate_account(
hass: HomeAssistant, mock_actron_api: AsyncMock
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test duplicate account handling - should abort when same account is already configured."""
# Create an existing config entry for the same user account
existing_entry = MockConfigEntry(
domain=DOMAIN,
title="test@example.com",
data={CONF_API_TOKEN: "existing_refresh_token"},
unique_id="test_user_id",
)
existing_entry.add_to_hass(hass)
mock_config_entry.add_to_hass(hass)
# Start the config flow
result = await hass.config_entries.flow.async_init(
@@ -182,3 +176,73 @@ async def test_user_flow_duplicate_account(
# Should abort because the account is already configured
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow_success(
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test successful reauthentication flow."""
# Create an existing config entry
mock_config_entry.add_to_hass(hass)
existing_entry = mock_config_entry
# Start the reauth flow
result = await mock_config_entry.start_reauth_flow(hass)
# Should show the reauth confirmation form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# Submit the confirmation form to start the OAuth flow
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should update the existing entry with new token
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert existing_entry.data[CONF_API_TOKEN] == "test_refresh_token"
async def test_reauth_flow_wrong_account(
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test reauthentication flow with wrong account."""
# Create an existing config entry
mock_config_entry.add_to_hass(hass)
# Mock the API to return a different user ID
mock_actron_api.get_user_info = AsyncMock(
return_value={"id": "different_user_id", "email": "different@example.com"}
)
# Start the reauth flow
result = await mock_config_entry.start_reauth_flow(hass)
# Should show the reauth confirmation form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# Submit the confirmation form
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
# Continue the flow after progress is done
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should abort because of wrong account
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_account"