Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow to configure the Notion integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from dataclasses import dataclass, field
7 from typing import Any
8 
9 from aionotion.errors import InvalidCredentialsError, NotionError
10 import voluptuous as vol
11 
12 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
13 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
14 from homeassistant.core import HomeAssistant
15 
16 from .const import CONF_REFRESH_TOKEN, CONF_USER_UUID, DOMAIN, LOGGER
17 from .util import async_get_client_with_credentials
18 
19 AUTH_SCHEMA = vol.Schema(
20  {
21  vol.Required(CONF_USERNAME): str,
22  vol.Required(CONF_PASSWORD): str,
23  }
24 )
25 REAUTH_SCHEMA = vol.Schema(
26  {
27  vol.Required(CONF_PASSWORD): str,
28  }
29 )
30 
31 
32 @dataclass(frozen=True, kw_only=True)
34  """Define a validation result."""
35 
36  user_uuid: str | None = None
37  refresh_token: str | None = None
38  errors: dict[str, Any] = field(default_factory=dict)
39 
40 
42  hass: HomeAssistant, username: str, password: str
43 ) -> CredentialsValidationResult:
44  """Validate a Notion username and password."""
45  errors = {}
46 
47  try:
48  client = await async_get_client_with_credentials(hass, username, password)
49  except InvalidCredentialsError:
50  errors["base"] = "invalid_auth"
51  except NotionError as err:
52  LOGGER.error("Unknown Notion error while validation credentials: %s", err)
53  errors["base"] = "unknown"
54  except Exception as err: # noqa: BLE001
55  LOGGER.exception("Unknown error while validation credentials: %s", err)
56  errors["base"] = "unknown"
57 
58  if errors:
59  return CredentialsValidationResult(errors=errors)
60 
62  user_uuid=client.user_uuid, refresh_token=client.refresh_token
63  )
64 
65 
66 class NotionFlowHandler(ConfigFlow, domain=DOMAIN):
67  """Handle a Notion config flow."""
68 
69  VERSION = 1
70 
71  async def async_step_reauth(
72  self, entry_data: Mapping[str, Any]
73  ) -> ConfigFlowResult:
74  """Handle configuration by re-auth."""
75  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
76 
78  self, user_input: dict[str, Any] | None = None
79  ) -> ConfigFlowResult:
80  """Handle re-auth completion."""
81 
82  reauth_entry = self._get_reauth_entry_get_reauth_entry()
83  if not user_input:
84  return self.async_show_formasync_show_formasync_show_form(
85  step_id="reauth_confirm",
86  data_schema=REAUTH_SCHEMA,
87  description_placeholders={
88  CONF_USERNAME: reauth_entry.data[CONF_USERNAME]
89  },
90  )
91 
92  credentials_validation_result = await async_validate_credentials(
93  self.hass, reauth_entry.data[CONF_USERNAME], user_input[CONF_PASSWORD]
94  )
95 
96  if credentials_validation_result.errors:
97  return self.async_show_formasync_show_formasync_show_form(
98  step_id="reauth_confirm",
99  data_schema=REAUTH_SCHEMA,
100  errors=credentials_validation_result.errors,
101  description_placeholders={
102  CONF_USERNAME: reauth_entry.data[CONF_USERNAME]
103  },
104  )
105 
106  return self.async_update_reload_and_abortasync_update_reload_and_abort(
107  reauth_entry,
108  data_updates={
109  CONF_REFRESH_TOKEN: credentials_validation_result.refresh_token
110  },
111  )
112 
113  async def async_step_user(
114  self, user_input: dict[str, str] | None = None
115  ) -> ConfigFlowResult:
116  """Handle the start of the config flow."""
117  if not user_input:
118  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=AUTH_SCHEMA)
119 
120  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_USERNAME])
121  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
122 
123  credentials_validation_result = await async_validate_credentials(
124  self.hass, user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
125  )
126 
127  if credentials_validation_result.errors:
128  return self.async_show_formasync_show_formasync_show_form(
129  step_id="user",
130  data_schema=AUTH_SCHEMA,
131  errors=credentials_validation_result.errors,
132  )
133 
134  return self.async_create_entryasync_create_entryasync_create_entry(
135  title=user_input[CONF_USERNAME],
136  data={
137  CONF_USERNAME: user_input[CONF_USERNAME],
138  CONF_USER_UUID: credentials_validation_result.user_uuid,
139  CONF_REFRESH_TOKEN: credentials_validation_result.refresh_token,
140  },
141  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:73
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:115
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:79
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)
_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)
CredentialsValidationResult async_validate_credentials(HomeAssistant hass, str username, str password)
Definition: config_flow.py:43
Client async_get_client_with_credentials(HomeAssistant hass, str email, str password)
Definition: util.py:16