Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Google Tasks."""
2 
3 from collections.abc import Mapping
4 import logging
5 from typing import Any
6 
7 from google.oauth2.credentials import Credentials
8 from googleapiclient.discovery import build
9 from googleapiclient.errors import HttpError
10 from googleapiclient.http import HttpRequest
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 DOMAIN, OAUTH2_SCOPES
17 
18 
20  config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
21 ):
22  """Config flow to handle Google Tasks OAuth2 authentication."""
23 
24  DOMAIN = DOMAIN
25 
26  @property
27  def logger(self) -> logging.Logger:
28  """Return logger."""
29  return logging.getLogger(__name__)
30 
31  @property
32  def extra_authorize_data(self) -> dict[str, Any]:
33  """Extra data that needs to be appended to the authorize url."""
34  return {
35  "scope": " ".join(OAUTH2_SCOPES),
36  # Add params to ensure we get back a refresh token
37  "access_type": "offline",
38  "prompt": "consent",
39  }
40 
41  async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
42  """Create an entry for the flow."""
43  credentials = Credentials(token=data[CONF_TOKEN][CONF_ACCESS_TOKEN])
44  try:
45  user_resource = build(
46  "oauth2",
47  "v2",
48  credentials=credentials,
49  )
50  user_resource_cmd: HttpRequest = user_resource.userinfo().get()
51  user_resource_info = await self.hass.async_add_executor_job(
52  user_resource_cmd.execute
53  )
54  resource = build(
55  "tasks",
56  "v1",
57  credentials=credentials,
58  )
59  cmd: HttpRequest = resource.tasklists().list()
60  await self.hass.async_add_executor_job(cmd.execute)
61  except HttpError as ex:
62  error = ex.reason
63  return self.async_abort(
64  reason="access_not_configured",
65  description_placeholders={"message": error},
66  )
67  except Exception:
68  self.loggerlogger.exception("Unknown error occurred")
69  return self.async_abort(reason="unknown")
70  user_id = user_resource_info["id"]
71  await self.async_set_unique_id(user_id)
72 
73  if self.source != SOURCE_REAUTH:
74  self._abort_if_unique_id_configured()
75  return self.async_create_entry(title=user_resource_info["name"], data=data)
76 
77  reauth_entry = self._get_reauth_entry()
78  if reauth_entry.unique_id:
79  self._abort_if_unique_id_mismatch(reason="wrong_account")
80 
81  return self.async_update_reload_and_abort(
82  reauth_entry, unique_id=user_id, data=data
83  )
84 
85  async def async_step_reauth(
86  self, entry_data: Mapping[str, Any]
87  ) -> ConfigFlowResult:
88  """Perform reauth upon an API authentication error."""
89  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
90 
92  self, user_input: dict[str, Any] | None = None
93  ) -> ConfigFlowResult:
94  """Confirm reauth dialog."""
95  if user_input is None:
96  return self.async_show_form(step_id="reauth_confirm")
97  return await self.async_step_user()
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:87
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:93
ConfigFlowResult async_oauth_create_entry(self, dict[str, Any] data)
Definition: config_flow.py:41
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88