diff --git a/homeassistant/components/mobile_app/__init__.py b/homeassistant/components/mobile_app/__init__.py index 80893e0cbfa..9fadca31b50 100644 --- a/homeassistant/components/mobile_app/__init__.py +++ b/homeassistant/components/mobile_app/__init__.py @@ -4,6 +4,7 @@ from contextlib import suppress from functools import partial from typing import Any +from homeassistant.auth import EVENT_USER_REMOVED from homeassistant.components import cloud, intent, notify as hass_notify from homeassistant.components.webhook import ( async_register as webhook_register, @@ -11,7 +12,7 @@ from homeassistant.components.webhook import ( ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_DEVICE_ID, CONF_WEBHOOK_ID, Platform -from homeassistant.core import HomeAssistant +from homeassistant.core import Event, HomeAssistant from homeassistant.helpers import ( config_validation as cv, device_registry as dr, @@ -36,6 +37,7 @@ from .const import ( ATTR_MODEL, ATTR_OS_VERSION, CONF_CLOUDHOOK_URL, + CONF_USER_ID, DATA_CONFIG_ENTRIES, DATA_DELETED_IDS, DATA_DEVICES, @@ -90,6 +92,15 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: websocket_api.async_setup_commands(hass) + async def _handle_user_removed(event: Event) -> None: + """Remove an entry when the user is removed.""" + user_id = event.data["user_id"] + for entry in hass.config_entries.async_entries(DOMAIN): + if entry.data[CONF_USER_ID] == user_id: + await hass.config_entries.async_remove(entry.entry_id) + + hass.bus.async_listen(EVENT_USER_REMOVED, _handle_user_removed) + return True diff --git a/tests/components/mobile_app/test_init.py b/tests/components/mobile_app/test_init.py index e1c7ed27cf9..a4edbea6ecf 100644 --- a/tests/components/mobile_app/test_init.py +++ b/tests/components/mobile_app/test_init.py @@ -226,3 +226,37 @@ async def test_delete_cloud_hook( await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert (CONF_CLOUDHOOK_URL in config_entry.data) == should_cloudhook_exist + + +async def test_remove_entry_on_user_remove( + hass: HomeAssistant, + hass_admin_user: MockUser, +) -> None: + """Test removing related config entry, when a user gets removed from HA.""" + + config_entry = MockConfigEntry( + data={ + **REGISTER_CLEARTEXT, + CONF_WEBHOOK_ID: "test-webhook-id", + ATTR_DEVICE_NAME: "Test", + ATTR_DEVICE_ID: "Test", + CONF_USER_ID: hass_admin_user.id, + CONF_CLOUDHOOK_URL: "https://hook-url-already-exists", + }, + domain=DOMAIN, + title="Test", + ) + config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.LOADED + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + + await hass.auth.async_remove_user(hass_admin_user) + await hass.async_block_till_done() + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 0