Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for brunt integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 from aiohttp import ClientResponseError
10 from aiohttp.client_exceptions import ServerDisconnectedError
11 from brunt import BruntClientAsync
12 import voluptuous as vol
13 
14 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
15 from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
16 
17 from .const import DOMAIN
18 
19 _LOGGER = logging.getLogger(__name__)
20 
21 DATA_SCHEMA = vol.Schema(
22  {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
23 )
24 REAUTH_SCHEMA = vol.Schema({vol.Required(CONF_PASSWORD): str})
25 
26 
27 async def validate_input(user_input: dict[str, Any]) -> dict[str, str] | None:
28  """Login to the brunt api and return errors if any."""
29  errors = None
30  bapi = BruntClientAsync(
31  username=user_input[CONF_USERNAME],
32  password=user_input[CONF_PASSWORD],
33  )
34  try:
35  await bapi.async_login()
36  except ClientResponseError as exc:
37  if exc.status == 403:
38  _LOGGER.warning("Brunt Credentials are incorrect")
39  errors = {"base": "invalid_auth"}
40  else:
41  _LOGGER.exception("Unknown error when trying to login to Brunt")
42  errors = {"base": "unknown"}
43  except ServerDisconnectedError:
44  _LOGGER.warning("Cannot connect to Brunt")
45  errors = {"base": "cannot_connect"}
46  except Exception:
47  _LOGGER.exception("Unknown error when trying to login to Brunt")
48  errors = {"base": "unknown"}
49  finally:
50  await bapi.async_close()
51  return errors
52 
53 
54 class BruntConfigFlow(ConfigFlow, domain=DOMAIN):
55  """Handle a config flow for Brunt."""
56 
57  VERSION = 1
58 
59  async def async_step_user(
60  self, user_input: dict[str, Any] | None = None
61  ) -> ConfigFlowResult:
62  """Handle the initial step."""
63  if user_input is None:
64  return self.async_show_formasync_show_formasync_show_form(step_id="user", data_schema=DATA_SCHEMA)
65 
66  errors = await validate_input(user_input)
67  if errors is not None:
68  return self.async_show_formasync_show_formasync_show_form(
69  step_id="user", data_schema=DATA_SCHEMA, errors=errors
70  )
71 
72  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_USERNAME].lower())
73  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
74  return self.async_create_entryasync_create_entryasync_create_entry(
75  title=user_input[CONF_USERNAME],
76  data=user_input,
77  )
78 
79  async def async_step_reauth(
80  self, entry_data: Mapping[str, Any]
81  ) -> ConfigFlowResult:
82  """Perform reauth upon an API authentication error."""
83  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
84 
86  self, user_input: dict[str, Any] | None = None
87  ) -> ConfigFlowResult:
88  """Dialog that informs the user that reauth is required."""
89  reauth_entry = self._get_reauth_entry_get_reauth_entry()
90  username = reauth_entry.data[CONF_USERNAME]
91  if user_input is None:
92  return self.async_show_formasync_show_formasync_show_form(
93  step_id="reauth_confirm",
94  data_schema=REAUTH_SCHEMA,
95  description_placeholders={
96  CONF_USERNAME: username,
97  CONF_NAME: reauth_entry.title,
98  },
99  )
100  user_input[CONF_USERNAME] = username
101  errors = await validate_input(user_input)
102  if errors is not None:
103  return self.async_show_formasync_show_formasync_show_form(
104  step_id="reauth_confirm",
105  data_schema=REAUTH_SCHEMA,
106  errors=errors,
107  description_placeholders={
108  CONF_USERNAME: username,
109  CONF_NAME: reauth_entry.title,
110  },
111  )
112 
113  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=user_input)
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:61
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:87
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:81
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)
dict[str, str]|None validate_input(dict[str, Any] user_input)
Definition: config_flow.py:27