Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Picnic 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 python_picnic_api import PicnicAPI
10 from python_picnic_api.session import PicnicAuthError
11 import requests
12 import voluptuous as vol
13 
14 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
15 from homeassistant.const import (
16  CONF_ACCESS_TOKEN,
17  CONF_COUNTRY_CODE,
18  CONF_PASSWORD,
19  CONF_USERNAME,
20 )
21 from homeassistant.core import HomeAssistant
22 from homeassistant.exceptions import HomeAssistantError
23 
24 from .const import COUNTRY_CODES, DOMAIN
25 
26 _LOGGER = logging.getLogger(__name__)
27 
28 STEP_USER_DATA_SCHEMA = vol.Schema(
29  {
30  vol.Required(CONF_USERNAME): str,
31  vol.Required(CONF_PASSWORD): str,
32  vol.Required(CONF_COUNTRY_CODE, default=COUNTRY_CODES[0]): vol.In(
33  COUNTRY_CODES
34  ),
35  }
36 )
37 
38 
39 class PicnicHub:
40  """Hub class to test user authentication."""
41 
42  @staticmethod
43  def authenticate(username, password, country_code) -> tuple[str, dict]:
44  """Test if we can authenticate with the Picnic API."""
45  picnic = PicnicAPI(username, password, country_code)
46  return picnic.session.auth_token, picnic.get_user()
47 
48 
49 async def validate_input(hass: HomeAssistant, data):
50  """Validate the user input allows us to connect.
51 
52  Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
53  """
54  hub = PicnicHub()
55 
56  try:
57  auth_token, user_data = await hass.async_add_executor_job(
58  hub.authenticate,
59  data[CONF_USERNAME],
60  data[CONF_PASSWORD],
61  data[CONF_COUNTRY_CODE],
62  )
63  except requests.exceptions.ConnectionError as error:
64  raise CannotConnect from error
65  except PicnicAuthError as error:
66  raise InvalidAuth from error
67 
68  # Return the validation result
69  address = (
70  f'{user_data["address"]["street"]} {user_data["address"]["house_number"]}'
71  f'{user_data["address"]["house_number_ext"]}'
72  )
73  return auth_token, {
74  "title": address,
75  "unique_id": user_data["user_id"],
76  }
77 
78 
79 class PicnicConfigFlow(ConfigFlow, domain=DOMAIN):
80  """Handle a config flow for Picnic."""
81 
82  VERSION = 1
83 
84  async def async_step_reauth(
85  self, entry_data: Mapping[str, Any]
86  ) -> ConfigFlowResult:
87  """Perform the re-auth step upon an API authentication error."""
88  return await self.async_step_userasync_step_userasync_step_user()
89 
90  async def async_step_user(
91  self, user_input: dict[str, Any] | None = None
92  ) -> ConfigFlowResult:
93  """Handle the authentication step, this is the generic step for both `step_user` and `step_reauth`."""
94  if user_input is None:
95  return self.async_show_formasync_show_formasync_show_form(
96  step_id="user", data_schema=STEP_USER_DATA_SCHEMA
97  )
98 
99  errors = {}
100 
101  try:
102  auth_token, info = await validate_input(self.hass, user_input)
103  except CannotConnect:
104  errors["base"] = "cannot_connect"
105  except InvalidAuth:
106  errors["base"] = "invalid_auth"
107  except Exception:
108  _LOGGER.exception("Unexpected exception")
109  errors["base"] = "unknown"
110  else:
111  data = {
112  CONF_ACCESS_TOKEN: auth_token,
113  CONF_COUNTRY_CODE: user_input[CONF_COUNTRY_CODE],
114  }
115  existing_entry = await self.async_set_unique_idasync_set_unique_id(info["unique_id"])
116 
117  # Abort if we're adding a new config and the unique id is already in use, else create the entry
118  if self.sourcesourcesource != SOURCE_REAUTH:
119  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
120  return self.async_create_entryasync_create_entryasync_create_entry(title="Picnic", data=data)
121 
122  # In case of re-auth, only continue if an exiting account exists with the same unique id
123  if existing_entry:
124  self.hass.config_entries.async_update_entry(existing_entry, data=data)
125  await self.hass.config_entries.async_reload(existing_entry.entry_id)
126  return self.async_abortasync_abortasync_abort(reason="reauth_successful")
127 
128  # Set the error because the account is different
129  errors["base"] = "different_account"
130 
131  return self.async_show_formasync_show_formasync_show_form(
132  step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
133  )
134 
135 
137  """Error to indicate we cannot connect."""
138 
139 
140 class InvalidAuth(HomeAssistantError):
141  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:86
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:92
tuple[str, dict] authenticate(username, password, country_code)
Definition: config_flow.py:43
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_step_user(self, dict[str, Any]|None user_input=None)
ConfigFlowResult async_abort(self, *str reason, 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)
str|None source(self)
_FlowResultT async_abort(self, *str reason, Mapping[str, str]|None description_placeholders=None)
def validate_input(HomeAssistant hass, data)
Definition: config_flow.py:49