Only create cloud user if cloud in use (#29150)
* Only create cloud user if cloud in use * Pass context to alexa * Update requirements * Fix handing & design pattern for 0.30 * fix tests * Fix lint & tests * rename internal user
This commit is contained in:
1 parent
5d5d053bce
commit
b847d55077
15 files changed
+221
-145
No files matched your search
@@ -4,7 +4,6 @@ import logging
|
||||
from hass_nabucasa import Cloud
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.auth.const import GROUP_ID_ADMIN
|
||||
from homeassistant.components.alexa import const as alexa_const
|
||||
from homeassistant.components.google_assistant import const as ga_c
|
||||
from homeassistant.const import (
|
||||
@@ -186,19 +185,6 @@ async def async_setup(hass, config):
|
||||
prefs = CloudPreferences(hass)
|
||||
await prefs.async_initialize()
|
||||
|
||||
# Cloud user
|
||||
user = None
|
||||
if prefs.cloud_user:
|
||||
# Fetch the user. It can happen that the user no longer exists if
|
||||
# an image was restored without restoring the cloud prefs.
|
||||
user = await hass.auth.async_get_user(prefs.cloud_user)
|
||||
|
||||
if user is None:
|
||||
user = await hass.auth.async_create_system_user(
|
||||
"Home Assistant Cloud", [GROUP_ID_ADMIN]
|
||||
)
|
||||
await prefs.async_update(cloud_user=user.id)
|
||||
|
||||
# Initialize Cloud
|
||||
websession = hass.helpers.aiohttp_client.async_get_clientsession()
|
||||
client = CloudClient(hass, prefs, websession, alexa_conf, google_conf)
|
||||
|
||||
@@ -7,7 +7,7 @@ import logging
|
||||
import aiohttp
|
||||
from hass_nabucasa.client import CloudClient as Interface
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.core import callback, Context
|
||||
from homeassistant.components.google_assistant import smart_home as ga
|
||||
from homeassistant.helpers.typing import HomeAssistantType
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
@@ -44,7 +44,6 @@ class CloudClient(Interface):
|
||||
self.alexa_user_config = alexa_user_config
|
||||
self._alexa_config = None
|
||||
self._google_config = None
|
||||
self.cloud = None
|
||||
|
||||
@property
|
||||
def base_path(self) -> Path:
|
||||
@@ -92,23 +91,22 @@ class CloudClient(Interface):
|
||||
|
||||
return self._alexa_config
|
||||
|
||||
@property
|
||||
def google_config(self) -> google_config.CloudGoogleConfig:
|
||||
async def get_google_config(self) -> google_config.CloudGoogleConfig:
|
||||
"""Return Google config."""
|
||||
if not self._google_config:
|
||||
assert self.cloud is not None
|
||||
|
||||
cloud_user = await self._prefs.get_cloud_user()
|
||||
|
||||
self._google_config = google_config.CloudGoogleConfig(
|
||||
self._hass, self.google_user_config, self._prefs, self.cloud
|
||||
self._hass, self.google_user_config, cloud_user, self._prefs, self.cloud
|
||||
)
|
||||
|
||||
return self._google_config
|
||||
|
||||
async def async_initialize(self, cloud) -> None:
|
||||
"""Initialize the client."""
|
||||
self.cloud = cloud
|
||||
|
||||
if not self.cloud.is_logged_in:
|
||||
return
|
||||
async def logged_in(self) -> None:
|
||||
"""When user logs in."""
|
||||
await self.prefs.async_set_username(self.cloud.username)
|
||||
|
||||
if self.alexa_config.enabled and self.alexa_config.should_report_state:
|
||||
try:
|
||||
@@ -116,14 +114,18 @@ class CloudClient(Interface):
|
||||
except alexa_errors.NoTokenAvailable:
|
||||
pass
|
||||
|
||||
if self.google_config.enabled:
|
||||
self.google_config.async_enable_local_sdk()
|
||||
if self._prefs.google_enabled:
|
||||
gconf = await self.get_google_config()
|
||||
|
||||
if self.google_config.should_report_state:
|
||||
self.google_config.async_enable_report_state()
|
||||
gconf.async_enable_local_sdk()
|
||||
|
||||
if gconf.should_report_state:
|
||||
gconf.async_enable_report_state()
|
||||
|
||||
async def cleanups(self) -> None:
|
||||
"""Cleanup some stuff after logout."""
|
||||
await self.prefs.async_set_username(None)
|
||||
|
||||
self._google_config = None
|
||||
|
||||
@callback
|
||||
@@ -141,8 +143,13 @@ class CloudClient(Interface):
|
||||
|
||||
async def async_alexa_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
||||
"""Process cloud alexa message to client."""
|
||||
cloud_user = await self._prefs.get_cloud_user()
|
||||
return await alexa_sh.async_handle_message(
|
||||
self._hass, self.alexa_config, payload, enabled=self._prefs.alexa_enabled
|
||||
self._hass,
|
||||
self.alexa_config,
|
||||
payload,
|
||||
context=Context(user_id=cloud_user),
|
||||
enabled=self._prefs.alexa_enabled,
|
||||
)
|
||||
|
||||
async def async_google_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
||||
@@ -150,8 +157,10 @@ class CloudClient(Interface):
|
||||
if not self._prefs.google_enabled:
|
||||
return ga.turned_off_response(payload)
|
||||
|
||||
gconf = await self.get_google_config()
|
||||
|
||||
return await ga.async_handle_message(
|
||||
self._hass, self.google_config, self.prefs.cloud_user, payload
|
||||
self._hass, gconf, gconf.cloud_user, payload
|
||||
)
|
||||
|
||||
async def async_webhook_message(self, payload: Dict[Any, Any]) -> Dict[Any, Any]:
|
||||
|
||||
@@ -17,6 +17,7 @@ PREF_DISABLE_2FA = "disable_2fa"
|
||||
PREF_ALIASES = "aliases"
|
||||
PREF_SHOULD_EXPOSE = "should_expose"
|
||||
PREF_GOOGLE_LOCAL_WEBHOOK_ID = "google_local_webhook_id"
|
||||
PREF_USERNAME = "username"
|
||||
DEFAULT_SHOULD_EXPOSE = True
|
||||
DEFAULT_DISABLE_2FA = False
|
||||
DEFAULT_ALEXA_REPORT_STATE = False
|
||||
|
||||
@@ -23,10 +23,11 @@ _LOGGER = logging.getLogger(__name__)
|
||||
class CloudGoogleConfig(AbstractConfig):
|
||||
"""HA Cloud Configuration for Google Assistant."""
|
||||
|
||||
def __init__(self, hass, config, prefs, cloud):
|
||||
def __init__(self, hass, config, cloud_user, prefs, cloud):
|
||||
"""Initialize the Google config."""
|
||||
super().__init__(hass)
|
||||
self._config = config
|
||||
self._user = cloud_user
|
||||
self._prefs = prefs
|
||||
self._cloud = cloud
|
||||
self._cur_entity_prefs = self._prefs.google_entity_configs
|
||||
@@ -46,7 +47,7 @@ class CloudGoogleConfig(AbstractConfig):
|
||||
@property
|
||||
def agent_user_id(self):
|
||||
"""Return Agent User Id to use for query responses."""
|
||||
return self._cloud.claims["cognito:username"]
|
||||
return self._cloud.username
|
||||
|
||||
@property
|
||||
def entity_config(self):
|
||||
@@ -74,7 +75,12 @@ class CloudGoogleConfig(AbstractConfig):
|
||||
@property
|
||||
def local_sdk_user_id(self):
|
||||
"""Return the user ID to be used for actions received via the local SDK."""
|
||||
return self._prefs.cloud_user
|
||||
return self._user
|
||||
|
||||
@property
|
||||
def cloud_user(self):
|
||||
"""Return Cloud User account."""
|
||||
return self._user
|
||||
|
||||
def should_expose(self, state):
|
||||
"""If a state object should be exposed."""
|
||||
|
||||
@@ -174,9 +174,8 @@ class GoogleActionsSyncView(HomeAssistantView):
|
||||
"""Trigger a Google Actions sync."""
|
||||
hass = request.app["hass"]
|
||||
cloud: Cloud = hass.data[DOMAIN]
|
||||
status = await cloud.client.google_config.async_sync_entities(
|
||||
cloud.client.google_config.agent_user_id
|
||||
)
|
||||
gconf = await cloud.client.get_google_config()
|
||||
status = await gconf.async_sync_entities(gconf.agent_user_id)
|
||||
return self.json({}, status_code=status)
|
||||
|
||||
|
||||
@@ -194,11 +193,7 @@ class CloudLoginView(HomeAssistantView):
|
||||
"""Handle login request."""
|
||||
hass = request.app["hass"]
|
||||
cloud = hass.data[DOMAIN]
|
||||
|
||||
with async_timeout.timeout(REQUEST_TIMEOUT):
|
||||
await hass.async_add_job(cloud.auth.login, data["email"], data["password"])
|
||||
|
||||
hass.async_add_job(cloud.iot.connect)
|
||||
await cloud.login(data["email"], data["password"])
|
||||
return self.json({"success": True})
|
||||
|
||||
|
||||
@@ -479,7 +474,8 @@ async def websocket_remote_disconnect(hass, connection, msg):
|
||||
async def google_assistant_list(hass, connection, msg):
|
||||
"""List all google assistant entities."""
|
||||
cloud = hass.data[DOMAIN]
|
||||
entities = google_helpers.async_get_entities(hass, cloud.client.google_config)
|
||||
gconf = await cloud.client.get_google_config()
|
||||
entities = google_helpers.async_get_entities(hass, gconf)
|
||||
|
||||
result = []
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"domain": "cloud",
|
||||
"name": "Cloud",
|
||||
"documentation": "https://www.home-assistant.io/integrations/cloud",
|
||||
"requirements": ["hass-nabucasa==0.29"],
|
||||
"requirements": ["hass-nabucasa==0.30"],
|
||||
"dependencies": ["http", "webhook"],
|
||||
"codeowners": ["@home-assistant/cloud"]
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
"""Preference management for cloud."""
|
||||
from ipaddress import ip_address
|
||||
from typing import Optional
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.auth.models import User
|
||||
from homeassistant.auth.const import GROUP_ID_ADMIN
|
||||
from homeassistant.util.logging import async_create_catching_coro
|
||||
|
||||
from .const import (
|
||||
@@ -19,6 +22,7 @@ from .const import (
|
||||
PREF_SHOULD_EXPOSE,
|
||||
PREF_ALEXA_ENTITY_CONFIGS,
|
||||
PREF_ALEXA_REPORT_STATE,
|
||||
PREF_USERNAME,
|
||||
DEFAULT_ALEXA_REPORT_STATE,
|
||||
PREF_GOOGLE_REPORT_STATE,
|
||||
PREF_GOOGLE_LOCAL_WEBHOOK_ID,
|
||||
@@ -47,16 +51,7 @@ class CloudPreferences:
|
||||
prefs = await self._store.async_load()
|
||||
|
||||
if prefs is None:
|
||||
prefs = {
|
||||
PREF_ENABLE_ALEXA: True,
|
||||
PREF_ENABLE_GOOGLE: True,
|
||||
PREF_ENABLE_REMOTE: False,
|
||||
PREF_GOOGLE_SECURE_DEVICES_PIN: None,
|
||||
PREF_GOOGLE_ENTITY_CONFIGS: {},
|
||||
PREF_ALEXA_ENTITY_CONFIGS: {},
|
||||
PREF_CLOUDHOOKS: {},
|
||||
PREF_CLOUD_USER: None,
|
||||
}
|
||||
prefs = self._empty_config("")
|
||||
|
||||
self._prefs = prefs
|
||||
|
||||
@@ -166,6 +161,27 @@ class CloudPreferences:
|
||||
updated_entities = {**entities, entity_id: updated_entity}
|
||||
await self.async_update(alexa_entity_configs=updated_entities)
|
||||
|
||||
async def async_set_username(self, username):
|
||||
"""Set the username that is logged in."""
|
||||
# Logging out.
|
||||
if username is None:
|
||||
user = await self._load_cloud_user()
|
||||
|
||||
if user is not None:
|
||||
await self._hass.auth.async_remove_user(user)
|
||||
await self._save_prefs({**self._prefs, PREF_CLOUD_USER: None})
|
||||
return
|
||||
|
||||
cur_username = self._prefs.get(PREF_USERNAME)
|
||||
|
||||
if cur_username == username:
|
||||
return
|
||||
|
||||
if cur_username is None:
|
||||
await self._save_prefs({**self._prefs, PREF_USERNAME: username})
|
||||
else:
|
||||
await self._save_prefs(self._empty_config(username))
|
||||
|
||||
def as_dict(self):
|
||||
"""Return dictionary version."""
|
||||
return {
|
||||
@@ -178,7 +194,6 @@ class CloudPreferences:
|
||||
PREF_ALEXA_REPORT_STATE: self.alexa_report_state,
|
||||
PREF_GOOGLE_REPORT_STATE: self.google_report_state,
|
||||
PREF_CLOUDHOOKS: self.cloudhooks,
|
||||
PREF_CLOUD_USER: self.cloud_user,
|
||||
}
|
||||
|
||||
@property
|
||||
@@ -239,10 +254,29 @@ class CloudPreferences:
|
||||
"""Return the published cloud webhooks."""
|
||||
return self._prefs.get(PREF_CLOUDHOOKS, {})
|
||||
|
||||
@property
|
||||
def cloud_user(self) -> str:
|
||||
async def get_cloud_user(self) -> str:
|
||||
"""Return ID from Home Assistant Cloud system user."""
|
||||
return self._prefs.get(PREF_CLOUD_USER)
|
||||
user = await self._load_cloud_user()
|
||||
|
||||
if user:
|
||||
return user.id
|
||||
|
||||
user = await self._hass.auth.async_create_system_user(
|
||||
"Home Assistant Cloud", [GROUP_ID_ADMIN]
|
||||
)
|
||||
await self.async_update(cloud_user=user.id)
|
||||
return user.id
|
||||
|
||||
async def _load_cloud_user(self) -> Optional[User]:
|
||||
"""Load cloud user if available."""
|
||||
user_id = self._prefs.get(PREF_CLOUD_USER)
|
||||
|
||||
if user_id is None:
|
||||
return None
|
||||
|
||||
# Fetch the user. It can happen that the user no longer exists if
|
||||
# an image was restored without restoring the cloud prefs.
|
||||
return await self._hass.auth.async_get_user(user_id)
|
||||
|
||||
@property
|
||||
def _has_local_trusted_network(self) -> bool:
|
||||
@@ -283,3 +317,19 @@ class CloudPreferences:
|
||||
|
||||
for listener in self._listeners:
|
||||
self._hass.async_create_task(async_create_catching_coro(listener(self)))
|
||||
|
||||
@callback
|
||||
def _empty_config(self, username):
|
||||
"""Return an empty config."""
|
||||
return {
|
||||
PREF_ENABLE_ALEXA: True,
|
||||
PREF_ENABLE_GOOGLE: True,
|
||||
PREF_ENABLE_REMOTE: False,
|
||||
PREF_GOOGLE_SECURE_DEVICES_PIN: None,
|
||||
PREF_GOOGLE_ENTITY_CONFIGS: {},
|
||||
PREF_ALEXA_ENTITY_CONFIGS: {},
|
||||
PREF_CLOUDHOOKS: {},
|
||||
PREF_CLOUD_USER: None,
|
||||
PREF_USERNAME: username,
|
||||
PREF_GOOGLE_LOCAL_WEBHOOK_ID: self._hass.components.webhook.async_generate_id(),
|
||||
}
|
||||
Reference in new issue
Block a user