Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for FYTA integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from fyta_cli.fyta_connector import FytaConnector
10 from fyta_cli.fyta_exceptions import (
11  FytaAuthentificationError,
12  FytaConnectionError,
13  FytaPasswordError,
14 )
15 from fyta_cli.fyta_models import Credentials
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
19 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_PASSWORD, CONF_USERNAME
21  TextSelector,
22  TextSelectorConfig,
23  TextSelectorType,
24 )
25 
26 from .const import CONF_EXPIRATION, DOMAIN
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 
31 DATA_SCHEMA = vol.Schema(
32  {
33  vol.Required(CONF_USERNAME): TextSelector(
35  type=TextSelectorType.TEXT,
36  autocomplete="username",
37  ),
38  ),
39  vol.Required(CONF_PASSWORD): TextSelector(
41  type=TextSelectorType.PASSWORD,
42  autocomplete="current-password",
43  ),
44  ),
45  }
46 )
47 
48 
49 class FytaConfigFlow(ConfigFlow, domain=DOMAIN):
50  """Handle a config flow for Fyta."""
51 
52  credentials: Credentials
53  VERSION = 1
54  MINOR_VERSION = 2
55 
56  async def async_auth(self, user_input: Mapping[str, Any]) -> dict[str, str]:
57  """Reusable Auth Helper."""
58  fyta = FytaConnector(user_input[CONF_USERNAME], user_input[CONF_PASSWORD])
59 
60  try:
61  self.credentialscredentials = await fyta.login()
62  except FytaConnectionError:
63  return {"base": "cannot_connect"}
64  except FytaAuthentificationError:
65  return {"base": "invalid_auth"}
66  except FytaPasswordError:
67  return {"base": "invalid_auth", CONF_PASSWORD: "password_error"}
68  except Exception as e: # noqa: BLE001
69  _LOGGER.error(e)
70  return {"base": "unknown"}
71  finally:
72  await fyta.client.close()
73 
74  return {}
75 
76  async def async_step_user(
77  self, user_input: dict[str, Any] | None = None
78  ) -> ConfigFlowResult:
79  """Handle the initial step."""
80  errors = {}
81  if user_input:
82  self._async_abort_entries_match_async_abort_entries_match({CONF_USERNAME: user_input[CONF_USERNAME]})
83 
84  if not (errors := await self.async_authasync_auth(user_input)):
85  user_input |= {
86  CONF_ACCESS_TOKEN: self.credentialscredentials.access_token,
87  CONF_EXPIRATION: self.credentialscredentials.expiration.isoformat(),
88  }
89  return self.async_create_entryasync_create_entryasync_create_entry(
90  title=user_input[CONF_USERNAME], data=user_input
91  )
92 
93  return self.async_show_formasync_show_formasync_show_form(
94  step_id="user", data_schema=DATA_SCHEMA, errors=errors
95  )
96 
97  async def async_step_reauth(
98  self, entry_data: Mapping[str, Any]
99  ) -> ConfigFlowResult:
100  """Handle flow upon an API authentication error."""
101  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
102 
104  self, user_input: dict[str, Any] | None = None
105  ) -> ConfigFlowResult:
106  """Handle reauthorization flow."""
107  errors = {}
108 
109  reauth_entry = self._get_reauth_entry_get_reauth_entry()
110  if user_input and not (errors := await self.async_authasync_auth(user_input)):
111  user_input |= {
112  CONF_ACCESS_TOKEN: self.credentialscredentials.access_token,
113  CONF_EXPIRATION: self.credentialscredentials.expiration.isoformat(),
114  }
115  return self.async_update_reload_and_abortasync_update_reload_and_abort(
116  reauth_entry,
117  data_updates=user_input,
118  )
119 
120  data_schema = self.add_suggested_values_to_schemaadd_suggested_values_to_schema(
121  DATA_SCHEMA,
122  {CONF_USERNAME: reauth_entry.data[CONF_USERNAME], **(user_input or {})},
123  )
124  return self.async_show_formasync_show_formasync_show_form(
125  step_id="reauth_confirm",
126  data_schema=data_schema,
127  errors=errors,
128  )
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:78
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:99
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:105
dict[str, str] async_auth(self, Mapping[str, Any] user_input)
Definition: config_flow.py:56
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_update_reload_and_abort(self, ConfigEntry entry, *str|None|UndefinedType unique_id=UNDEFINED, str|UndefinedType title=UNDEFINED, Mapping[str, Any]|UndefinedType data=UNDEFINED, Mapping[str, Any]|UndefinedType data_updates=UNDEFINED, Mapping[str, Any]|UndefinedType options=UNDEFINED, str|UndefinedType reason=UNDEFINED, bool reload_even_if_entry_is_unchanged=True)
None _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
vol.Schema add_suggested_values_to_schema(self, vol.Schema data_schema, Mapping[str, Any]|None suggested_values)
_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)