mirror of
https://github.com/home-assistant/core.git
synced 2025-07-14 00:37:13 +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
|
||||
)
|
||||
|
||||
try:
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
except ConfigEntryAuthFailed:
|
||||
return False
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
@ -199,15 +196,17 @@ class VolvoData:
|
||||
|
||||
async def update(self):
|
||||
"""Update status from the online service."""
|
||||
if not await self.connection.update(journal=True):
|
||||
return False
|
||||
try:
|
||||
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:
|
||||
if vehicle.vin not in self.vehicles:
|
||||
self.discover_vehicle(vehicle)
|
||||
|
||||
return True
|
||||
|
||||
async def auth_is_valid(self):
|
||||
"""Check if provided username/password/region authenticate."""
|
||||
try:
|
||||
@ -235,8 +234,7 @@ class VolvoUpdateCoordinator(DataUpdateCoordinator):
|
||||
"""Fetch data from API endpoint."""
|
||||
|
||||
async with async_timeout.timeout(10):
|
||||
if not await self.volvo_data.update():
|
||||
raise UpdateFailed("Error communicating with API")
|
||||
await self.volvo_data.update()
|
||||
|
||||
|
||||
class VolvoEntity(CoordinatorEntity):
|
||||
|
@ -1,6 +1,7 @@
|
||||
"""Config flow for Volvo On Call integration."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
import logging
|
||||
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.data_entry_flow import FlowResult
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from . import VolvoData
|
||||
from .const import CONF_MUTABLE, CONF_SCANDINAVIAN_MILES, DOMAIN
|
||||
@ -19,32 +19,31 @@ from .errors import InvalidAuth
|
||||
|
||||
_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):
|
||||
"""VolvoOnCall config flow."""
|
||||
|
||||
VERSION = 1
|
||||
_reauth_entry: config_entries.ConfigEntry | None = None
|
||||
|
||||
async def async_step_user(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> FlowResult:
|
||||
"""Handle user step."""
|
||||
errors = {}
|
||||
defaults = {
|
||||
CONF_USERNAME: "",
|
||||
CONF_PASSWORD: "",
|
||||
CONF_REGION: None,
|
||||
CONF_MUTABLE: True,
|
||||
CONF_SCANDINAVIAN_MILES: False,
|
||||
}
|
||||
|
||||
if user_input is not None:
|
||||
await self.async_set_unique_id(user_input[CONF_USERNAME])
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
if not self._reauth_entry:
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
try:
|
||||
await self.is_valid(user_input)
|
||||
@ -54,18 +53,51 @@ class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
_LOGGER.exception("Unhandled exception in user step")
|
||||
errors["base"] = "unknown"
|
||||
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(
|
||||
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(
|
||||
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:
|
||||
"""Import volvooncall config from configuration.yaml."""
|
||||
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):
|
||||
"""Check for user input errors."""
|
||||
|
||||
|
@ -16,7 +16,8 @@
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
},
|
||||
"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": {
|
||||
|
@ -1,7 +1,8 @@
|
||||
{
|
||||
"config": {
|
||||
"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": {
|
||||
"invalid_auth": "Invalid authentication",
|
||||
@ -16,6 +17,10 @@
|
||||
"scandinavian_miles": "Use Scandinavian Miles",
|
||||
"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,
|
||||
}
|
||||
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