mirror of
https://github.com/home-assistant/core.git
synced 2025-07-25 06:07:17 +00:00
Add reauth flow to Pterodactyl (#142285)
* Add reauth flow * Add common function to validate connection in config flow * Fix remaining review findings
This commit is contained in:
parent
1ab8deff3d
commit
904265bca7
@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
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
|
||||||
|
|
||||||
@ -29,36 +30,81 @@ STEP_USER_DATA_SCHEMA = vol.Schema(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
STEP_REAUTH_DATA_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_API_KEY): str,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class PterodactylConfigFlow(ConfigFlow, domain=DOMAIN):
|
class PterodactylConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||||
"""Handle a config flow for Pterodactyl."""
|
"""Handle a config flow for Pterodactyl."""
|
||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
|
||||||
|
async def async_validate_connection(self, url: str, api_key: str) -> dict[str, str]:
|
||||||
|
"""Validate the connection to the Pterodactyl server."""
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
api = PterodactylAPI(self.hass, url, api_key)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await api.async_init()
|
||||||
|
except PterodactylAuthorizationError:
|
||||||
|
errors["base"] = "invalid_auth"
|
||||||
|
except PterodactylConnectionError:
|
||||||
|
errors["base"] = "cannot_connect"
|
||||||
|
except Exception:
|
||||||
|
_LOGGER.exception("Unexpected exception occurred during config flow")
|
||||||
|
errors["base"] = "unknown"
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
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
|
||||||
) -> ConfigFlowResult:
|
) -> ConfigFlowResult:
|
||||||
"""Handle the initial step."""
|
"""Handle the initial step."""
|
||||||
errors: dict[str, str] = {}
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
if user_input is not None:
|
if user_input is not None:
|
||||||
url = URL(user_input[CONF_URL]).human_repr()
|
url = URL(user_input[CONF_URL]).human_repr()
|
||||||
api_key = user_input[CONF_API_KEY]
|
api_key = user_input[CONF_API_KEY]
|
||||||
|
|
||||||
self._async_abort_entries_match({CONF_URL: url})
|
self._async_abort_entries_match({CONF_URL: url})
|
||||||
api = PterodactylAPI(self.hass, url, api_key)
|
errors = await self.async_validate_connection(url, api_key)
|
||||||
|
|
||||||
try:
|
if not errors:
|
||||||
await api.async_init()
|
|
||||||
except PterodactylAuthorizationError:
|
|
||||||
errors["base"] = "invalid_auth"
|
|
||||||
except PterodactylConnectionError:
|
|
||||||
errors["base"] = "cannot_connect"
|
|
||||||
except Exception:
|
|
||||||
_LOGGER.exception("Unexpected exception occurred during config flow")
|
|
||||||
errors["base"] = "unknown"
|
|
||||||
else:
|
|
||||||
return self.async_create_entry(title=url, data=user_input)
|
return self.async_create_entry(title=url, data=user_input)
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
|
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def async_step_reauth(
|
||||||
|
self, entry_data: Mapping[str, Any]
|
||||||
|
) -> ConfigFlowResult:
|
||||||
|
"""Perform re-authentication on an API authentication error."""
|
||||||
|
return await self.async_step_reauth_confirm()
|
||||||
|
|
||||||
|
async def async_step_reauth_confirm(
|
||||||
|
self, user_input: Mapping[str, Any] | None = None
|
||||||
|
) -> ConfigFlowResult:
|
||||||
|
"""Dialog that informs the user that re-authentication is required."""
|
||||||
|
errors: dict[str, str] = {}
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
reauth_entry = self._get_reauth_entry()
|
||||||
|
url = reauth_entry.data[CONF_URL]
|
||||||
|
api_key = user_input[CONF_API_KEY]
|
||||||
|
|
||||||
|
errors = await self.async_validate_connection(url, api_key)
|
||||||
|
|
||||||
|
if not errors:
|
||||||
|
return self.async_update_reload_and_abort(
|
||||||
|
reauth_entry, data_updates=user_input
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="reauth_confirm",
|
||||||
|
data_schema=STEP_REAUTH_DATA_SCHEMA,
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
@ -8,6 +8,7 @@ import logging
|
|||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import CONF_API_KEY, CONF_URL
|
from homeassistant.const import CONF_API_KEY, CONF_URL
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
|
||||||
|
|
||||||
from .api import (
|
from .api import (
|
||||||
@ -55,12 +56,16 @@ class PterodactylCoordinator(DataUpdateCoordinator[dict[str, PterodactylData]]):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
await self.api.async_init()
|
await self.api.async_init()
|
||||||
except (PterodactylAuthorizationError, PterodactylConnectionError) as error:
|
except PterodactylConnectionError as error:
|
||||||
raise UpdateFailed(error) from error
|
raise UpdateFailed(error) from error
|
||||||
|
except PterodactylAuthorizationError as error:
|
||||||
|
raise ConfigEntryAuthFailed(error) from error
|
||||||
|
|
||||||
async def _async_update_data(self) -> dict[str, PterodactylData]:
|
async def _async_update_data(self) -> dict[str, PterodactylData]:
|
||||||
"""Get updated data from the Pterodactyl server."""
|
"""Get updated data from the Pterodactyl server."""
|
||||||
try:
|
try:
|
||||||
return await self.api.async_get_data()
|
return await self.api.async_get_data()
|
||||||
except (PterodactylAuthorizationError, PterodactylConnectionError) as error:
|
except PterodactylConnectionError as error:
|
||||||
raise UpdateFailed(error) from error
|
raise UpdateFailed(error) from error
|
||||||
|
except PterodactylAuthorizationError as error:
|
||||||
|
raise ConfigEntryAuthFailed(error) from error
|
||||||
|
@ -51,7 +51,7 @@ rules:
|
|||||||
status: done
|
status: done
|
||||||
comment: Handled by coordinator.
|
comment: Handled by coordinator.
|
||||||
parallel-updates: done
|
parallel-updates: done
|
||||||
reauthentication-flow: todo
|
reauthentication-flow: done
|
||||||
test-coverage: todo
|
test-coverage: todo
|
||||||
|
|
||||||
# Gold
|
# Gold
|
||||||
|
@ -10,6 +10,16 @@
|
|||||||
"url": "The URL of your Pterodactyl server, including the protocol (http:// or https://) and optionally the port number.",
|
"url": "The URL of your Pterodactyl server, including the protocol (http:// or https://) and optionally the port number.",
|
||||||
"api_key": "The account API key for accessing your Pterodactyl server."
|
"api_key": "The account API key for accessing your Pterodactyl server."
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"reauth_confirm": {
|
||||||
|
"title": "[%key:common::config_flow::title::reauth%]",
|
||||||
|
"description": "Please update your account API key.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "[%key:common::config_flow::data::api_key%]"
|
||||||
|
},
|
||||||
|
"data_description": {
|
||||||
|
"api_key": "[%key:component::pterodactyl::config::step::user::data_description::api_key%]"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
@ -18,7 +28,8 @@
|
|||||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
|
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
|
||||||
|
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"entity": {
|
"entity": {
|
||||||
|
@ -8,10 +8,11 @@ from requests.models import Response
|
|||||||
|
|
||||||
from homeassistant.components.pterodactyl.const import DOMAIN
|
from homeassistant.components.pterodactyl.const import DOMAIN
|
||||||
from homeassistant.config_entries import SOURCE_USER
|
from homeassistant.config_entries import SOURCE_USER
|
||||||
|
from homeassistant.const import CONF_API_KEY, CONF_URL
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.data_entry_flow import FlowResultType
|
from homeassistant.data_entry_flow import FlowResultType
|
||||||
|
|
||||||
from .conftest import TEST_URL, TEST_USER_INPUT
|
from .conftest import TEST_API_KEY, TEST_URL, TEST_USER_INPUT
|
||||||
|
|
||||||
from tests.common import MockConfigEntry
|
from tests.common import MockConfigEntry
|
||||||
|
|
||||||
@ -90,11 +91,10 @@ async def test_recovery_after_error(
|
|||||||
assert result["data"] == TEST_USER_INPUT
|
assert result["data"] == TEST_USER_INPUT
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.usefixtures("mock_setup_entry")
|
@pytest.mark.usefixtures("mock_setup_entry", "mock_pterodactyl")
|
||||||
async def test_service_already_configured(
|
async def test_service_already_configured(
|
||||||
hass: HomeAssistant,
|
hass: HomeAssistant,
|
||||||
mock_config_entry: MockConfigEntry,
|
mock_config_entry: MockConfigEntry,
|
||||||
mock_pterodactyl: PterodactylClient,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Test config flow abort if the Pterodactyl server is already configured."""
|
"""Test config flow abort if the Pterodactyl server is already configured."""
|
||||||
mock_config_entry.add_to_hass(hass)
|
mock_config_entry.add_to_hass(hass)
|
||||||
@ -105,3 +105,68 @@ async def test_service_already_configured(
|
|||||||
|
|
||||||
assert result["type"] is FlowResultType.ABORT
|
assert result["type"] is FlowResultType.ABORT
|
||||||
assert result["reason"] == "already_configured"
|
assert result["reason"] == "already_configured"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("mock_pterodactyl", "mock_setup_entry")
|
||||||
|
async def test_reauth_full_flow(
|
||||||
|
hass: HomeAssistant,
|
||||||
|
mock_config_entry: MockConfigEntry,
|
||||||
|
) -> None:
|
||||||
|
"""Test reauth config flow success."""
|
||||||
|
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"], user_input={CONF_API_KEY: TEST_API_KEY}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["type"] is FlowResultType.ABORT
|
||||||
|
assert result["reason"] == "reauth_successful"
|
||||||
|
assert mock_config_entry.data[CONF_URL] == TEST_URL
|
||||||
|
assert mock_config_entry.data[CONF_API_KEY] == TEST_API_KEY
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("mock_setup_entry")
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("exception_type", "expected_error"),
|
||||||
|
[
|
||||||
|
(PterodactylApiError, "cannot_connect"),
|
||||||
|
(BadRequestError, "cannot_connect"),
|
||||||
|
(Exception, "unknown"),
|
||||||
|
(HTTPError(response=mock_response()), "invalid_auth"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_reauth_recovery_after_error(
|
||||||
|
hass: HomeAssistant,
|
||||||
|
exception_type: Exception,
|
||||||
|
expected_error: str,
|
||||||
|
mock_config_entry: MockConfigEntry,
|
||||||
|
mock_pterodactyl: PterodactylClient,
|
||||||
|
) -> None:
|
||||||
|
"""Test recovery after an error during re-authentication."""
|
||||||
|
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"
|
||||||
|
|
||||||
|
mock_pterodactyl.client.servers.list_servers.side_effect = exception_type
|
||||||
|
|
||||||
|
result = await hass.config_entries.flow.async_configure(
|
||||||
|
result["flow_id"], user_input={CONF_API_KEY: TEST_API_KEY}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["type"] is FlowResultType.FORM
|
||||||
|
assert result["errors"] == {"base": expected_error}
|
||||||
|
|
||||||
|
mock_pterodactyl.reset_mock(side_effect=True)
|
||||||
|
|
||||||
|
result = await hass.config_entries.flow.async_configure(
|
||||||
|
result["flow_id"], user_input={CONF_API_KEY: TEST_API_KEY}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["type"] is FlowResultType.ABORT
|
||||||
|
assert result["reason"] == "reauth_successful"
|
||||||
|
assert mock_config_entry.data[CONF_URL] == TEST_URL
|
||||||
|
assert mock_config_entry.data[CONF_API_KEY] == TEST_API_KEY
|
||||||
|
Loading…
x
Reference in New Issue
Block a user