Reauthentication flow for Watts Vision + integration (#163141)

This commit is contained in:
theobld-ww
2026-02-16 19:00:49 +01:00
committed by GitHub
parent e49767d37a
commit 9dc38eda9f
5 changed files with 141 additions and 3 deletions
+30 -1
View File
@@ -1,11 +1,12 @@
"""Config flow for Watts Vision integration."""
from collections.abc import Mapping
import logging
from typing import Any
from visionpluspython.auth import WattsVisionAuth
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN, OAUTH2_SCOPES
@@ -32,6 +33,25 @@ class OAuth2FlowHandler(
"prompt": "consent",
}
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauthentication upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauthentication dialog."""
if user_input is None:
return self.async_show_form(step_id="reauth_confirm")
return await self.async_step_pick_implementation(
user_input={
"implementation": self._get_reauth_entry().data["auth_implementation"]
}
)
async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
"""Create an entry for the OAuth2 flow."""
@@ -42,6 +62,15 @@ class OAuth2FlowHandler(
return self.async_abort(reason="invalid_token")
await self.async_set_unique_id(user_id)
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch(reason="reauth_account_mismatch")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data=data,
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
+1 -1
View File
@@ -6,6 +6,6 @@
"dependencies": ["application_credentials", "cloud"],
"documentation": "https://www.home-assistant.io/integrations/watts",
"iot_class": "cloud_polling",
"quality_scale": "bronze",
"quality_scale": "silver",
"requirements": ["visionpluspython==1.0.2"]
}
@@ -30,7 +30,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done
# Gold
@@ -12,6 +12,8 @@
"oauth_implementation_unavailable": "[%key:common::config_flow::abort::oauth2_implementation_unavailable%]",
"oauth_timeout": "[%key:common::config_flow::abort::oauth2_timeout%]",
"oauth_unauthorized": "[%key:common::config_flow::abort::oauth2_unauthorized%]",
"reauth_account_mismatch": "The authenticated account does not match the account that needed re-authentication",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"user_rejected_authorize": "[%key:common::config_flow::abort::oauth2_user_rejected_authorize%]"
},
"create_entry": {
@@ -20,6 +22,10 @@
"step": {
"pick_implementation": {
"title": "[%key:common::config_flow::title::oauth2_pick_implementation%]"
},
"reauth_confirm": {
"description": "The Watts Vision + integration needs to re-authenticate your account",
"title": "[%key:common::config_flow::title::reauth%]"
}
}
},
+103
View File
@@ -197,6 +197,109 @@ async def test_oauth_invalid_response(
assert result.get("reason") == "oauth_failed"
@pytest.mark.usefixtures("current_request_with_host", "mock_setup_entry")
async def test_reauth_flow(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the reauthentication flow."""
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"], {})
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "new-refresh-token",
"access_token": "new-access-token",
"token_type": "Bearer",
"expires_in": 3600,
},
)
with patch(
"homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token",
return_value="test-user-id",
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
mock_config_entry.data["token"].pop("expires_at")
assert mock_config_entry.data["token"] == {
"refresh_token": "new-refresh-token",
"access_token": "new-access-token",
"token_type": "Bearer",
"expires_in": 3600,
}
@pytest.mark.usefixtures("current_request_with_host")
async def test_reauth_account_mismatch(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication with a different account aborts."""
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"], {})
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "new-refresh-token",
"access_token": "new-access-token",
"token_type": "Bearer",
"expires_in": 3600,
},
)
with patch(
"homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token",
return_value="different-user-id",
):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_account_mismatch"
@pytest.mark.usefixtures("current_request_with_host")
async def test_unique_config_entry(
hass: HomeAssistant,