Skip to content

Commit

Permalink
fix: retrieve entry during async_step_reauth for relogin
Browse files Browse the repository at this point in the history
  • Loading branch information
duhow committed Feb 8, 2024
1 parent 89ccc2b commit 0cf97ce
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 8 deletions.
3 changes: 2 additions & 1 deletion custom_components/aigues_barcelona/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
if entry.entry_id in hass.data[DOMAIN].keys():
hass.data[DOMAIN].pop(entry.entry_id)
if not hass.data[DOMAIN]:
del hass.data[DOMAIN]

Expand Down
22 changes: 18 additions & 4 deletions custom_components/aigues_barcelona/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from homeassistant.exceptions import HomeAssistantError

from .api import AiguesApiClient
from .const import API_ERROR_TOKEN_REVOKED
from .const import CONF_CONTRACT
from .const import DOMAIN

Expand Down Expand Up @@ -87,7 +88,7 @@ async def validate_credentials(

if (
isinstance(api.last_response, str)
and api.last_response == "JWT Token Revoked"
and api.last_response == API_ERROR_TOKEN_REVOKED
):
raise TokenExpired

Expand All @@ -112,26 +113,39 @@ async def async_step_reauth(self, entry) -> FlowResult:
if hasattr(entry, "data"):
self.stored_input = entry.data
else:
# FIXME: for DataUpdateCoordinator, entry is not valid,
# as it contains only sensor data. Missing entry_id.
# Reauth when restarting works.
self.stored_input = entry

# WHAT: for DataUpdateCoordinator, entry is not valid,
# as it contains only sensor data. Missing entry_id.
# This recovers the entry_id data.
if entry := self.hass.config_entries.async_get_entry(
self.context["entry_id"]
):
self.entry = entry
return await self.async_step_reauth_confirm(None)

async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Return to user step with stored input (previous user creds) and the
current provided token."""

if not user_input:
return self.async_show_form(
step_id="reauth_confirm", data_schema=TOKEN_SCHEMA
)

errors = {}
_LOGGER.debug(
f"Current values on reauth_confirm: {self.entry} --> {user_input}"
)
user_input = {**self.stored_input, **user_input}
try:
info = await validate_credentials(self.hass, user_input)
_LOGGER.debug(f"Result is {info}")
if not info: # invalid oauth token
raise InvalidAuth

contracts = info[CONF_CONTRACT]
if contracts != self.stored_input.get(CONF_CONTRACT):
_LOGGER.error("Reauth failed, contract does not match stored one")
Expand Down
2 changes: 2 additions & 0 deletions custom_components/aigues_barcelona/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@

API_HOST = "api.aiguesdebarcelona.cat"
API_COOKIE_TOKEN = "ofexTokenJwt"

API_ERROR_TOKEN_REVOKED = "JWT Token Revoked"
10 changes: 7 additions & 3 deletions custom_components/aigues_barcelona/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .api import AiguesApiClient
from .const import API_ERROR_TOKEN_REVOKED
from .const import ATTR_LAST_MEASURE
from .const import CONF_CONTRACT
from .const import CONF_VALUE
Expand Down Expand Up @@ -104,7 +105,7 @@ def __init__(
)

async def _async_update_data(self):
_LOGGER.info("Updating coordinator data")
_LOGGER.info(f"Updating coordinator data for {self.contract}")
TODAY = datetime.now()
LAST_WEEK = TODAY - timedelta(days=7)
TOMORROW = TODAY + timedelta(days=1)
Expand All @@ -120,6 +121,7 @@ async def _async_update_data(self):
_LOGGER.warn("Skipping request update data - too early")
return

consumptions = None
try:
if self._api.is_token_expired():
raise ConfigEntryAuthFailed
Expand All @@ -131,8 +133,10 @@ async def _async_update_data(self):
except ConfigEntryAuthFailed as exp:
_LOGGER.error("Token has expired, cannot check consumptions.")
raise ConfigEntryAuthFailed from exp
except Exception as msg:
_LOGGER.error("error while getting data: %s", msg)
except Exception as exp:
_LOGGER.error("error while getting data: %s", exp)
if API_ERROR_TOKEN_REVOKED in str(exp):
raise ConfigEntryAuthFailed from exp

if not consumptions:
_LOGGER.error("No consumptions available")
Expand Down

0 comments on commit 0cf97ce

Please sign in to comment.