Skip to content

Commit

Permalink
Implement reauth flow for volvooncall (home-assistant#77328)
Browse files Browse the repository at this point in the history
* implement reauth flow

* added more tests

* implement feedback for __init__.py

* implemented feedback

* remove impossible return checks

* raise UpdateFailed when update fails
  • Loading branch information
y34hbuddy authored Aug 31, 2022
1 parent de9f22f commit a9fe985
Show file tree
Hide file tree
Showing 5 changed files with 116 additions and 27 deletions.
18 changes: 8 additions & 10 deletions homeassistant/components/volvooncall/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -199,15 +196,17 @@ def discover_vehicle(self, vehicle):

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:
Expand Down Expand Up @@ -235,8 +234,7 @@ async def _async_update_data(self):
"""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):
Expand Down
62 changes: 47 additions & 15 deletions homeassistant/components/volvooncall/config_flow.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -11,40 +12,38 @@
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
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)
Expand All @@ -54,18 +53,51 @@ async def async_step_user(
_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."""

Expand Down
3 changes: 2 additions & 1 deletion homeassistant/components/volvooncall/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
7 changes: 6 additions & 1 deletion homeassistant/components/volvooncall/translations/en.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -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"
}
}
},
Expand Down
53 changes: 53 additions & 0 deletions tests/components/volvooncall/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

0 comments on commit a9fe985

Please sign in to comment.