diff --git a/homeassistant/components/nam/__init__.py b/homeassistant/components/nam/__init__.py index 6b0f9db3757..021b46e2f38 100644 --- a/homeassistant/components/nam/__init__.py +++ b/homeassistant/components/nam/__init__.py @@ -52,11 +52,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options = ConnectionOptions(host=host, username=username, password=password) try: nam = await NettigoAirMonitor.create(websession, options) - except AuthFailed as err: - raise ConfigEntryAuthFailed from err except (ApiError, ClientError, ClientConnectorError, asyncio.TimeoutError) as err: raise ConfigEntryNotReady from err + try: + await nam.async_check_credentials() + except AuthFailed as err: + raise ConfigEntryAuthFailed from err + coordinator = NAMDataUpdateCoordinator(hass, nam, entry.unique_id) await coordinator.async_config_entry_first_refresh() diff --git a/homeassistant/components/nam/config_flow.py b/homeassistant/components/nam/config_flow.py index df41eb7c5f1..451148c22fe 100644 --- a/homeassistant/components/nam/config_flow.py +++ b/homeassistant/components/nam/config_flow.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio from collections.abc import Mapping +from dataclasses import dataclass import logging from typing import Any @@ -27,6 +28,15 @@ from homeassistant.helpers.device_registry import format_mac from .const import DOMAIN + +@dataclass +class NamConfig: + """NAM device configuration class.""" + + mac_address: str + auth_enabled: bool + + _LOGGER = logging.getLogger(__name__) AUTH_SCHEMA = vol.Schema( @@ -34,15 +44,31 @@ AUTH_SCHEMA = vol.Schema( ) -async def async_get_mac(hass: HomeAssistant, host: str, data: dict[str, Any]) -> str: - """Get device MAC address.""" +async def async_get_config(hass: HomeAssistant, host: str) -> NamConfig: + """Get device MAC address and auth_enabled property.""" websession = async_get_clientsession(hass) - options = ConnectionOptions(host, data.get(CONF_USERNAME), data.get(CONF_PASSWORD)) + options = ConnectionOptions(host) nam = await NettigoAirMonitor.create(websession, options) async with async_timeout.timeout(10): - return await nam.async_get_mac_address() + mac = await nam.async_get_mac_address() + + return NamConfig(mac, nam.auth_enabled) + + +async def async_check_credentials( + hass: HomeAssistant, host: str, data: dict[str, Any] +) -> None: + """Check if credentials are valid.""" + websession = async_get_clientsession(hass) + + options = ConnectionOptions(host, data.get(CONF_USERNAME), data.get(CONF_PASSWORD)) + + nam = await NettigoAirMonitor.create(websession, options) + + async with async_timeout.timeout(10): + await nam.async_check_credentials() class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): @@ -54,6 +80,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Initialize flow.""" self.host: str self.entry: config_entries.ConfigEntry + self._config: NamConfig async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -65,9 +92,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): self.host = user_input[CONF_HOST] try: - mac = await async_get_mac(self.hass, self.host, {}) - except AuthFailed: - return await self.async_step_credentials() + config = await async_get_config(self.hass, self.host) except (ApiError, ClientConnectorError, asyncio.TimeoutError): errors["base"] = "cannot_connect" except CannotGetMac: @@ -76,9 +101,12 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: - await self.async_set_unique_id(format_mac(mac)) + await self.async_set_unique_id(format_mac(config.mac_address)) self._abort_if_unique_id_configured({CONF_HOST: self.host}) + if config.auth_enabled is True: + return await self.async_step_credentials() + return self.async_create_entry( title=self.host, data=user_input, @@ -98,19 +126,15 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): if user_input is not None: try: - mac = await async_get_mac(self.hass, self.host, user_input) + await async_check_credentials(self.hass, self.host, user_input) except AuthFailed: errors["base"] = "invalid_auth" except (ApiError, ClientConnectorError, asyncio.TimeoutError): errors["base"] = "cannot_connect" - except CannotGetMac: - return self.async_abort(reason="device_unsupported") except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: - await self.async_set_unique_id(format_mac(mac)) - self._abort_if_unique_id_configured({CONF_HOST: self.host}) return self.async_create_entry( title=self.host, @@ -132,15 +156,13 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): self._async_abort_entries_match({CONF_HOST: self.host}) try: - mac = await async_get_mac(self.hass, self.host, {}) - except AuthFailed: - return await self.async_step_credentials() + self._config = await async_get_config(self.hass, self.host) except (ApiError, ClientConnectorError, asyncio.TimeoutError): return self.async_abort(reason="cannot_connect") except CannotGetMac: return self.async_abort(reason="device_unsupported") - await self.async_set_unique_id(format_mac(mac)) + await self.async_set_unique_id(format_mac(self._config.mac_address)) self._abort_if_unique_id_configured({CONF_HOST: self.host}) return await self.async_step_confirm_discovery() @@ -157,6 +179,9 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): data={CONF_HOST: self.host}, ) + if self._config.auth_enabled is True: + return await self.async_step_credentials() + self._set_confirm_only() return self.async_show_form( @@ -181,7 +206,7 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): if user_input is not None: try: - await async_get_mac(self.hass, self.host, user_input) + await async_check_credentials(self.hass, self.host, user_input) except (ApiError, AuthFailed, ClientConnectorError, asyncio.TimeoutError): return self.async_abort(reason="reauth_unsuccessful") else: diff --git a/homeassistant/components/nam/manifest.json b/homeassistant/components/nam/manifest.json index a842af46f84..88048b59162 100644 --- a/homeassistant/components/nam/manifest.json +++ b/homeassistant/components/nam/manifest.json @@ -3,7 +3,7 @@ "name": "Nettigo Air Monitor", "documentation": "https://www.home-assistant.io/integrations/nam", "codeowners": ["@bieniu"], - "requirements": ["nettigo-air-monitor==1.2.4"], + "requirements": ["nettigo-air-monitor==1.3.0"], "zeroconf": [ { "type": "_http._tcp.local.", diff --git a/requirements_all.txt b/requirements_all.txt index 70a29067a7b..8a804d3ae90 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1077,7 +1077,7 @@ netdisco==3.0.0 netmap==0.7.0.2 # homeassistant.components.nam -nettigo-air-monitor==1.2.4 +nettigo-air-monitor==1.3.0 # homeassistant.components.neurio_energy neurio==0.3.1 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 850a379eaf6..48b20ee778f 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -745,7 +745,7 @@ netdisco==3.0.0 netmap==0.7.0.2 # homeassistant.components.nam -nettigo-air-monitor==1.2.4 +nettigo-air-monitor==1.3.0 # homeassistant.components.nexia nexia==1.0.1 diff --git a/tests/components/nam/test_config_flow.py b/tests/components/nam/test_config_flow.py index 9479e29cdea..67274cf1c78 100644 --- a/tests/components/nam/test_config_flow.py +++ b/tests/components/nam/test_config_flow.py @@ -23,6 +23,8 @@ DISCOVERY_INFO = zeroconf.ZeroconfServiceInfo( ) VALID_CONFIG = {"host": "10.10.2.3"} VALID_AUTH = {"username": "fake_username", "password": "fake_password"} +DEVICE_CONFIG = {"www_basicauth_enabled": False} +DEVICE_CONFIG_AUTH = {"www_basicauth_enabled": True} async def test_form_create_entry_without_auth(hass): @@ -34,7 +36,10 @@ async def test_form_create_entry_without_auth(hass): assert result["step_id"] == SOURCE_USER assert result["errors"] == {} - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + with patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ), patch( @@ -62,24 +67,22 @@ async def test_form_create_entry_with_auth(hass): assert result["errors"] == {} with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", - side_effect=AuthFailed("Auth Error"), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - VALID_CONFIG, - ) - await hass.async_block_till_done() - - assert result["type"] == data_entry_flow.RESULT_TYPE_FORM - assert result["step_id"] == "credentials" - - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG_AUTH, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ), patch( "homeassistant.components.nam.async_setup_entry", return_value=True ) as mock_setup_entry: + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + VALID_CONFIG, + ) + + assert result["type"] == data_entry_flow.RESULT_TYPE_FORM + assert result["step_id"] == "credentials" + result = await hass.config_entries.flow.async_configure( result["flow_id"], VALID_AUTH, @@ -104,7 +107,10 @@ async def test_reauth_successful(hass): ) entry.add_to_hass(hass) - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + with patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG_AUTH, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ): @@ -137,7 +143,7 @@ async def test_reauth_unsuccessful(hass): entry.add_to_hass(hass) with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", side_effect=ApiError("API Error"), ): result = await hass.config_entries.flow.async_init( @@ -171,8 +177,11 @@ async def test_form_with_auth_errors(hass, error): """Test we handle errors when auth is required.""" exc, base_error = error with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", side_effect=AuthFailed("Auth Error"), + ), patch( + "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", + return_value="aa:bb:cc:dd:ee:ff", ): result = await hass.config_entries.flow.async_init( DOMAIN, @@ -221,26 +230,13 @@ async def test_form_errors(hass, error): async def test_form_abort(hass): - """Test we handle abort after error.""" - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( - "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", - side_effect=CannotGetMac("Cannot get MAC address from device"), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, - context={"source": SOURCE_USER}, - data=VALID_CONFIG, - ) - - assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT - assert result["reason"] == "device_unsupported" - - -async def test_form_with_auth_abort(hass): """Test we handle abort after error.""" with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", - side_effect=AuthFailed("Auth Error"), + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG, + ), patch( + "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", + side_effect=CannotGetMac("Cannot get MAC address from device"), ): result = await hass.config_entries.flow.async_init( DOMAIN, @@ -248,18 +244,6 @@ async def test_form_with_auth_abort(hass): data=VALID_CONFIG, ) - assert result["type"] == data_entry_flow.RESULT_TYPE_FORM - assert result["step_id"] == "credentials" - - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( - "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", - side_effect=CannotGetMac("Cannot get MAC address from device"), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - VALID_AUTH, - ) - assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "device_unsupported" @@ -275,7 +259,10 @@ async def test_form_already_configured(hass): DOMAIN, context={"source": SOURCE_USER} ) - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + with patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ): @@ -293,7 +280,10 @@ async def test_form_already_configured(hass): async def test_zeroconf(hass): """Test we get the form.""" - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + with patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ): @@ -332,8 +322,11 @@ async def test_zeroconf(hass): async def test_zeroconf_with_auth(hass): """Test that the zeroconf step with auth works.""" with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", side_effect=AuthFailed("Auth Error"), + ), patch( + "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", + return_value="aa:bb:cc:dd:ee:ff", ): result = await hass.config_entries.flow.async_init( DOMAIN, @@ -351,7 +344,10 @@ async def test_zeroconf_with_auth(hass): assert result["errors"] == {} assert context["title_placeholders"]["host"] == "10.10.2.3" - with patch("homeassistant.components.nam.NettigoAirMonitor.initialize"), patch( + with patch( + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", + return_value=DEVICE_CONFIG_AUTH, + ), patch( "homeassistant.components.nam.NettigoAirMonitor.async_get_mac_address", return_value="aa:bb:cc:dd:ee:ff", ), patch( diff --git a/tests/components/nam/test_init.py b/tests/components/nam/test_init.py index 3223a394f68..9eac901d693 100644 --- a/tests/components/nam/test_init.py +++ b/tests/components/nam/test_init.py @@ -51,7 +51,7 @@ async def test_config_auth_failed(hass): ) with patch( - "homeassistant.components.nam.NettigoAirMonitor.initialize", + "homeassistant.components.nam.NettigoAirMonitor.async_check_credentials", side_effect=AuthFailed("Authorization has failed"), ): entry.add_to_hass(hass)