Skip to content

Commit

Permalink
Add reauth flow to Habitica integration (home-assistant#131676)
Browse files Browse the repository at this point in the history
* Add reauth flow to Habitica integration

* tests, invalid_credentials string

* test only api_key

* section consts

* test config entry

* test reauth is triggered

* set reauthentication-flow to done

* use consts in tests

* reauth_entry

* changes

* fix import

* changes
  • Loading branch information
tr4nt0r authored Dec 29, 2024
1 parent 53e69af commit 9804e8a
Show file tree
Hide file tree
Showing 7 changed files with 385 additions and 64 deletions.
229 changes: 178 additions & 51 deletions homeassistant/components/habitica/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@

from __future__ import annotations

from collections.abc import Mapping
import logging
from typing import TYPE_CHECKING, Any

from aiohttp import ClientError
from habiticalib import Habitica, HabiticaException, NotAuthorizedError
from habiticalib import (
Habitica,
HabiticaException,
LoginData,
NotAuthorizedError,
UserData,
)
import voluptuous as vol

from homeassistant import data_entry_flow
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
CONF_API_KEY,
Expand All @@ -25,12 +33,15 @@
TextSelectorType,
)

from . import HabiticaConfigEntry
from .const import (
CONF_API_USER,
DEFAULT_URL,
DOMAIN,
FORGOT_PASSWORD_URL,
HABITICANS_URL,
SECTION_REAUTH_API_KEY,
SECTION_REAUTH_LOGIN,
SIGN_UP_URL,
SITE_DATA_URL,
X_CLIENT,
Expand Down Expand Up @@ -62,14 +73,44 @@
}
)

STEP_REAUTH_DATA_SCHEMA = vol.Schema(
{
vol.Required(SECTION_REAUTH_LOGIN): data_entry_flow.section(
vol.Schema(
{
vol.Optional(CONF_USERNAME): TextSelector(
TextSelectorConfig(
type=TextSelectorType.EMAIL,
autocomplete="email",
)
),
vol.Optional(CONF_PASSWORD): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
)
),
},
),
{"collapsed": False},
),
vol.Required(SECTION_REAUTH_API_KEY): data_entry_flow.section(
vol.Schema(
{
vol.Optional(CONF_API_KEY): str,
},
),
{"collapsed": True},
),
}
)

_LOGGER = logging.getLogger(__name__)


class HabiticaConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for habitica."""

VERSION = 1

async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
Expand All @@ -94,33 +135,20 @@ async def async_step_login(
"""
errors: dict[str, str] = {}
if user_input is not None:
session = async_get_clientsession(self.hass)
api = Habitica(session=session, x_client=X_CLIENT)
try:
login = await api.login(
username=user_input[CONF_USERNAME],
password=user_input[CONF_PASSWORD],
)
user = await api.get_user(user_fields="profile")

except NotAuthorizedError:
errors["base"] = "invalid_auth"
except (HabiticaException, ClientError):
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(str(login.data.id))
errors, login, user = await self.validate_login(
{**user_input, CONF_URL: DEFAULT_URL}
)
if not errors and login is not None and user is not None:
await self.async_set_unique_id(str(login.id))
self._abort_if_unique_id_configured()
if TYPE_CHECKING:
assert user.data.profile.name
assert user.profile.name
return self.async_create_entry(
title=user.data.profile.name,
title=user.profile.name,
data={
CONF_API_USER: str(login.data.id),
CONF_API_KEY: login.data.apiToken,
CONF_NAME: user.data.profile.name, # needed for api_call action
CONF_API_USER: str(login.id),
CONF_API_KEY: login.apiToken,
CONF_NAME: user.profile.name, # needed for api_call action
CONF_URL: DEFAULT_URL,
CONF_VERIFY_SSL: True,
},
Expand All @@ -145,36 +173,18 @@ async def async_step_advanced(
"""
errors: dict[str, str] = {}
if user_input is not None:
session = async_get_clientsession(
self.hass, verify_ssl=user_input[CONF_VERIFY_SSL]
)
try:
api = Habitica(
session=session,
x_client=X_CLIENT,
api_user=user_input[CONF_API_USER],
api_key=user_input[CONF_API_KEY],
url=user_input.get(CONF_URL, DEFAULT_URL),
)
user = await api.get_user(user_fields="profile")
except NotAuthorizedError:
errors["base"] = "invalid_auth"
except (HabiticaException, ClientError):
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(user_input[CONF_API_USER])
self._abort_if_unique_id_configured()
await self.async_set_unique_id(user_input[CONF_API_USER])
self._abort_if_unique_id_configured()
errors, user = await self.validate_api_key(user_input)
if not errors and user is not None:
if TYPE_CHECKING:
assert user.data.profile.name
assert user.profile.name
return self.async_create_entry(
title=user.data.profile.name,
title=user.profile.name,
data={
**user_input,
CONF_URL: user_input.get(CONF_URL, DEFAULT_URL),
CONF_NAME: user.data.profile.name, # needed for api_call action
CONF_NAME: user.profile.name, # needed for api_call action
},
)

Expand All @@ -189,3 +199,120 @@ async def async_step_advanced(
"default_url": DEFAULT_URL,
},
)

async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()

async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Dialog that informs the user that reauth is required."""
errors: dict[str, str] = {}
reauth_entry: HabiticaConfigEntry = self._get_reauth_entry()

if user_input is not None:
if user_input[SECTION_REAUTH_LOGIN].get(CONF_USERNAME) and user_input[
SECTION_REAUTH_LOGIN
].get(CONF_PASSWORD):
errors, login, _ = await self.validate_login(
{**reauth_entry.data, **user_input[SECTION_REAUTH_LOGIN]}
)
if not errors and login is not None:
await self.async_set_unique_id(str(login.id))
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
reauth_entry,
data_updates={CONF_API_KEY: login.apiToken},
)
elif user_input[SECTION_REAUTH_API_KEY].get(CONF_API_KEY):
errors, user = await self.validate_api_key(
{
**reauth_entry.data,
**user_input[SECTION_REAUTH_API_KEY],
}
)
if not errors and user is not None:
return self.async_update_reload_and_abort(
reauth_entry, data_updates=user_input[SECTION_REAUTH_API_KEY]
)
else:
errors["base"] = "invalid_credentials"

return self.async_show_form(
step_id="reauth_confirm",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_REAUTH_DATA_SCHEMA,
suggested_values={
CONF_USERNAME: (
user_input[SECTION_REAUTH_LOGIN].get(CONF_USERNAME)
if user_input
else None,
)
},
),
description_placeholders={
CONF_NAME: reauth_entry.title,
"habiticans": HABITICANS_URL,
},
errors=errors,
)

async def validate_login(
self, user_input: Mapping[str, Any]
) -> tuple[dict[str, str], LoginData | None, UserData | None]:
"""Validate login with login credentials."""
errors: dict[str, str] = {}
session = async_get_clientsession(
self.hass, verify_ssl=user_input.get(CONF_VERIFY_SSL, True)
)
api = Habitica(session=session, x_client=X_CLIENT)
try:
login = await api.login(
username=user_input[CONF_USERNAME],
password=user_input[CONF_PASSWORD],
)
user = await api.get_user(user_fields="profile")

except NotAuthorizedError:
errors["base"] = "invalid_auth"
except (HabiticaException, ClientError):
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return errors, login.data, user.data

return errors, None, None

async def validate_api_key(
self, user_input: Mapping[str, Any]
) -> tuple[dict[str, str], UserData | None]:
"""Validate authentication with api key."""
errors: dict[str, str] = {}
session = async_get_clientsession(
self.hass, verify_ssl=user_input.get(CONF_VERIFY_SSL, True)
)
api = Habitica(
session=session,
x_client=X_CLIENT,
api_user=user_input[CONF_API_USER],
api_key=user_input[CONF_API_KEY],
url=user_input.get(CONF_URL, DEFAULT_URL),
)
try:
user = await api.get_user(user_fields="profile")
except NotAuthorizedError:
errors["base"] = "invalid_auth"
except (HabiticaException, ClientError):
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return errors, user.data

return errors, None
3 changes: 3 additions & 0 deletions homeassistant/components/habitica/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,6 @@

DEVELOPER_ID = "4c4ca53f-c059-4ffa-966e-9d29dd405daf"
X_CLIENT = f"{DEVELOPER_ID} - {APPLICATION_NAME} {__version__}"

SECTION_REAUTH_LOGIN = "reauth_login"
SECTION_REAUTH_API_KEY = "reauth_api_key"
11 changes: 7 additions & 4 deletions homeassistant/components/habitica/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
HomeAssistantError,
)
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

Expand Down Expand Up @@ -71,10 +75,9 @@ async def _async_setup(self) -> None:
await self.habitica.get_content(user.data.preferences.language)
).data
except NotAuthorizedError as e:
raise ConfigEntryNotReady(
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
translation_placeholders={"account": self.config_entry.title},
translation_key="authentication_failed",
) from e
except TooManyRequestsError as e:
raise ConfigEntryNotReady(
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/habitica/quality_scale.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: todo
reauthentication-flow: todo
reauthentication-flow: done
test-coverage: done

# Gold
Expand Down
Loading

0 comments on commit 9804e8a

Please sign in to comment.