Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for microBees integration."""
2 
3 from collections.abc import Mapping
4 import logging
5 from typing import Any
6 
7 from microBeesPy import MicroBees, MicroBeesException
8 
9 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult
10 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
11 from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
12 
13 from .const import DOMAIN
14 
15 
17  config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
18 ):
19  """Handle a config flow for microBees."""
20 
21  DOMAIN = DOMAIN
22 
23  @property
24  def logger(self) -> logging.Logger:
25  """Return logger."""
26  return logging.getLogger(__name__)
27 
28  @property
29  def extra_authorize_data(self) -> dict[str, Any]:
30  """Extra data that needs to be appended to the authorize url."""
31  scopes = ["read", "write"]
32  return {"scope": " ".join(scopes)}
33 
34  async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
35  """Create an oauth config entry or update existing entry for reauth."""
36 
37  microbees = MicroBees(
38  session=aiohttp_client.async_get_clientsession(self.hass),
39  token=data[CONF_TOKEN][CONF_ACCESS_TOKEN],
40  )
41 
42  try:
43  current_user = await microbees.getMyProfile()
44  except MicroBeesException:
45  return self.async_abort(reason="invalid_auth")
46  except Exception:
47  self.loggerlogger.exception("Unexpected error")
48  return self.async_abort(reason="unknown")
49 
50  await self.async_set_unique_id(current_user.id)
51  if self.source != SOURCE_REAUTH:
52  self._abort_if_unique_id_configured()
53  return self.async_create_entry(
54  title=current_user.username,
55  data=data,
56  )
57 
58  self._abort_if_unique_id_mismatch(reason="wrong_account")
59  return self.async_update_reload_and_abort(self._get_reauth_entry(), data=data)
60 
61  async def async_step_reauth(
62  self, entry_data: Mapping[str, Any]
63  ) -> ConfigFlowResult:
64  """Perform reauth upon an API authentication error."""
65  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
66 
68  self, user_input: dict[str, Any] | None = None
69  ) -> ConfigFlowResult:
70  """Confirm reauth dialog."""
71  if user_input is None:
72  return self.async_show_form(step_id="reauth_confirm")
73  return await self.async_step_user()
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:63
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:69
ConfigFlowResult async_oauth_create_entry(self, dict[str, Any] data)
Definition: config_flow.py:34