Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for August integration."""
2 
3 from collections.abc import Mapping
4 from dataclasses import dataclass
5 import logging
6 from pathlib import Path
7 from typing import Any
8 
9 import aiohttp
10 import voluptuous as vol
11 from yalexs.authenticator_common import ValidationResult
12 from yalexs.const import BRANDS_WITHOUT_OAUTH, DEFAULT_BRAND, Brand
13 from yalexs.manager.exceptions import CannotConnect, InvalidAuth, RequireValidation
14 
15 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
16 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
17 from homeassistant.core import callback
18 
19 from .const import (
20  CONF_ACCESS_TOKEN_CACHE_FILE,
21  CONF_BRAND,
22  CONF_LOGIN_METHOD,
23  DEFAULT_LOGIN_METHOD,
24  DOMAIN,
25  LOGIN_METHODS,
26  VERIFICATION_CODE_KEY,
27 )
28 from .gateway import AugustGateway
29 from .util import async_create_august_clientsession
30 
31 # The Yale Home Brand is not supported by the August integration
32 # anymore and should migrate to the Yale integration
33 AVAILABLE_BRANDS = BRANDS_WITHOUT_OAUTH.copy()
34 del AVAILABLE_BRANDS[Brand.YALE_HOME]
35 
36 
37 _LOGGER = logging.getLogger(__name__)
38 
39 
41  data: dict[str, Any], august_gateway: AugustGateway
42 ) -> dict[str, Any]:
43  """Validate the user input allows us to connect.
44 
45  Data has the keys from DATA_SCHEMA with values provided by the user.
46 
47  Request configuration steps from the user.
48  """
49  assert august_gateway.authenticator is not None
50  authenticator = august_gateway.authenticator
51  if (code := data.get(VERIFICATION_CODE_KEY)) is not None:
52  result = await authenticator.async_validate_verification_code(code)
53  _LOGGER.debug("Verification code validation: %s", result)
54  if result != ValidationResult.VALIDATED:
55  raise RequireValidation
56 
57  try:
58  await august_gateway.async_authenticate()
59  except RequireValidation:
60  _LOGGER.debug(
61  "Requesting new verification code for %s via %s",
62  data.get(CONF_USERNAME),
63  data.get(CONF_LOGIN_METHOD),
64  )
65  if code is None:
66  await august_gateway.authenticator.async_send_verification_code()
67  raise
68 
69  return {
70  "title": data.get(CONF_USERNAME),
71  "data": august_gateway.config_entry(),
72  }
73 
74 
75 @dataclass(slots=True)
77  """Result from validation."""
78 
79  validation_required: bool
80  info: dict[str, Any]
81  errors: dict[str, str]
82  description_placeholders: dict[str, str]
83 
84 
85 class AugustConfigFlow(ConfigFlow, domain=DOMAIN):
86  """Handle a config flow for August."""
87 
88  VERSION = 1
89 
90  def __init__(self) -> None:
91  """Store an AugustGateway()."""
92  self._august_gateway_august_gateway: AugustGateway | None = None
93  self._aiohttp_session_aiohttp_session: aiohttp.ClientSession | None = None
94  self._user_auth_details_user_auth_details: dict[str, Any] = {}
95  self._needs_reset_needs_reset = True
96  super().__init__()
97 
98  async def async_step_user(
99  self, user_input: dict[str, Any] | None = None
100  ) -> ConfigFlowResult:
101  """Handle the initial step."""
102  return await self.async_step_user_validateasync_step_user_validate()
103 
105  self, user_input: dict[str, Any] | None = None
106  ) -> ConfigFlowResult:
107  """Handle authentication."""
108  errors: dict[str, str] = {}
109  description_placeholders: dict[str, str] = {}
110  if user_input is not None:
111  self._user_auth_details_user_auth_details.update(user_input)
112  validate_result = await self._async_auth_or_validate_async_auth_or_validate()
113  description_placeholders = validate_result.description_placeholders
114  if validate_result.validation_required:
115  return await self.async_step_validationasync_step_validation()
116  if not (errors := validate_result.errors):
117  return await self._async_update_or_create_entry_async_update_or_create_entry(validate_result.info)
118 
119  return self.async_show_formasync_show_formasync_show_form(
120  step_id="user_validate",
121  data_schema=vol.Schema(
122  {
123  vol.Required(
124  CONF_BRAND,
125  default=self._user_auth_details_user_auth_details.get(CONF_BRAND, DEFAULT_BRAND),
126  ): vol.In(AVAILABLE_BRANDS),
127  vol.Required(
128  CONF_LOGIN_METHOD,
129  default=self._user_auth_details_user_auth_details.get(
130  CONF_LOGIN_METHOD, DEFAULT_LOGIN_METHOD
131  ),
132  ): vol.In(LOGIN_METHODS),
133  vol.Required(
134  CONF_USERNAME,
135  default=self._user_auth_details_user_auth_details.get(CONF_USERNAME),
136  ): str,
137  vol.Required(CONF_PASSWORD): str,
138  }
139  ),
140  errors=errors,
141  description_placeholders=description_placeholders,
142  )
143 
145  self, user_input: dict[str, Any] | None = None
146  ) -> ConfigFlowResult:
147  """Handle validation (2fa) step."""
148  if user_input:
149  if self.sourcesourcesourcesource == SOURCE_REAUTH:
150  return await self.async_step_reauth_validateasync_step_reauth_validate(user_input)
151  return await self.async_step_user_validateasync_step_user_validate(user_input)
152 
153  previously_failed = VERIFICATION_CODE_KEY in self._user_auth_details_user_auth_details
154  return self.async_show_formasync_show_formasync_show_form(
155  step_id="validation",
156  data_schema=vol.Schema(
157  {vol.Required(VERIFICATION_CODE_KEY): vol.All(str, vol.Strip)}
158  ),
159  errors={"base": "invalid_verification_code"} if previously_failed else None,
160  description_placeholders={
161  CONF_BRAND: self._user_auth_details_user_auth_details[CONF_BRAND],
162  CONF_USERNAME: self._user_auth_details_user_auth_details[CONF_USERNAME],
163  CONF_LOGIN_METHOD: self._user_auth_details_user_auth_details[CONF_LOGIN_METHOD],
164  },
165  )
166 
167  @callback
168  def _async_get_gateway(self) -> AugustGateway:
169  """Set up the gateway."""
170  if self._august_gateway_august_gateway is not None:
171  return self._august_gateway_august_gateway
172  self._aiohttp_session_aiohttp_session = async_create_august_clientsession(self.hass)
173  self._august_gateway_august_gateway = AugustGateway(
174  Path(self.hass.config.config_dir), self._aiohttp_session_aiohttp_session
175  )
176  return self._august_gateway_august_gateway
177 
178  @callback
179  def _async_shutdown_gateway(self) -> None:
180  """Shutdown the gateway."""
181  if self._aiohttp_session_aiohttp_session is not None:
182  self._aiohttp_session_aiohttp_session.detach()
183  self._august_gateway_august_gateway = None
184 
185  async def async_step_reauth(
186  self, entry_data: Mapping[str, Any]
187  ) -> ConfigFlowResult:
188  """Handle configuration by re-auth."""
189  self._user_auth_details_user_auth_details = dict(entry_data)
190  return await self.async_step_reauth_validateasync_step_reauth_validate()
191 
193  self, user_input: dict[str, Any] | None = None
194  ) -> ConfigFlowResult:
195  """Handle reauth and validation."""
196  errors: dict[str, str] = {}
197  description_placeholders: dict[str, str] = {}
198  if user_input is not None:
199  self._user_auth_details_user_auth_details.update(user_input)
200  validate_result = await self._async_auth_or_validate_async_auth_or_validate()
201  description_placeholders = validate_result.description_placeholders
202  if validate_result.validation_required:
203  return await self.async_step_validationasync_step_validation()
204  if not (errors := validate_result.errors):
205  return await self._async_update_or_create_entry_async_update_or_create_entry(validate_result.info)
206 
207  return self.async_show_formasync_show_formasync_show_form(
208  step_id="reauth_validate",
209  data_schema=vol.Schema(
210  {
211  vol.Required(
212  CONF_BRAND,
213  default=self._user_auth_details_user_auth_details.get(CONF_BRAND, DEFAULT_BRAND),
214  ): vol.In(BRANDS_WITHOUT_OAUTH),
215  vol.Required(CONF_PASSWORD): str,
216  }
217  ),
218  errors=errors,
219  description_placeholders=description_placeholders
220  | {
221  CONF_USERNAME: self._user_auth_details_user_auth_details[CONF_USERNAME],
222  },
223  )
224 
226  self, gateway: AugustGateway, username: str, access_token_cache_file: str | None
227  ) -> None:
228  """Reset the access token cache if needed."""
229  # We need to configure the access token cache file before we setup the gateway
230  # since we need to reset it if the brand changes BEFORE we setup the gateway
231  gateway.async_configure_access_token_cache_file(
232  username, access_token_cache_file
233  )
234  if self._needs_reset_needs_reset:
235  self._needs_reset_needs_reset = False
236  await gateway.async_reset_authentication()
237 
238  async def _async_auth_or_validate(self) -> ValidateResult:
239  """Authenticate or validate."""
240  user_auth_details = self._user_auth_details_user_auth_details
241  gateway = self._async_get_gateway_async_get_gateway()
242  assert gateway is not None
243  await self._async_reset_access_token_cache_if_needed_async_reset_access_token_cache_if_needed(
244  gateway,
245  user_auth_details[CONF_USERNAME],
246  user_auth_details.get(CONF_ACCESS_TOKEN_CACHE_FILE),
247  )
248  await gateway.async_setup(user_auth_details)
249 
250  errors: dict[str, str] = {}
251  info: dict[str, Any] = {}
252  description_placeholders: dict[str, str] = {}
253  validation_required = False
254 
255  try:
256  info = await async_validate_input(user_auth_details, gateway)
257  except CannotConnect:
258  errors["base"] = "cannot_connect"
259  except InvalidAuth:
260  errors["base"] = "invalid_auth"
261  except RequireValidation:
262  validation_required = True
263  except Exception as ex:
264  _LOGGER.exception("Unexpected exception")
265  errors["base"] = "unhandled"
266  description_placeholders = {"error": str(ex)}
267 
268  return ValidateResult(
269  validation_required, info, errors, description_placeholders
270  )
271 
273  self, info: dict[str, Any]
274  ) -> ConfigFlowResult:
275  """Update existing entry or create a new one."""
276  self._async_shutdown_gateway_async_shutdown_gateway()
277 
278  existing_entry = await self.async_set_unique_idasync_set_unique_id(
279  self._user_auth_details_user_auth_details[CONF_USERNAME]
280  )
281  if not existing_entry:
282  return self.async_create_entryasync_create_entryasync_create_entry(title=info["title"], data=info["data"])
283 
284  return self.async_update_reload_and_abortasync_update_reload_and_abort(existing_entry, data=info["data"])
ConfigFlowResult async_step_reauth_validate(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:194
ConfigFlowResult _async_update_or_create_entry(self, dict[str, Any] info)
Definition: config_flow.py:274
ConfigFlowResult async_step_validation(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:146
None _async_reset_access_token_cache_if_needed(self, AugustGateway gateway, str username, str|None access_token_cache_file)
Definition: config_flow.py:227
ConfigFlowResult async_step_user_validate(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:106
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:100
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:187
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_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)
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)
str
_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)
str|None source(self)
dict[str, Any] async_validate_input(dict[str, Any] data, AugustGateway august_gateway)
Definition: config_flow.py:42
aiohttp.ClientSession async_create_august_clientsession(HomeAssistant hass)
Definition: util.py:23
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
IssData update(pyiss.ISS iss)
Definition: __init__.py:33