Home Assistant Unofficial Reference 2024.12.1
oauth.py
Go to the documentation of this file.
1 """oAuth2 functions and classes for Geocaching API integration."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
8  AuthImplementation,
9  AuthorizationServer,
10  ClientCredential,
11 )
12 from homeassistant.core import HomeAssistant
13 
14 from .const import ENVIRONMENT, ENVIRONMENT_URLS
15 
16 
18  """Local OAuth2 implementation for Geocaching."""
19 
20  def __init__(
21  self,
22  hass: HomeAssistant,
23  auth_domain: str,
24  credential: ClientCredential,
25  ) -> None:
26  """Local Geocaching Oauth Implementation."""
27  super().__init__(
28  hass=hass,
29  auth_domain=auth_domain,
30  credential=credential,
31  authorization_server=AuthorizationServer(
32  authorize_url=ENVIRONMENT_URLS[ENVIRONMENT]["authorize_url"],
33  token_url=ENVIRONMENT_URLS[ENVIRONMENT]["token_url"],
34  ),
35  )
36 
37  @property
38  def extra_authorize_data(self) -> dict:
39  """Extra data that needs to be appended to the authorize url."""
40  return {"scope": "*", "response_type": "code"}
41 
42  async def async_resolve_external_data(self, external_data: Any) -> dict:
43  """Initialize local Geocaching API auth implementation."""
44  redirect_uri = external_data["state"]["redirect_uri"]
45  data = {
46  "grant_type": "authorization_code",
47  "code": external_data["code"],
48  "redirect_uri": redirect_uri,
49  }
50  token = await self._token_request(data)
51  # Store the redirect_uri (Needed for refreshing token, but not according to oAuth2 spec!)
52  token["redirect_uri"] = redirect_uri
53  return token
54 
55  async def _async_refresh_token(self, token: dict) -> dict:
56  """Refresh tokens."""
57  data = {
58  "client_id": self.client_id,
59  "client_secret": self.client_secret,
60  "grant_type": "refresh_token",
61  "refresh_token": token["refresh_token"],
62  # Add previously stored redirect_uri (Mandatory, but not according to oAuth2 spec!)
63  "redirect_uri": token["redirect_uri"],
64  }
65 
66  new_token = await self._token_request(data)
67  return {**token, **new_token}
None __init__(self, HomeAssistant hass, str auth_domain, ClientCredential credential)
Definition: oauth.py:25