Home Assistant Unofficial Reference 2024.12.1
oauth2.py
Go to the documentation of this file.
1 """OAuth2 implementations for Toon."""
2 
3 from __future__ import annotations
4 
5 import base64
6 from typing import Any, cast
7 
9  AuthImplementation,
10  AuthorizationServer,
11  ClientCredential,
12 )
13 from homeassistant.core import HomeAssistant
14 from homeassistant.helpers.aiohttp_client import async_get_clientsession
15 
16 from .const import SCOPE_VALUES
17 
18 
20  """Local OAuth2 implementation for Electric Kiwi."""
21 
22  def __init__(
23  self,
24  hass: HomeAssistant,
25  domain: str,
26  client_credential: ClientCredential,
27  authorization_server: AuthorizationServer,
28  ) -> None:
29  """Set up Electric Kiwi oauth."""
30  super().__init__(
31  hass=hass,
32  auth_domain=domain,
33  credential=client_credential,
34  authorization_server=authorization_server,
35  )
36 
37  self._name_name_name = client_credential.name
38 
39  @property
40  def extra_authorize_data(self) -> dict[str, Any]:
41  """Extra data that needs to be appended to the authorize url."""
42  return {"scope": SCOPE_VALUES}
43 
44  async def async_resolve_external_data(self, external_data: Any) -> dict:
45  """Initialize local Electric Kiwi auth implementation."""
46  data = {
47  "grant_type": "authorization_code",
48  "code": external_data["code"],
49  "redirect_uri": external_data["state"]["redirect_uri"],
50  }
51 
52  return await self._token_request_token_request(data)
53 
54  async def _async_refresh_token(self, token: dict) -> dict:
55  """Refresh tokens."""
56  data = {
57  "grant_type": "refresh_token",
58  "refresh_token": token["refresh_token"],
59  }
60 
61  new_token = await self._token_request_token_request(data)
62  return {**token, **new_token}
63 
64  async def _token_request(self, data: dict) -> dict:
65  """Make a token request."""
66  session = async_get_clientsession(self.hass)
67  client_str = f"{self.client_id}:{self.client_secret}"
68  client_string_bytes = client_str.encode("ascii")
69 
70  base64_bytes = base64.b64encode(client_string_bytes)
71  base64_client = base64_bytes.decode("ascii")
72  headers = {"Authorization": f"Basic {base64_client}"}
73 
74  resp = await session.post(self.token_url, data=data, headers=headers)
75  resp.raise_for_status()
76  return cast(dict, await resp.json())
None __init__(self, HomeAssistant hass, str domain, ClientCredential client_credential, AuthorizationServer authorization_server)
Definition: oauth2.py:28
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)