Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for the Abode Security System component."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from http import HTTPStatus
7 from typing import Any, cast
8 
9 from jaraco.abode.client import Client as Abode
10 from jaraco.abode.exceptions import (
11  AuthenticationException as AbodeAuthenticationException,
12  Exception as AbodeException,
13 )
14 from jaraco.abode.helpers.errors import MFA_CODE_REQUIRED
15 from requests.exceptions import ConnectTimeout, HTTPError
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
19 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
20 
21 from .const import CONF_POLLING, DOMAIN, LOGGER
22 
23 CONF_MFA = "mfa_code"
24 
25 
26 class AbodeFlowHandler(ConfigFlow, domain=DOMAIN):
27  """Config flow for Abode."""
28 
29  VERSION = 1
30 
31  def __init__(self) -> None:
32  """Initialize."""
33  self.data_schemadata_schema = {
34  vol.Required(CONF_USERNAME): str,
35  vol.Required(CONF_PASSWORD): str,
36  }
37  self.mfa_data_schemamfa_data_schema = {
38  vol.Required(CONF_MFA): str,
39  }
40 
41  self._mfa_code_mfa_code: str | None = None
42  self._password_password: str | None = None
43  self._polling: bool = False
44  self._username_username: str | None = None
45 
46  async def _async_abode_login(self, step_id: str) -> ConfigFlowResult:
47  """Handle login with Abode."""
48  errors = {}
49 
50  try:
51  await self.hass.async_add_executor_job(
52  Abode, self._username_username, self._password_password, True, False, False
53  )
54 
55  except AbodeException as ex:
56  if ex.errcode == MFA_CODE_REQUIRED[0]:
57  return await self.async_step_mfaasync_step_mfa()
58 
59  LOGGER.error("Unable to connect to Abode: %s", ex)
60 
61  if ex.errcode == HTTPStatus.BAD_REQUEST:
62  errors = {"base": "invalid_auth"}
63 
64  else:
65  errors = {"base": "cannot_connect"}
66 
67  except (ConnectTimeout, HTTPError):
68  errors = {"base": "cannot_connect"}
69 
70  if errors:
71  return self.async_show_formasync_show_formasync_show_form(
72  step_id=step_id, data_schema=vol.Schema(self.data_schemadata_schema), errors=errors
73  )
74 
75  return await self._async_create_entry_async_create_entry()
76 
77  async def _async_abode_mfa_login(self) -> ConfigFlowResult:
78  """Handle multi-factor authentication (MFA) login with Abode."""
79  try:
80  # Create instance to access login method for passing MFA code
81  abode = Abode(auto_login=False, get_devices=False, get_automations=False)
82  await self.hass.async_add_executor_job(
83  abode.login, self._username_username, self._password_password, self._mfa_code_mfa_code
84  )
85 
86  except AbodeAuthenticationException:
87  return self.async_show_formasync_show_formasync_show_form(
88  step_id="mfa",
89  data_schema=vol.Schema(self.mfa_data_schemamfa_data_schema),
90  errors={"base": "invalid_mfa_code"},
91  )
92 
93  return await self._async_create_entry_async_create_entry()
94 
95  async def _async_create_entry(self) -> ConfigFlowResult:
96  """Create the config entry."""
97  config_data = {
98  CONF_USERNAME: self._username_username,
99  CONF_PASSWORD: self._password_password,
100  CONF_POLLING: self._polling,
101  }
102  existing_entry = await self.async_set_unique_idasync_set_unique_id(self._username_username)
103 
104  if existing_entry:
105  return self.async_update_reload_and_abortasync_update_reload_and_abort(existing_entry, data=config_data)
106 
107  return self.async_create_entryasync_create_entryasync_create_entry(
108  title=cast(str, self._username_username), data=config_data
109  )
110 
111  async def async_step_user(
112  self, user_input: dict[str, Any] | None = None
113  ) -> ConfigFlowResult:
114  """Handle a flow initialized by the user."""
115  if user_input is None:
116  return self.async_show_formasync_show_formasync_show_form(
117  step_id="user", data_schema=vol.Schema(self.data_schemadata_schema)
118  )
119 
120  self._username_username = user_input[CONF_USERNAME]
121  self._password_password = user_input[CONF_PASSWORD]
122 
123  return await self._async_abode_login_async_abode_login(step_id="user")
124 
125  async def async_step_mfa(
126  self, user_input: dict[str, Any] | None = None
127  ) -> ConfigFlowResult:
128  """Handle a multi-factor authentication (MFA) flow."""
129  if user_input is None:
130  return self.async_show_formasync_show_formasync_show_form(
131  step_id="mfa", data_schema=vol.Schema(self.mfa_data_schemamfa_data_schema)
132  )
133 
134  self._mfa_code_mfa_code = user_input[CONF_MFA]
135 
136  return await self._async_abode_mfa_login_async_abode_mfa_login()
137 
138  async def async_step_reauth(
139  self, entry_data: Mapping[str, Any]
140  ) -> ConfigFlowResult:
141  """Handle reauthorization request from Abode."""
142  self._username_username = entry_data[CONF_USERNAME]
143 
144  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
145 
147  self, user_input: dict[str, Any] | None = None
148  ) -> ConfigFlowResult:
149  """Handle reauthorization flow."""
150  if user_input is None:
151  return self.async_show_formasync_show_formasync_show_form(
152  step_id="reauth_confirm",
153  data_schema=vol.Schema(
154  {
155  vol.Required(CONF_USERNAME, default=self._username_username): str,
156  vol.Required(CONF_PASSWORD): str,
157  }
158  ),
159  )
160 
161  self._username_username = user_input[CONF_USERNAME]
162  self._password_password = user_input[CONF_PASSWORD]
163 
164  return await self._async_abode_login_async_abode_login(step_id="reauth_confirm")
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:113
ConfigFlowResult _async_abode_login(self, str step_id)
Definition: config_flow.py:46
ConfigFlowResult async_step_mfa(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:127
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:148
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:140
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)
_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)