Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Google Mail integration."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 import logging
7 from typing import Any, cast
8 
9 from google.oauth2.credentials import Credentials
10 from googleapiclient.discovery import build
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, DOMAIN
17 
18 
20  config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
21 ):
22  """Config flow to handle Google Mail 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(DEFAULT_ACCESS),
36  # Add params to ensure we get back a refresh token
37  "access_type": "offline",
38  "prompt": "consent",
39  }
40 
41  async def async_step_reauth(
42  self, entry_data: Mapping[str, Any]
43  ) -> ConfigFlowResult:
44  """Perform reauth upon an API authentication error."""
45  return await self.async_step_reauth_confirmasync_step_reauth_confirm()
46 
48  self, user_input: dict[str, Any] | None = None
49  ) -> ConfigFlowResult:
50  """Confirm reauth dialog."""
51  if user_input is None:
52  return self.async_show_form(step_id="reauth_confirm")
53  return await self.async_step_user()
54 
55  async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult:
56  """Create an entry for the flow, or update existing entry."""
57 
58  def _get_profile() -> str:
59  """Get profile from inside the executor."""
60  users = build("gmail", "v1", credentials=credentials).users()
61  return users.getProfile(userId="me").execute()["emailAddress"]
62 
63  credentials = Credentials(data[CONF_TOKEN][CONF_ACCESS_TOKEN])
64  email = await self.hass.async_add_executor_job(_get_profile)
65 
66  await self.async_set_unique_id(email)
67  if self.source != SOURCE_REAUTH:
68  self._abort_if_unique_id_configured()
69 
70  return self.async_create_entry(title=email, data=data)
71 
72  reauth_entry = self._get_reauth_entry()
73  self._abort_if_unique_id_mismatch(
74  reason="wrong_account",
75  description_placeholders={"email": cast(str, reauth_entry.unique_id)},
76  )
77  return self.async_update_reload_and_abort(reauth_entry, data=data)
ConfigFlowResult async_step_reauth(self, Mapping[str, Any] entry_data)
Definition: config_flow.py:43
ConfigFlowResult async_oauth_create_entry(self, dict[str, Any] data)
Definition: config_flow.py:55
ConfigFlowResult async_step_reauth_confirm(self, dict[str, Any]|None user_input=None)
Definition: config_flow.py:49
def execute(hass, filename, source, data=None, return_response=False)
Definition: __init__.py:194