mirror of
https://github.com/home-assistant/core.git
synced 2025-07-18 02:37:08 +00:00
Implement reauth flow for volvooncall (#77328)
* implement reauth flow * added more tests * implement feedback for __init__.py * implemented feedback * remove impossible return checks * raise UpdateFailed when update fails
This commit is contained in:
parent
de9f22f308
commit
a9fe9857bd
@ -127,10 +127,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
hass, volvo_data
|
hass, volvo_data
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
|
||||||
await coordinator.async_config_entry_first_refresh()
|
await coordinator.async_config_entry_first_refresh()
|
||||||
except ConfigEntryAuthFailed:
|
|
||||||
return False
|
|
||||||
|
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|
||||||
@ -199,15 +196,17 @@ class VolvoData:
|
|||||||
|
|
||||||
async def update(self):
|
async def update(self):
|
||||||
"""Update status from the online service."""
|
"""Update status from the online service."""
|
||||||
if not await self.connection.update(journal=True):
|
try:
|
||||||
return False
|
await self.connection.update(journal=True)
|
||||||
|
except ClientResponseError as ex:
|
||||||
|
if ex.status == 401:
|
||||||
|
raise ConfigEntryAuthFailed(ex) from ex
|
||||||
|
raise UpdateFailed(ex) from ex
|
||||||
|
|
||||||
for vehicle in self.connection.vehicles:
|
for vehicle in self.connection.vehicles:
|
||||||
if vehicle.vin not in self.vehicles:
|
if vehicle.vin not in self.vehicles:
|
||||||
self.discover_vehicle(vehicle)
|
self.discover_vehicle(vehicle)
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
async def auth_is_valid(self):
|
async def auth_is_valid(self):
|
||||||
"""Check if provided username/password/region authenticate."""
|
"""Check if provided username/password/region authenticate."""
|
||||||
try:
|
try:
|
||||||
@ -235,8 +234,7 @@ class VolvoUpdateCoordinator(DataUpdateCoordinator):
|
|||||||
"""Fetch data from API endpoint."""
|
"""Fetch data from API endpoint."""
|
||||||
|
|
||||||
async with async_timeout.timeout(10):
|
async with async_timeout.timeout(10):
|
||||||
if not await self.volvo_data.update():
|
await self.volvo_data.update()
|
||||||
raise UpdateFailed("Error communicating with API")
|
|
||||||
|
|
||||||
|
|
||||||
class VolvoEntity(CoordinatorEntity):
|
class VolvoEntity(CoordinatorEntity):
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
"""Config flow for Volvo On Call integration."""
|
"""Config flow for Volvo On Call integration."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Mapping
|
||||||
import logging
|
import logging
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -11,7 +12,6 @@ from homeassistant import config_entries
|
|||||||
from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_USERNAME
|
from homeassistant.const import CONF_PASSWORD, CONF_REGION, CONF_USERNAME
|
||||||
from homeassistant.data_entry_flow import FlowResult
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||||
import homeassistant.helpers.config_validation as cv
|
|
||||||
|
|
||||||
from . import VolvoData
|
from . import VolvoData
|
||||||
from .const import CONF_MUTABLE, CONF_SCANDINAVIAN_MILES, DOMAIN
|
from .const import CONF_MUTABLE, CONF_SCANDINAVIAN_MILES, DOMAIN
|
||||||
@ -19,31 +19,30 @@ from .errors import InvalidAuth
|
|||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
USER_SCHEMA = vol.Schema(
|
|
||||||
{
|
|
||||||
vol.Required(CONF_USERNAME): cv.string,
|
|
||||||
vol.Required(CONF_PASSWORD): cv.string,
|
|
||||||
vol.Required(CONF_REGION, default=None): vol.In(
|
|
||||||
{"na": "North America", "cn": "China", None: "Rest of world"}
|
|
||||||
),
|
|
||||||
vol.Optional(CONF_MUTABLE, default=True): cv.boolean,
|
|
||||||
vol.Optional(CONF_SCANDINAVIAN_MILES, default=False): cv.boolean,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
"""VolvoOnCall config flow."""
|
"""VolvoOnCall config flow."""
|
||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
_reauth_entry: config_entries.ConfigEntry | None = None
|
||||||
|
|
||||||
async def async_step_user(
|
async def async_step_user(
|
||||||
self, user_input: dict[str, Any] | None = None
|
self, user_input: dict[str, Any] | None = None
|
||||||
) -> FlowResult:
|
) -> FlowResult:
|
||||||
"""Handle user step."""
|
"""Handle user step."""
|
||||||
errors = {}
|
errors = {}
|
||||||
|
defaults = {
|
||||||
|
CONF_USERNAME: "",
|
||||||
|
CONF_PASSWORD: "",
|
||||||
|
CONF_REGION: None,
|
||||||
|
CONF_MUTABLE: True,
|
||||||
|
CONF_SCANDINAVIAN_MILES: False,
|
||||||
|
}
|
||||||
|
|
||||||
if user_input is not None:
|
if user_input is not None:
|
||||||
await self.async_set_unique_id(user_input[CONF_USERNAME])
|
await self.async_set_unique_id(user_input[CONF_USERNAME])
|
||||||
|
|
||||||
|
if not self._reauth_entry:
|
||||||
self._abort_if_unique_id_configured()
|
self._abort_if_unique_id_configured()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -54,18 +53,51 @@ class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
_LOGGER.exception("Unhandled exception in user step")
|
_LOGGER.exception("Unhandled exception in user step")
|
||||||
errors["base"] = "unknown"
|
errors["base"] = "unknown"
|
||||||
if not errors:
|
if not errors:
|
||||||
|
if self._reauth_entry:
|
||||||
|
self.hass.config_entries.async_update_entry(
|
||||||
|
self._reauth_entry, data=self._reauth_entry.data | user_input
|
||||||
|
)
|
||||||
|
await self.hass.config_entries.async_reload(
|
||||||
|
self._reauth_entry.entry_id
|
||||||
|
)
|
||||||
|
return self.async_abort(reason="reauth_successful")
|
||||||
|
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title=user_input[CONF_USERNAME], data=user_input
|
title=user_input[CONF_USERNAME], data=user_input
|
||||||
)
|
)
|
||||||
|
elif self._reauth_entry:
|
||||||
|
for key in defaults:
|
||||||
|
defaults[key] = self._reauth_entry.data.get(key)
|
||||||
|
|
||||||
|
user_schema = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_USERNAME, default=defaults[CONF_USERNAME]): str,
|
||||||
|
vol.Required(CONF_PASSWORD, default=defaults[CONF_PASSWORD]): str,
|
||||||
|
vol.Required(CONF_REGION, default=defaults[CONF_REGION]): vol.In(
|
||||||
|
{"na": "North America", "cn": "China", None: "Rest of world"}
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_MUTABLE, default=defaults[CONF_MUTABLE]): bool,
|
||||||
|
vol.Optional(
|
||||||
|
CONF_SCANDINAVIAN_MILES, default=defaults[CONF_SCANDINAVIAN_MILES]
|
||||||
|
): bool,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="user", data_schema=USER_SCHEMA, errors=errors
|
step_id="user", data_schema=user_schema, errors=errors
|
||||||
)
|
)
|
||||||
|
|
||||||
async def async_step_import(self, import_data) -> FlowResult:
|
async def async_step_import(self, import_data) -> FlowResult:
|
||||||
"""Import volvooncall config from configuration.yaml."""
|
"""Import volvooncall config from configuration.yaml."""
|
||||||
return await self.async_step_user(import_data)
|
return await self.async_step_user(import_data)
|
||||||
|
|
||||||
|
async def async_step_reauth(self, user_input: Mapping[str, Any]) -> FlowResult:
|
||||||
|
"""Perform reauth upon an API authentication error."""
|
||||||
|
self._reauth_entry = self.hass.config_entries.async_get_entry(
|
||||||
|
self.context["entry_id"]
|
||||||
|
)
|
||||||
|
return await self.async_step_user()
|
||||||
|
|
||||||
async def is_valid(self, user_input):
|
async def is_valid(self, user_input):
|
||||||
"""Check for user input errors."""
|
"""Check for user input errors."""
|
||||||
|
|
||||||
|
@ -16,7 +16,8 @@
|
|||||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "Account is already configured"
|
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
|
||||||
|
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"issues": {
|
"issues": {
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "Account is already configured"
|
"reauth_successful": "You have successfully re-authenticated to Volvo On Call",
|
||||||
|
"cant_reauth": "Could not find original configuration that needs reauthentication"
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
"invalid_auth": "Invalid authentication",
|
"invalid_auth": "Invalid authentication",
|
||||||
@ -16,6 +17,10 @@
|
|||||||
"scandinavian_miles": "Use Scandinavian Miles",
|
"scandinavian_miles": "Use Scandinavian Miles",
|
||||||
"username": "Username"
|
"username": "Username"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"reauth_confirm": {
|
||||||
|
"title": "Re-authentication Required",
|
||||||
|
"description": "The Volvo On Call integration needs to re-authenticate your account"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -167,3 +167,56 @@ async def test_import(hass: HomeAssistant) -> None:
|
|||||||
"scandinavian_miles": False,
|
"scandinavian_miles": False,
|
||||||
}
|
}
|
||||||
assert len(mock_setup_entry.mock_calls) == 1
|
assert len(mock_setup_entry.mock_calls) == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_reauth(hass: HomeAssistant) -> None:
|
||||||
|
"""Test that we handle the reauth flow."""
|
||||||
|
|
||||||
|
first_entry = MockConfigEntry(
|
||||||
|
domain=DOMAIN,
|
||||||
|
unique_id="test-username",
|
||||||
|
data={
|
||||||
|
"username": "test-username",
|
||||||
|
"password": "test-password",
|
||||||
|
"region": "na",
|
||||||
|
"mutable": True,
|
||||||
|
"scandinavian_miles": False,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
first_entry.add_to_hass(hass)
|
||||||
|
|
||||||
|
result = await hass.config_entries.flow.async_init(
|
||||||
|
DOMAIN,
|
||||||
|
context={
|
||||||
|
"source": config_entries.SOURCE_REAUTH,
|
||||||
|
"entry_id": first_entry.entry_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# the first form is just the confirmation prompt
|
||||||
|
assert result["type"] == FlowResultType.FORM
|
||||||
|
|
||||||
|
result2 = await hass.config_entries.flow.async_configure(
|
||||||
|
result["flow_id"],
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
# the second form is the user flow where reauth happens
|
||||||
|
assert result2["type"] == FlowResultType.FORM
|
||||||
|
|
||||||
|
with patch("volvooncall.Connection.get"):
|
||||||
|
result3 = await hass.config_entries.flow.async_configure(
|
||||||
|
result2["flow_id"],
|
||||||
|
{
|
||||||
|
"username": "test-username",
|
||||||
|
"password": "test-new-password",
|
||||||
|
"region": "na",
|
||||||
|
"mutable": True,
|
||||||
|
"scandinavian_miles": False,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
await hass.async_block_till_done()
|
||||||
|
|
||||||
|
assert result3["type"] == FlowResultType.ABORT
|
||||||
|
assert result3["reason"] == "reauth_successful"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user