Prepare google calendar integration for Application Credentials (#71748)

* Prepare google calendar integration for Application Credentials

Update google calendar integration to have fewer dependencies on
yaml configuration data to prepare for supporting application
credentials, which means setup can happen without configuration.yaml
at all. This pre-factoring will allow the following PR adding
application credentials support to be more focused.

* Add test coverage for device auth checks
This commit is contained in:
Allen Porter 2022-05-12 19:33:52 -07:00 committed by GitHub
parent 7ab4960b1e
commit 32e4046435
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 103 additions and 25 deletions

View file

@ -19,18 +19,25 @@ from oauth2client.client import (
OAuth2WebServerFlow,
)
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
from homeassistant.core import CALLBACK_TYPE, HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util import dt
from .const import CONF_CALENDAR_ACCESS, DATA_CONFIG, DEVICE_AUTH_IMPL, DOMAIN
from .const import (
CONF_CALENDAR_ACCESS,
DATA_CONFIG,
DEFAULT_FEATURE_ACCESS,
DEVICE_AUTH_IMPL,
DOMAIN,
FeatureAccess,
)
_LOGGER = logging.getLogger(__name__)
EVENT_PAGE_SIZE = 100
EXCHANGE_TIMEOUT_SECONDS = 60
DEVICE_AUTH_CREDS = "creds"
class OAuthError(Exception):
@ -53,7 +60,7 @@ class DeviceAuth(config_entry_oauth2_flow.LocalOAuth2Implementation):
async def async_resolve_external_data(self, external_data: Any) -> dict:
"""Resolve a Google API Credentials object to Home Assistant token."""
creds: Credentials = external_data["creds"]
creds: Credentials = external_data[DEVICE_AUTH_CREDS]
return {
"access_token": creds.access_token,
"refresh_token": creds.refresh_token,
@ -132,13 +139,25 @@ class DeviceFlow:
)
async def async_create_device_flow(hass: HomeAssistant) -> DeviceFlow:
def get_feature_access(hass: HomeAssistant) -> FeatureAccess:
"""Return the desired calendar feature access."""
# This may be called during config entry setup without integration setup running when there
# is no google entry in configuration.yaml
return (
hass.data.get(DOMAIN, {})
.get(DATA_CONFIG, {})
.get(CONF_CALENDAR_ACCESS, DEFAULT_FEATURE_ACCESS)
)
async def async_create_device_flow(
hass: HomeAssistant, client_id: str, client_secret: str, access: FeatureAccess
) -> DeviceFlow:
"""Create a new Device flow."""
conf = hass.data[DOMAIN][DATA_CONFIG]
oauth_flow = OAuth2WebServerFlow(
client_id=conf[CONF_CLIENT_ID],
client_secret=conf[CONF_CLIENT_SECRET],
scope=conf[CONF_CALENDAR_ACCESS].scope,
client_id=client_id,
client_secret=client_secret,
scope=access.scope,
redirect_uri="",
)
try: