Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """API for Honeywell Lyric bound to Home Assistant OAuth."""
2 
3 from typing import cast
4 
5 from aiohttp import BasicAuth, ClientSession
6 from aiolyric.client import LyricClient
7 
8 from homeassistant.components.application_credentials import AuthImplementation
9 from homeassistant.helpers import config_entry_oauth2_flow
10 from homeassistant.helpers.aiohttp_client import async_get_clientsession
11 
12 
13 class OAuth2SessionLyric(config_entry_oauth2_flow.OAuth2Session):
14  """OAuth2Session for Lyric."""
15 
16  async def force_refresh_token(self) -> None:
17  """Force a token refresh."""
18  new_token = await self.implementation.async_refresh_token(self.token)
19 
20  self.hass.config_entries.async_update_entry(
21  self.config_entry, data={**self.config_entry.data, "token": new_token}
22  )
23 
24 
25 class ConfigEntryLyricClient(LyricClient):
26  """Provide Honeywell Lyric authentication tied to an OAuth2 based config entry."""
27 
28  def __init__(
29  self,
30  websession: ClientSession,
31  oauth_session: config_entry_oauth2_flow.OAuth2Session,
32  ) -> None:
33  """Initialize Honeywell Lyric auth."""
34  super().__init__(websession)
35  self._oauth_session_oauth_session = oauth_session
36 
37  async def async_get_access_token(self):
38  """Return a valid access token."""
39  await self._oauth_session_oauth_session.async_ensure_token_valid()
40 
41  return self._oauth_session_oauth_session.token["access_token"]
42 
43 
45  AuthImplementation,
46 ):
47  """Lyric Local OAuth2 implementation."""
48 
49  async def _token_request(self, data: dict) -> dict:
50  """Make a token request."""
51  session = async_get_clientsession(self.hass)
52 
53  data["client_id"] = self.client_id
54 
55  if self.client_secret is not None:
56  data["client_secret"] = self.client_secret
57 
58  headers = {
59  "Authorization": BasicAuth(self.client_id, self.client_secret).encode(),
60  "Content-Type": "application/x-www-form-urlencoded",
61  }
62 
63  resp = await session.post(self.token_url, headers=headers, data=data)
64  resp.raise_for_status()
65  return cast(dict, await resp.json())
None __init__(self, ClientSession websession, config_entry_oauth2_flow.OAuth2Session oauth_session)
Definition: api.py:32
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)