Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Cloudflare integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any
8 
9 import pycfdns
10 import voluptuous as vol
11 
12 from homeassistant.components import persistent_notification
13 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
14 from homeassistant.const import CONF_API_TOKEN, CONF_ZONE
15 from homeassistant.core import HomeAssistant
16 from homeassistant.exceptions import HomeAssistantError
17 from homeassistant.helpers import config_validation as cv
18 from homeassistant.helpers.aiohttp_client import async_get_clientsession
19 
20 from .const import CONF_RECORDS, DOMAIN
21 from .helpers import get_zone_id
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 DATA_SCHEMA = vol.Schema(
26  {
27  vol.Required(CONF_API_TOKEN): str,
28  }
29 )
30 
31 
32 def _zone_schema(zones: list[pycfdns.ZoneModel] | None = None) -> vol.Schema:
33  """Zone selection schema."""
34  zones_list = []
35 
36  if zones is not None:
37  zones_list = [zones["name"] for zones in zones]
38 
39  return vol.Schema({vol.Required(CONF_ZONE): vol.In(zones_list)})
40 
41 
42 def _records_schema(records: list[pycfdns.RecordModel] | None = None) -> vol.Schema:
43  """Zone records selection schema."""
44  records_dict = {}
45 
46  if records:
47  records_dict = {name["name"]: name["name"] for name in records}
48 
49  return vol.Schema({vol.Required(CONF_RECORDS): cv.multi_select(records_dict)})
50 
51 
52 async def _validate_input(
53  hass: HomeAssistant,
54  data: dict[str, Any],
55 ) -> dict[str, Any]:
56  """Validate the user input allows us to connect.
57 
58  Data has the keys from DATA_SCHEMA with values provided by the user.
59  """
60  zone = data.get(CONF_ZONE)
61  records: list[pycfdns.RecordModel] = []
62 
63  client = pycfdns.Client(
64  api_token=data[CONF_API_TOKEN],
65  client_session=async_get_clientsession(hass),
66  )
67 
68  zones = await client.list_zones()
69  if zone and (zone_id := get_zone_id(zone, zones)) is not None:
70  records = await client.list_dns_records(zone_id=zone_id, type="A")
71 
72  return {"zones": zones, "records": records}
73 
74 
75 class CloudflareConfigFlow(ConfigFlow, domain=DOMAIN):
76  """Handle a config flow for Cloudflare."""
77 
78  VERSION = 1
79 
80  def __init__(self) -> None:
81  """Initialize the Cloudflare config flow."""
82  self.cloudflare_config: dict[str, Any] = {}
83  self.zoneszones: list[pycfdns.ZoneModel] | None = None
84  self.recordsrecords: list[pycfdns.RecordModel] | None = None
85 
86  async def async_step_reauth(
87  self, entry_data: Mapping[str, Any]
88  ) -> ConfigFlowResult:
89  """Handle initiation of re-authentication with Cloudflare."""
90  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
91 
93  self, user_input: dict[str, Any] | None = None
94  ) -> ConfigFlowResult:
95  """Handle re-authentication with Cloudflare."""
96  errors: dict[str, str] = {}
97 
98  if user_input is not None:
99  _, errors = await self._async_validate_or_error_async_validate_or_error(user_input)
100 
101  if not errors:
102  reauth_entry = self._get_reauth_entry_get_reauth_entry()
103  return self.async_update_reload_and_abortasync_update_reload_and_abort(
104  reauth_entry,
105  data={
106  **reauth_entry.data,
107  CONF_API_TOKEN: user_input[CONF_API_TOKEN],
108  },
109  )
110 
111  return self.async_show_formasync_show_formasync_show_form(
112  step_id="reauth_confirm",
113  data_schema=DATA_SCHEMA,
114  errors=errors,
115  )
116 
117  async def async_step_user(
118  self, user_input: dict[str, Any] | None = None
119  ) -> ConfigFlowResult:
120  """Handle a flow initiated by the user."""
121  persistent_notification.async_dismiss(self.hass, "cloudflare_setup")
122 
123  errors: dict[str, str] = {}
124 
125  if user_input is not None:
126  info, errors = await self._async_validate_or_error_async_validate_or_error(user_input)
127 
128  if not errors:
129  self.cloudflare_config.update(user_input)
130  self.zoneszones = info["zones"]
131  return await self.async_step_zoneasync_step_zone()
132 
133  return self.async_show_formasync_show_formasync_show_form(
134  step_id="user", data_schema=DATA_SCHEMA, errors=errors
135  )
136 
137  async def async_step_zone(
138  self, user_input: dict[str, Any] | None = None
139  ) -> ConfigFlowResult:
140  """Handle the picking the zone."""
141  errors: dict[str, str] = {}
142 
143  if user_input is not None:
144  self.cloudflare_config.update(user_input)
145  info, errors = await self._async_validate_or_error_async_validate_or_error(self.cloudflare_config)
146 
147  if not errors:
148  await self.async_set_unique_idasync_set_unique_id(user_input[CONF_ZONE])
149  self.recordsrecords = info["records"]
150 
151  return await self.async_step_recordsasync_step_records()
152 
153  return self.async_show_formasync_show_formasync_show_form(
154  step_id="zone",
155  data_schema=_zone_schema(self.zoneszones),
156  errors=errors,
157  )
158 
160  self, user_input: dict[str, Any] | None = None
161  ) -> ConfigFlowResult:
162  """Handle the picking the zone records."""
163 
164  if user_input is not None:
165  self.cloudflare_config.update(user_input)
166  title = self.cloudflare_config[CONF_ZONE]
167  return self.async_create_entryasync_create_entryasync_create_entry(title=title, data=self.cloudflare_config)
168 
169  return self.async_show_formasync_show_formasync_show_form(
170  step_id="records",
171  data_schema=_records_schema(self.recordsrecords),
172  )
173 
175  self, config: dict[str, Any]
176  ) -> tuple[dict[str, list[Any]], dict[str, str]]:
177  errors: dict[str, str] = {}
178  info = {}
179 
180  try:
181  info = await _validate_input(self.hass, config)
182  except pycfdns.ComunicationException:
183  errors["base"] = "cannot_connect"
184  except pycfdns.AuthenticationException:
185  errors["base"] = "invalid_auth"
186  except Exception:
187  _LOGGER.exception("Unexpected exception")
188  errors["base"] = "unknown"
189 
190  return info, errors
191 
192 
194  """Error to indicate we cannot connect."""
195 
196 
197 class InvalidAuth(HomeAssistantError):
198  """Error to indicate there is invalid auth."""
ConfigFlowResult async_step_records(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:161
ConfigFlowResult async_step_user(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:119
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:94
tuple[dict[str, list[Any]], dict[str, str]] _async_validate_or_error(self, dict[str, Any] config)
Definition: config_flow.py:176
ConfigFlowResult async_step_zone(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:139
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:88
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, Any] _validate_input(HomeAssistant hass, dict[str, Any] data)
Definition: config_flow.py:55
vol.Schema _zone_schema(list[pycfdns.ZoneModel]|None zones=None)
Definition: config_flow.py:32
vol.Schema _records_schema(list[pycfdns.RecordModel]|None records=None)
Definition: config_flow.py:42
str|None get_zone_id(str target_zone_name, list[pycfdns.ZoneModel] zones)
Definition: helpers.py:6
IssData update(pyiss.ISS iss)
Definition: __init__.py:33
aiohttp.ClientSession async_get_clientsession(HomeAssistant hass, bool verify_ssl=True, socket.AddressFamily family=socket.AF_UNSPEC, ssl_util.SSLCipherList ssl_cipher=ssl_util.SSLCipherList.PYTHON_DEFAULT)