Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for tractive integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 import aiotractive
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 
17 from .const import DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 USER_DATA_SCHEMA = vol.Schema(
22  {vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str}
23 )
24 
25 
26 async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
27  """Validate the user input allows us to connect.
28 
29  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
30  """
31 
32  client = aiotractive.api.API(data[CONF_EMAIL], data[CONF_PASSWORD])
33  try:
34  user_id = await client.user_id()
35  except aiotractive.exceptions.UnauthorizedError as error:
36  raise InvalidAuth from error
37  finally:
38  await client.close()
39 
40  return {"title": data[CONF_EMAIL], "user_id": user_id}
41 
42 
43 class TractiveConfigFlow(ConfigFlow, domain=DOMAIN):
44  """Handle a config flow for tractive."""
45 
46  VERSION = 1
47 
48  async def async_step_user(
49  self, user_input: dict[str, Any] | None = None
50  ) -> ConfigFlowResult:
51  """Handle the initial step."""
52  if user_input is None:
53  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=USER_DATA_SCHEMA)
54 
55  errors = {}
56 
57  try:
58  info = await validate_input(self.hass, user_input)
59  except InvalidAuth:
60  errors["base"] = "invalid_auth"
61  except Exception:
62  _LOGGER.exception("Unexpected exception")
63  errors["base"] = "unknown"
64  else:
65  await self.async_set_unique_idasync_set_unique_id(info["user_id"])
66  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
67  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=user_input)
68 
69  return self.async_show_formasync_show_formasync_show_form(
70  step_id="user", data_schema=USER_DATA_SCHEMA, errors=errors
71  )
72 
73  async def async_step_reauth(
74  self, entry_data: Mapping[str, Any]
75  ) -> ConfigFlowResult:
76  """Handle configuration by re-auth."""
77  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
78 
80  self, user_input: dict[str, Any] | None = None
81  ) -> ConfigFlowResult:
82  """Dialog that informs the user that reauth is required."""
83 
84  errors = {}
85 
86  if user_input is not None:
87  try:
88  info = await validate_input(self.hass, user_input)
89  except InvalidAuth:
90  errors["base"] = "invalid_auth"
91  except Exception:
92  _LOGGER.exception("Unexpected exception")
93  errors["base"] = "unknown"
94  else:
95  existing_entry = await self.async_set_unique_idasync_set_unique_id(info["user_id"])
96  if existing_entry:
97  await self.hass.config_entries.async_reload(existing_entry.entry_id)
98  return self.async_abortasync_abortasync_abort(reason="reauth_successful")
99  return self.async_abortasync_abortasync_abort(reason="reauth_failed_existing")
100 
101  return self.async_show_formasync_show_formasync_show_form(
102  step_id="reauth_confirm",
103  data_schema=USER_DATA_SCHEMA,
104  errors=errors,
105  )
106 
107 
109  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:81
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:50
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:75
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
dict[str, Any] validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:26