Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Opower 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 opower import (
10  CannotConnect,
11  InvalidAuth,
12  Opower,
13  get_supported_utility_names,
14  select_utility,
15 )
16 import voluptuous as vol
17 
18 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
19 from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
20 from homeassistant.core import HomeAssistant, callback
21 from homeassistant.helpers.aiohttp_client import async_create_clientsession
22 from homeassistant.helpers.typing import VolDictType
23 
24 from .const import CONF_TOTP_SECRET, CONF_UTILITY, DOMAIN
25 
26 _LOGGER = logging.getLogger(__name__)
27 
28 STEP_USER_DATA_SCHEMA = vol.Schema(
29  {
30  vol.Required(CONF_UTILITY): vol.In(get_supported_utility_names()),
31  vol.Required(CONF_USERNAME): str,
32  vol.Required(CONF_PASSWORD): str,
33  }
34 )
35 
36 
37 async def _validate_login(
38  hass: HomeAssistant, login_data: dict[str, str]
39 ) -> dict[str, str]:
40  """Validate login data and return any errors."""
41  api = Opower(
43  login_data[CONF_UTILITY],
44  login_data[CONF_USERNAME],
45  login_data[CONF_PASSWORD],
46  login_data.get(CONF_TOTP_SECRET),
47  )
48  errors: dict[str, str] = {}
49  try:
50  await api.async_login()
51  except InvalidAuth:
52  _LOGGER.exception(
53  "Invalid auth when connecting to %s", login_data[CONF_UTILITY]
54  )
55  errors["base"] = "invalid_auth"
56  except CannotConnect:
57  _LOGGER.exception("Could not connect to %s", login_data[CONF_UTILITY])
58  errors["base"] = "cannot_connect"
59  return errors
60 
61 
62 class OpowerConfigFlow(ConfigFlow, domain=DOMAIN):
63  """Handle a config flow for Opower."""
64 
65  VERSION = 1
66 
67  def __init__(self) -> None:
68  """Initialize a new OpowerConfigFlow."""
69  self.utility_infoutility_info: dict[str, Any] | None = None
70 
71  async def async_step_user(
72  self, user_input: dict[str, Any] | None = None
73  ) -> ConfigFlowResult:
74  """Handle the initial step."""
75  errors: dict[str, str] = {}
76  if user_input is not None:
77  self._async_abort_entries_match_async_abort_entries_match(
78  {
79  CONF_UTILITY: user_input[CONF_UTILITY],
80  CONF_USERNAME: user_input[CONF_USERNAME],
81  }
82  )
83  if select_utility(user_input[CONF_UTILITY]).accepts_mfa():
84  self.utility_infoutility_info = user_input
85  return await self.async_step_mfaasync_step_mfa()
86 
87  errors = await _validate_login(self.hass, user_input)
88  if not errors:
89  return self._async_create_opower_entry_async_create_opower_entry(user_input)
90 
91  return self.async_show_formasync_show_formasync_show_form(
92  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
93  )
94 
95  async def async_step_mfa(
96  self, user_input: dict[str, Any] | None = None
97  ) -> ConfigFlowResult:
98  """Handle MFA step."""
99  assert self.utility_infoutility_info is not None
100  errors: dict[str, str] = {}
101  if user_input is not None:
102  data = {**self.utility_infoutility_info, **user_input}
103  errors = await _validate_login(self.hass, data)
104  if not errors:
105  return self._async_create_opower_entry_async_create_opower_entry(data)
106 
107  if errors:
108  schema = {
109  vol.Required(
110  CONF_USERNAME, default=self.utility_infoutility_info[CONF_USERNAME]
111  ): str,
112  vol.Required(CONF_PASSWORD): str,
113  }
114  else:
115  schema = {}
116 
117  schema[vol.Required(CONF_TOTP_SECRET)] = str
118 
119  return self.async_show_formasync_show_formasync_show_form(
120  step_id="mfa",
121  data_schema=vol.Schema(schema),
122  errors=errors,
123  )
124 
125  @callback
126  def _async_create_opower_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
127  """Create the config entry."""
128  return self.async_create_entryasync_create_entryasync_create_entry(
129  title=f"{data[CONF_UTILITY]} ({data[CONF_USERNAME]})",
130  data=data,
131  )
132 
133  async def async_step_reauth(
134  self, entry_data: Mapping[str, Any]
135  ) -> ConfigFlowResult:
136  """Handle configuration by re-auth."""
137  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
138 
140  self, user_input: dict[str, Any] | None = None
141  ) -> ConfigFlowResult:
142  """Dialog that informs the user that reauth is required."""
143  errors: dict[str, str] = {}
144  reauth_entry = self._get_reauth_entry_get_reauth_entry()
145  if user_input is not None:
146  data = {**reauth_entry.data, **user_input}
147  errors = await _validate_login(self.hass, data)
148  if not errors:
149  return self.async_update_reload_and_abortasync_update_reload_and_abort(reauth_entry, data=data)
150 
151  schema: VolDictType = {
152  vol.Required(CONF_USERNAME): reauth_entry.data[CONF_USERNAME],
153  vol.Required(CONF_PASSWORD): str,
154  }
155  if select_utility(reauth_entry.data[CONF_UTILITY]).accepts_mfa():
156  schema[vol.Optional(CONF_TOTP_SECRET)] = str
157  return self.async_show_formasync_show_formasync_show_form(
158  step_id="reauth_confirm",
159  data_schema=vol.Schema(schema),
160  errors=errors,
161  description_placeholders={CONF_NAME: reauth_entry.title},
162  )
ConfigFlowResult _async_create_opower_entry(self, dict[str, Any] data)
Definition: config_flow.py:126
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:141
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:73
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:135
ConfigFlowResult async_step_mfa(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:97
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 _async_abort_entries_match(self, dict[str, Any]|None match_dict=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)
dict[str, str] _validate_login(HomeAssistant hass, dict[str, str] login_data)
Definition: config_flow.py:39
aiohttp.ClientSession async_create_clientsession()
Definition: coordinator.py:51