Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Schlage integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from typing import Any
7 
8 import pyschlage
9 from pyschlage.exceptions import NotAuthorizedError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
14 
15 from .const import DOMAIN, LOGGER
16 
17 STEP_USER_DATA_SCHEMA = vol.Schema(
18  {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
19 )
20 STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Required(CONF_PASSWORD): str})
21 
22 
23 class SchlageConfigFlow(ConfigFlow, domain=DOMAIN):
24  """Handle a config flow for Schlage."""
25 
26  VERSION = 1
27 
28  async def async_step_user(
29  self, user_input: dict[str, Any] | None = None
30  ) -> ConfigFlowResult:
31  """Handle the initial step."""
32  if user_input is None:
33  return self._show_user_form_show_user_form({})
34  username = user_input[CONF_USERNAME].lower()
35  password = user_input[CONF_PASSWORD]
36  user_id, errors = await self.hass.async_add_executor_job(
37  _authenticate, username, password
38  )
39  if user_id is None:
40  return self._show_user_form_show_user_form(errors)
41 
42  await self.async_set_unique_idasync_set_unique_id(user_id)
43  return self.async_create_entryasync_create_entryasync_create_entry(
44  title=username,
45  data={
46  CONF_USERNAME: username,
47  CONF_PASSWORD: password,
48  },
49  )
50 
51  def _show_user_form(self, errors: dict[str, str]) -> ConfigFlowResult:
52  """Show the user form."""
53  return self.async_show_formasync_show_formasync_show_form(
54  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
55  )
56 
57  async def async_step_reauth(
58  self, entry_data: Mapping[str, Any]
59  ) -> ConfigFlowResult:
60  """Handle reauth upon an API authentication error."""
61  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
62 
64  self, user_input: dict[str, Any] | None = None
65  ) -> ConfigFlowResult:
66  """Dialog that informs the user that reauth is required."""
67  if user_input is None:
68  return self._show_reauth_form_show_reauth_form({})
69 
70  reauth_entry = self._get_reauth_entry_get_reauth_entry()
71  username = reauth_entry.data[CONF_USERNAME]
72  password = user_input[CONF_PASSWORD]
73  user_id, errors = await self.hass.async_add_executor_job(
74  _authenticate, username, password
75  )
76  if user_id is None:
77  return self._show_reauth_form_show_reauth_form(errors)
78 
79  await self.async_set_unique_idasync_set_unique_id(user_id)
80  self._abort_if_unique_id_mismatch_abort_if_unique_id_mismatch(reason="wrong_account")
81 
82  data = {
83  CONF_USERNAME: username,
84  CONF_PASSWORD: user_input[CONF_PASSWORD],
85  }
86  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=data)
87 
88  def _show_reauth_form(self, errors: dict[str, str]) -> ConfigFlowResult:
89  """Show the reauth form."""
90  return self.async_show_formasync_show_formasync_show_form(
91  step_id="reauth_confirm",
92  data_schema=STEP_REAUTH_DATA_SCHEMA,
93  errors=errors,
94  )
95 
96 
97 def _authenticate(username: str, password: str) -> tuple[str | None, dict[str, str]]:
98  """Authenticate with the Schlage API."""
99  user_id = None
100  errors: dict[str, str] = {}
101  try:
102  auth = pyschlage.Auth(username, password)
103  auth.authenticate()
104  except NotAuthorizedError:
105  errors["base"] = "invalid_auth"
106  except Exception: # noqa: BLE001
107  LOGGER.exception("Unknown error")
108  errors["base"] = "unknown"
109  else:
110  # The user_id property will make a blocking call if it's not already
111  # cached. To avoid blocking the event loop, we read it here.
112  user_id = auth.user_id
113  return user_id, errors
ConfigFlowResult _show_reauth_form(self, dict[str, str] errors)
Definition: config_flow.py:88
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:59
ConfigFlowResult _show_user_form(self, dict[str, str] errors)
Definition: config_flow.py:51
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:30
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:65
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)
None _abort_if_unique_id_mismatch(self, *str reason="unique_id_mismatch", 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)
tuple[str|None, dict[str, str]] _authenticate(str username, str password)
Definition: config_flow.py:97