Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Verisure integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 from verisure import (
9  Error as VerisureError,
10  LoginError as VerisureLoginError,
11  ResponseError as VerisureResponseError,
12  Session as Verisure,
13 )
14 import voluptuous as vol
15 
16 from homeassistant.config_entries import (
17  ConfigEntry,
18  ConfigFlow,
19  ConfigFlowResult,
20  OptionsFlow,
21 )
22 from homeassistant.const import CONF_CODE, CONF_EMAIL, CONF_PASSWORD
23 from homeassistant.core import callback
24 from homeassistant.helpers.storage import STORAGE_DIR
25 
26 from .const import (
27  CONF_GIID,
28  CONF_LOCK_CODE_DIGITS,
29  DEFAULT_LOCK_CODE_DIGITS,
30  DOMAIN,
31  LOGGER,
32 )
33 
34 
35 class VerisureConfigFlowHandler(ConfigFlow, domain=DOMAIN):
36  """Handle a config flow for Verisure."""
37 
38  VERSION = 2
39 
40  email: str
41  password: str
42  verisure: Verisure
43 
44  @staticmethod
45  @callback
47  config_entry: ConfigEntry,
48  ) -> VerisureOptionsFlowHandler:
49  """Get the options flow for this handler."""
51 
52  async def async_step_user(
53  self, user_input: dict[str, Any] | None = None
54  ) -> ConfigFlowResult:
55  """Handle the initial step."""
56  errors: dict[str, str] = {}
57 
58  if user_input is not None:
59  self.emailemail = user_input[CONF_EMAIL]
60  self.passwordpassword = user_input[CONF_PASSWORD]
61  self.verisureverisure = Verisure(
62  username=self.emailemail,
63  password=self.passwordpassword,
64  cookie_file_name=self.hass.config.path(
65  STORAGE_DIR, f"verisure_{user_input[CONF_EMAIL]}"
66  ),
67  )
68 
69  try:
70  await self.hass.async_add_executor_job(self.verisureverisure.login)
71  except VerisureLoginError as ex:
72  if "Multifactor authentication enabled" in str(ex):
73  try:
74  await self.hass.async_add_executor_job(
75  self.verisureverisure.request_mfa
76  )
77  except (
78  VerisureLoginError,
79  VerisureError,
80  VerisureResponseError,
81  ) as mfa_ex:
82  LOGGER.debug(
83  "Unexpected response from Verisure during MFA set up, %s",
84  mfa_ex,
85  )
86  errors["base"] = "unknown_mfa"
87  else:
88  return await self.async_step_mfaasync_step_mfa()
89  else:
90  LOGGER.debug("Could not log in to Verisure, %s", ex)
91  errors["base"] = "invalid_auth"
92  except (VerisureError, VerisureResponseError) as ex:
93  LOGGER.debug("Unexpected response from Verisure, %s", ex)
94  errors["base"] = "unknown"
95  else:
96  return await self.async_step_installationasync_step_installation()
97 
98  return self.async_show_formasync_show_formasync_show_form(
99  step_id="user",
100  data_schema=vol.Schema(
101  {
102  vol.Required(CONF_EMAIL): str,
103  vol.Required(CONF_PASSWORD): str,
104  }
105  ),
106  errors=errors,
107  )
108 
109  async def async_step_mfa(
110  self, user_input: dict[str, Any] | None = None
111  ) -> ConfigFlowResult:
112  """Handle multifactor authentication step."""
113  errors: dict[str, str] = {}
114 
115  if user_input is not None:
116  try:
117  await self.hass.async_add_executor_job(
118  self.verisureverisure.validate_mfa, user_input[CONF_CODE]
119  )
120  except VerisureLoginError as ex:
121  LOGGER.debug("Could not log in to Verisure, %s", ex)
122  errors["base"] = "invalid_auth"
123  except (VerisureError, VerisureResponseError) as ex:
124  LOGGER.debug("Unexpected response from Verisure, %s", ex)
125  errors["base"] = "unknown"
126  else:
127  return await self.async_step_installationasync_step_installation()
128 
129  return self.async_show_formasync_show_formasync_show_form(
130  step_id="mfa",
131  data_schema=vol.Schema(
132  {
133  vol.Required(CONF_CODE): vol.All(
134  vol.Coerce(str), vol.Length(min=6, max=6)
135  )
136  }
137  ),
138  errors=errors,
139  )
140 
142  self, user_input: dict[str, Any] | None = None
143  ) -> ConfigFlowResult:
144  """Select Verisure installation to add."""
145  installations_data = await self.hass.async_add_executor_job(
146  self.verisureverisure.get_installations
147  )
148  installations = {
149  inst["giid"]: f"{inst['alias']} ({inst['address']['street']})"
150  for inst in (
151  installations_data.get("data", {})
152  .get("account", {})
153  .get("installations", [])
154  )
155  }
156 
157  if user_input is None:
158  if len(installations) != 1:
159  return self.async_show_formasync_show_formasync_show_form(
160  step_id="installation",
161  data_schema=vol.Schema(
162  {vol.Required(CONF_GIID): vol.In(installations)}
163  ),
164  )
165  user_input = {CONF_GIID: list(installations)[0]}
166 
167  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_GIID])
168  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
169 
170  return self.async_create_entryasync_create_entryasync_create_entry(
171  title=installations[user_input[CONF_GIID]],
172  data={
173  CONF_EMAIL: self.emailemail,
174  CONF_PASSWORD: self.passwordpassword,
175  CONF_GIID: user_input[CONF_GIID],
176  },
177  )
178 
179  async def async_step_reauth(
180  self, entry_data: Mapping[str, Any]
181  ) -> ConfigFlowResult:
182  """Handle initiation of re-authentication with Verisure."""
183  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
184 
186  self, user_input: dict[str, Any] | None = None
187  ) -> ConfigFlowResult:
188  """Handle re-authentication with Verisure."""
189  errors: dict[str, str] = {}
190 
191  if user_input is not None:
192  self.emailemail = user_input[CONF_EMAIL]
193  self.passwordpassword = user_input[CONF_PASSWORD]
194 
195  self.verisureverisure = Verisure(
196  username=self.emailemail,
197  password=self.passwordpassword,
198  cookie_file_name=self.hass.config.path(
199  STORAGE_DIR, f"verisure_{user_input[CONF_EMAIL]}"
200  ),
201  )
202 
203  try:
204  await self.hass.async_add_executor_job(self.verisureverisure.login)
205  except VerisureLoginError as ex:
206  if "Multifactor authentication enabled" in str(ex):
207  try:
208  await self.hass.async_add_executor_job(
209  self.verisureverisure.request_mfa
210  )
211  except (
212  VerisureLoginError,
213  VerisureError,
214  VerisureResponseError,
215  ) as mfa_ex:
216  LOGGER.debug(
217  "Unexpected response from Verisure during MFA set up, %s",
218  mfa_ex,
219  )
220  errors["base"] = "unknown_mfa"
221  else:
222  return await self.async_step_reauth_mfaasync_step_reauth_mfa()
223  else:
224  LOGGER.debug("Could not log in to Verisure, %s", ex)
225  errors["base"] = "invalid_auth"
226  except (VerisureError, VerisureResponseError) as ex:
227  LOGGER.debug("Unexpected response from Verisure, %s", ex)
228  errors["base"] = "unknown"
229  else:
230  return self.async_update_reload_and_abortasync_update_reload_and_abort(
231  self._get_reauth_entry_get_reauth_entry(),
232  data_updates={
233  CONF_EMAIL: user_input[CONF_EMAIL],
234  CONF_PASSWORD: user_input[CONF_PASSWORD],
235  },
236  )
237 
238  return self.async_show_formasync_show_formasync_show_form(
239  step_id="reauth_confirm",
240  data_schema=vol.Schema(
241  {
242  vol.Required(
243  CONF_EMAIL, default=self._get_reauth_entry_get_reauth_entry().data[CONF_EMAIL]
244  ): str,
245  vol.Required(CONF_PASSWORD): str,
246  }
247  ),
248  errors=errors,
249  )
250 
252  self, user_input: dict[str, Any] | None = None
253  ) -> ConfigFlowResult:
254  """Handle multifactor authentication step during re-authentication."""
255  errors: dict[str, str] = {}
256 
257  if user_input is not None:
258  try:
259  await self.hass.async_add_executor_job(
260  self.verisureverisure.validate_mfa, user_input[CONF_CODE]
261  )
262  await self.hass.async_add_executor_job(self.verisureverisure.login)
263  except VerisureLoginError as ex:
264  LOGGER.debug("Could not log in to Verisure, %s", ex)
265  errors["base"] = "invalid_auth"
266  except (VerisureError, VerisureResponseError) as ex:
267  LOGGER.debug("Unexpected response from Verisure, %s", ex)
268  errors["base"] = "unknown"
269  else:
270  return self.async_update_reload_and_abortasync_update_reload_and_abort(
271  self._get_reauth_entry_get_reauth_entry(),
272  data_updates={
273  CONF_EMAIL: self.emailemail,
274  CONF_PASSWORD: self.passwordpassword,
275  },
276  )
277 
278  return self.async_show_formasync_show_formasync_show_form(
279  step_id="reauth_mfa",
280  data_schema=vol.Schema(
281  {
282  vol.Required(CONF_CODE): vol.All(
283  vol.Coerce(str),
284  vol.Length(min=6, max=6),
285  )
286  }
287  ),
288  errors=errors,
289  )
290 
291 
293  """Handle Verisure options."""
294 
295  async def async_step_init(
296  self, user_input: dict[str, Any] | None = None
297  ) -> ConfigFlowResult:
298  """Manage Verisure options."""
299  errors: dict[str, Any] = {}
300 
301  if user_input is not None:
302  return self.async_create_entryasync_create_entry(data=user_input)
303 
304  return self.async_show_formasync_show_form(
305  step_id="init",
306  data_schema=vol.Schema(
307  {
308  vol.Optional(
309  CONF_LOCK_CODE_DIGITS,
310  description={
311  "suggested_value": self.config_entryconfig_entryconfig_entry.options.get(
312  CONF_LOCK_CODE_DIGITS, DEFAULT_LOCK_CODE_DIGITS
313  )
314  },
315  ): int,
316  }
317  ),
318  errors=errors,
319  )
ConfigFlowResult async_step_mfa(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:111
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:54
ConfigFlowResult async_step_installation(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:143
ConfigFlowResult async_step_reauth_mfa(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:253
VerisureOptionsFlowHandler async_get_options_flow(ConfigEntry config_entry)
Definition: config_flow.py:48
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:181
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:187
ConfigFlowResult async_step_init(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:297
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_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)
None config_entry(self, ConfigEntry value)
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)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88