diff --git a/homeassistant/components/plex/__init__.py b/homeassistant/components/plex/__init__.py index 559f4440aef..59ae14b8ca9 100644 --- a/homeassistant/components/plex/__init__.py +++ b/homeassistant/components/plex/__init__.py @@ -35,6 +35,7 @@ from .const import ( CONF_SERVER_IDENTIFIER, DISPATCHERS, DOMAIN, + INVALID_TOKEN_MESSAGE, PLATFORMS, PLATFORMS_COMPLETED, PLEX_SERVER_CONFIG, @@ -153,6 +154,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: plexapi.exceptions.BadRequest, plexapi.exceptions.NotFound, ) as error: + if INVALID_TOKEN_MESSAGE in str(error): + raise ConfigEntryAuthFailed( + "Token not accepted, please reauthenticate Plex server" + f" '{entry.data[CONF_SERVER]}'" + ) from error _LOGGER.error( "Login to %s failed, verify token and SSL settings: [%s]", entry.data[CONF_SERVER], diff --git a/homeassistant/components/plex/const.py b/homeassistant/components/plex/const.py index 3f761c9748a..7936cb6e6c3 100644 --- a/homeassistant/components/plex/const.py +++ b/homeassistant/components/plex/const.py @@ -57,3 +57,5 @@ SERVICE_REFRESH_LIBRARY = "refresh_library" SERVICE_SCAN_CLIENTS = "scan_for_clients" PLEX_URI_SCHEME = "plex://" + +INVALID_TOKEN_MESSAGE = "Invalid token" diff --git a/tests/components/plex/test_init.py b/tests/components/plex/test_init.py index 08b8635829f..bc43a1e0d89 100644 --- a/tests/components/plex/test_init.py +++ b/tests/components/plex/test_init.py @@ -360,3 +360,19 @@ async def test_trigger_reauth( flows = hass.config_entries.flow.async_progress() assert len(flows) == 1 assert flows[0]["context"]["source"] == SOURCE_REAUTH + + +async def test_setup_with_deauthorized_token( + hass: HomeAssistant, entry, setup_plex_server +) -> None: + """Test setup with a deauthorized token.""" + with patch( + "plexapi.server.PlexServer", + side_effect=plexapi.exceptions.BadRequest(const.INVALID_TOKEN_MESSAGE), + ): + entry.add_to_hass(hass) + assert not await hass.config_entries.async_setup(entry.entry_id) + + flows = hass.config_entries.flow.async_progress() + assert len(flows) == 1 + assert flows[0]["context"]["source"] == SOURCE_REAUTH