Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Google Sheets 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 google.oauth2.credentials import Credentials
10 from gspread import Client, GSpreadException
11 
12 from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult
13 from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
14 from homeassistant.helpers import config_entry_oauth2_flow
15 
16 from .const import DEFAULT_ACCESS, DEFAULT_NAME, DOMAIN
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
22  config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
23 ):
24  """Config flow to handle Google Sheets OAuth2 authentication."""
25 
26  DOMAIN = DOMAIN
27 
28  @property
29  def logger(self) -> logging.Logger:
30  """Return logger."""
31  return logging.getLogger(__name__)
32 
33  @property
34  def extra_authorize_data(self) -> dict[str, Any]:
35  """Extra data that needs to be appended to the authorize url."""
36  return {
37  "scope": DEFAULT_ACCESS,
38  # Add params to ensure we get back a refresh token
39  "access_type": "offline",
40  "prompt": "consent",
41  }
42 
43  async def async_step_reauth(
44  self, entry_data: Mapping[str, Any]
45  ) -> ConfigFlowResult:
46  """Perform reauth upon an API authentication error."""
47  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
48 
50  self, user_input: dict[str, Any] | None = None
51  ) -> ConfigFlowResult:
52  """Confirm reauth dialog."""
53  if user_input is None:
54  return self.async_show_form(step_id="reauth_confirm")
55  return await self.async_step_user()
56 
57  async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
58  """Create an entry for the flow, or update existing entry."""
59  service = Client(
60  Credentials(data[CONF_TOKEN][CONF_ACCESS_TOKEN]) # type: ignore[no-untyped-call]
61  )
62 
63  if self.sourcesource == SOURCE_REAUTH:
64  reauth_entry = self._get_reauth_entry()
65  _LOGGER.debug("service.open_by_key")
66  try:
67  await self.hass.async_add_executor_job(
68  service.open_by_key,
69  reauth_entry.unique_id,
70  )
71  except GSpreadException as err:
72  _LOGGER.error(
73  "Could not find spreadsheet '%s': %s",
74  reauth_entry.unique_id,
75  str(err),
76  )
77  return self.async_abort(reason="open_spreadsheet_failure")
78 
79  return self.async_update_reload_and_abort(reauth_entry, data=data)
80 
81  try:
82  doc = await self.hass.async_add_executor_job(
83  service.create, "Home Assistant"
84  )
85  except GSpreadException as err:
86  _LOGGER.error("Error creating spreadsheet: %s", str(err))
87  return self.async_abort(reason="create_spreadsheet_failure")
88 
89  await self.async_set_unique_id(doc.id)
90  self._abort_if_unique_id_configured()
91  return self.async_create_entry(
92  title=DEFAULT_NAME, data=data, description_placeholders={"url": doc.url}
93  )
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:45
ConfigFlowResult async_oauth_create_entry(self, dict[str, Any] data)
Definition: config_flow.py:57
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:51