Home Assistant Unofficial Reference 2024.12.1
api.py
Go to the documentation of this file.
1 """API for xbox bound to Home Assistant OAuth."""
2 
3 from aiohttp import ClientSession
4 from xbox.webapi.authentication.manager import AuthenticationManager
5 from xbox.webapi.authentication.models import OAuth2TokenResponse
6 
7 from homeassistant.helpers import config_entry_oauth2_flow
8 from homeassistant.util.dt import utc_from_timestamp
9 
10 
11 class AsyncConfigEntryAuth(AuthenticationManager):
12  """Provide xbox authentication tied to an OAuth2 based config entry."""
13 
14  def __init__(
15  self,
16  websession: ClientSession,
17  oauth_session: config_entry_oauth2_flow.OAuth2Session,
18  ) -> None:
19  """Initialize xbox auth."""
20  # Leaving out client credentials as they are handled by Home Assistant
21  super().__init__(websession, "", "", "")
22  self._oauth_session_oauth_session = oauth_session
23  self.oauthoauth = self._get_oauth_token_get_oauth_token()
24 
25  async def refresh_tokens(self) -> None:
26  """Return a valid access token."""
27  if not self._oauth_session_oauth_session.valid_token:
28  await self._oauth_session_oauth_session.async_ensure_token_valid()
29  self.oauthoauth = self._get_oauth_token_get_oauth_token()
30 
31  # This will skip the OAuth refresh and only refresh User and XSTS tokens
32  await super().refresh_tokens()
33 
34  def _get_oauth_token(self) -> OAuth2TokenResponse:
35  tokens = {**self._oauth_session_oauth_session.token}
36  issued = tokens["expires_at"] - tokens["expires_in"]
37  del tokens["expires_at"]
38  token_response = OAuth2TokenResponse.parse_obj(tokens)
39  token_response.issued = utc_from_timestamp(issued)
40  return token_response
OAuth2TokenResponse _get_oauth_token(self)
Definition: api.py:34
None __init__(self, ClientSession websession, config_entry_oauth2_flow.OAuth2Session oauth_session)
Definition: api.py:18