Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion custom_components/wyzeapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from homeassistant.helpers.check_config import HomeAssistantConfig
from homeassistant.components import bluetooth
from wyzeapy import Wyzeapy
from wyzeapy.exceptions import AccessTokenError
from wyzeapy.exceptions import AccessTokenError, UnknownApiError
from wyzeapy.wyze_auth_lib import Token

from .const import (
Expand Down Expand Up @@ -47,6 +47,9 @@
] # Fixme: Re add scene
_LOGGER = logging.getLogger(__name__)

# Wyze API response code for an invalid or expired refresh token
REFRESH_TOKEN_ERROR_CODE = "2002"


# noinspection PyUnusedLocal
async def async_setup(
Expand Down Expand Up @@ -134,6 +137,18 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
)
_LOGGER.error(e)
raise ConfigEntryAuthFailed("Unable to login, please re-login.") from None
except UnknownApiError as e:
# wyzeapy surfaces a rejected refresh token as a generic API error.
# Without this, setup fails with no way to re-enter credentials.
if e.args and str(e.args[0]) == REFRESH_TOKEN_ERROR_CODE:
_LOGGER.error(
"Wyzeapi: Stored refresh token was rejected. Please re-login "
"through integration configuration"
)
raise ConfigEntryAuthFailed(
"Refresh token rejected, please re-login."
) from e
raise

hass.data[DOMAIN][config_entry.entry_id] = {
CONF_CLIENT: client,
Expand Down
58 changes: 58 additions & 0 deletions tests/test_setup_entry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Tests for login error handling in async_setup_entry."""

from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch

import pytest
from homeassistant.exceptions import ConfigEntryAuthFailed
from wyzeapy.exceptions import UnknownApiError

from custom_components import wyzeapi
from custom_components.wyzeapi.const import (
ACCESS_TOKEN,
API_KEY,
KEY_ID,
REFRESH_TIME,
REFRESH_TOKEN,
)


def make_entry():
return SimpleNamespace(
entry_id="entry-id",
data={
"username": "user@example.com",
"password": "hunter2",
KEY_ID: "key-id",
API_KEY: "api-key",
ACCESS_TOKEN: "access",
REFRESH_TOKEN: "refresh",
REFRESH_TIME: "1.0",
},
options={},
)


async def setup_with_login_error(error):
client = SimpleNamespace(
login=AsyncMock(side_effect=error),
register_for_token_callback=Mock(),
)
hass = SimpleNamespace(data={})
with (
patch.object(wyzeapi.Wyzeapy, "create", AsyncMock(return_value=client)),
patch.object(wyzeapi, "TokenManager"),
):
return await wyzeapi.async_setup_entry(hass, make_entry())


@pytest.mark.asyncio
async def test_rejected_refresh_token_triggers_reauth() -> None:
with pytest.raises(ConfigEntryAuthFailed):
await setup_with_login_error(UnknownApiError("2002", "refresh token is error"))


@pytest.mark.asyncio
async def test_other_unknown_api_errors_are_not_treated_as_auth_failures() -> None:
with pytest.raises(UnknownApiError):
await setup_with_login_error(UnknownApiError("5000", "server error"))