Skip to content

Commit

Permalink
Implement reauthentication flow (#624)
Browse files Browse the repository at this point in the history
* Replace named config variables with constants
* Implement reauthentication flow
* Update quality scale for reauthentication
  • Loading branch information
WebSpider authored Feb 17, 2025
1 parent 8ea5d4d commit d0e56b6
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 16 deletions.
65 changes: 60 additions & 5 deletions custom_components/myskoda/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
callback,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.schema_config_entry_flow import (
SchemaCommonFlowHandler,
Expand All @@ -37,10 +37,13 @@

from .const import (
DOMAIN,
CONF_PASSWORD,
CONF_POLL_INTERVAL,
CONF_POLL_INTERVAL_MIN,
CONF_POLL_INTERVAL_MAX,
CONF_SPIN,
CONF_TRACING,
CONF_USERNAME,
CONF_READONLY,
)

Expand Down Expand Up @@ -71,19 +74,19 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None:
async_get_clientsession(hass), get_default_context(), mqtt_enabled=False
)

await hub.connect(data["email"], data["password"])
await hub.connect(data[CONF_USERNAME], data[CONF_PASSWORD])
await hub.disconnect()


STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required("email"): str,
vol.Required("password"): str,
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
OPTIONS_SCHEMA = vol.Schema(
{
vol.Required("tracing", default=False): bool,
vol.Required(CONF_TRACING, default=False): bool,
vol.Optional(CONF_POLL_INTERVAL): int,
vol.Optional(CONF_READONLY, default=False): bool,
vol.Optional(CONF_SPIN): str,
Expand Down Expand Up @@ -138,6 +141,58 @@ async def async_step_user(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)

async def async_step_reauth(self, entry_data: dict[str, Any]) -> ConfigFlowResult:
"""Handle initiation of re-authentication with MySkoda."""
_LOGGER.debug("Authentication error detected, starting reauth")
self.reauth_entry = self._get_reauth_entry()
return await self.async_step_reauth_confirm()

async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle re-authentication with MySkoda."""
errors: dict = {}

if user_input is not None:
try:
await validate_input(self.hass, user_input)
except (CannotConnect, ClientResponseError) as err:
errors["base"] = "cannot_connect"
raise ConfigEntryNotReady("Error connecting to MySkoda: %s", err)
except Exception as err:
errors["base"] = "unknown"
_LOGGER.error("Failed to log in due to error: %s", str(err))
return self.async_abort(reason="unknown")

data = self.reauth_entry.data.copy()
self.hass.config_entries.async_update_entry(
self.reauth_entry,
data={
**data,
**user_input,
},
)
self.hass.async_create_task(
self.hass.config_entries.async_reload(self.reauth_entry.entry_id)
)

return self.async_abort(reason="reauth_successful")

return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema(
{
vol.Required(
CONF_USERNAME, default=self.reauth_entry.data[CONF_USERNAME]
): str,
vol.Required(
CONF_PASSWORD, default=self.reauth_entry.data[CONF_PASSWORD]
): str,
}
),
errors=errors,
)

@staticmethod
@callback
def async_get_options_flow(
Expand Down
4 changes: 3 additions & 1 deletion custom_components/myskoda/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

DEFAULT_FETCH_INTERVAL_IN_MINUTES = 30
API_COOLDOWN_IN_SECONDS = 30.0

CONF_USERNAME = "email"
CONF_PASSWORD = "password"
CONF_POLL_INTERVAL = "poll_interval_in_minutes"
CONF_POLL_INTERVAL_MIN = 1
CONF_POLL_INTERVAL_MAX = 1440
CONF_SPIN = "s-pin"
CONF_READONLY = "readonly"
CONF_TRACING = "tracing"

MAX_STORED_OPERATIONS = 2
MAX_STORED_SERVICE_EVENTS = 2
Expand Down
16 changes: 8 additions & 8 deletions custom_components/myskoda/quality_scale.yaml
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
rules:
# Bronze
action-setup: todo
appropriate-polling: todo
action-setup: done
appropriate-polling: done
brands: todo
common-modules: todo
config-flow-test-coverage: todo
config-flow: todo
dependency-transparency: todo
dependency-transparency: done
docs-actions: todo
docs-high-level-description: todo
docs-installation-instructions: todo
docs-removal-instructions: todo
entity-event-setup: todo
entity-unique-id: todo
has-entity-name: todo
has-entity-name: done
runtime-data: todo
test-before-configure: todo
test-before-configure: done
test-before-setup: todo
unique-config-entry: todo

# Silver
action-exceptions: todo
config-entry-unloading: todo
config-entry-unloading: done
docs-configuration-parameters: todo
docs-installation-parameters: todo
entity-unavailable: todo
entity-unavailable: done
integration-owner: todo
log-when-unavailable: todo
parallel-updates: todo
reauthentication-flow: todo
reauthentication-flow: done
test-coverage:
status: todo
comment: Platform missing tests
Expand Down
15 changes: 13 additions & 2 deletions custom_components/myskoda/translations/en.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"config": {
"abort": {
"already_configured": "Device is already configured"
"already_configured": "Device is already configured",
"reauth_successful": "Reauthentication has succeeded.",
"no_entry": "Could not find MySkoda configuration. Please check your logs and open an issue on GitHub."
},
"error": {
"cannot_connect": "Failed to connect. MySkoda may be down or unreachable.",
Expand All @@ -10,11 +12,20 @@
"unknown": "An unexpected error occurred. Please check the HomeAssistant logfiles and report an issue to the developers."
},
"step": {
"reauth_confirm": {
"data": {
"email": "E-mail address",
"password": "Password"
},
"description": "Authentication to MySkoda has failed. Please re-enter the credentials from your MySkoda app.",
"title": "Re-authenticate MySkoda"
},
"user": {
"data": {
"email": "E-mail",
"password": "Password"
}
},
"description": "Enter the credentials from your MySkoda app."
}
}
},
Expand Down

0 comments on commit d0e56b6

Please sign in to comment.