1
0
mirror of https://github.com/home-assistant/core.git synced 2026-04-17 23:53:49 +01:00

Add reauth to Mastodon (#163148)

This commit is contained in:
Andrew Jackson
2026-02-16 15:29:20 +00:00
committed by GitHub
parent 7ab4f2f431
commit dfd61f85c2
7 changed files with 203 additions and 26 deletions

View File

@@ -9,6 +9,7 @@ from mastodon.Mastodon import (
Mastodon,
MastodonError,
MastodonNotFoundError,
MastodonUnauthorizedError,
)
from homeassistant.const import (
@@ -18,7 +19,7 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify
@@ -48,6 +49,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: MastodonConfigEntry) ->
entry,
)
except MastodonUnauthorizedError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_failed",
) from error
except MastodonError as ex:
raise ConfigEntryNotReady("Failed to connect") from ex

View File

@@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from mastodon.Mastodon import (
@@ -43,6 +44,15 @@ STEP_USER_DATA_SCHEMA = vol.Schema(
): TextSelector(TextSelectorConfig(type=TextSelectorType.PASSWORD)),
}
)
REAUTH_SCHEMA = vol.Schema(
{
vol.Required(
CONF_ACCESS_TOKEN,
): TextSelector(TextSelectorConfig(type=TextSelectorType.PASSWORD)),
}
)
EXAMPLE_URL = "https://mastodon.social"
def base_url_from_url(url: str) -> str:
@@ -50,18 +60,26 @@ def base_url_from_url(url: str) -> str:
return str(URL(url).origin())
def remove_email_link(account_name: str) -> str:
"""Remove email link from account name."""
# Replaces the @ with a HTML entity to prevent mailto links.
return account_name.replace("@", "@")
class MastodonConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""
VERSION = 1
MINOR_VERSION = 2
base_url: str
client_id: str
client_secret: str
access_token: str
def check_connection(
self,
base_url: str,
client_id: str,
client_secret: str,
access_token: str,
) -> tuple[
InstanceV2 | Instance | None,
Account | None,
@@ -70,10 +88,10 @@ class MastodonConfigFlow(ConfigFlow, domain=DOMAIN):
"""Check connection to the Mastodon instance."""
try:
client = create_mastodon_client(
base_url,
client_id,
client_secret,
access_token,
self.base_url,
self.client_id,
self.client_secret,
self.access_token,
)
try:
instance = client.instance_v2()
@@ -117,12 +135,13 @@ class MastodonConfigFlow(ConfigFlow, domain=DOMAIN):
if user_input:
user_input[CONF_BASE_URL] = base_url_from_url(user_input[CONF_BASE_URL])
self.base_url = user_input[CONF_BASE_URL]
self.client_id = user_input[CONF_CLIENT_ID]
self.client_secret = user_input[CONF_CLIENT_SECRET]
self.access_token = user_input[CONF_ACCESS_TOKEN]
instance, account, errors = await self.hass.async_add_executor_job(
self.check_connection,
user_input[CONF_BASE_URL],
user_input[CONF_CLIENT_ID],
user_input[CONF_CLIENT_SECRET],
user_input[CONF_ACCESS_TOKEN],
self.check_connection
)
if not errors:
@@ -137,5 +156,43 @@ class MastodonConfigFlow(ConfigFlow, domain=DOMAIN):
return self.show_user_form(
user_input,
errors,
description_placeholders={"example_url": "https://mastodon.social"},
description_placeholders={"example_url": EXAMPLE_URL},
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
self.base_url = entry_data[CONF_BASE_URL]
self.client_id = entry_data[CONF_CLIENT_ID]
self.client_secret = entry_data[CONF_CLIENT_SECRET]
self.access_token = entry_data[CONF_ACCESS_TOKEN]
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauth dialog."""
errors: dict[str, str] = {}
if user_input:
self.access_token = user_input[CONF_ACCESS_TOKEN]
instance, account, errors = await self.hass.async_add_executor_job(
self.check_connection
)
if not errors:
name = construct_mastodon_username(instance, account)
await self.async_set_unique_id(slugify(name))
self._abort_if_unique_id_mismatch(reason="wrong_account")
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={CONF_ACCESS_TOKEN: user_input[CONF_ACCESS_TOKEN]},
)
account_name = self._get_reauth_entry().title
return self.async_show_form(
step_id="reauth_confirm",
data_schema=REAUTH_SCHEMA,
errors=errors,
description_placeholders={
"account_name": remove_email_link(account_name),
},
)

View File

@@ -7,6 +7,6 @@
"integration_type": "service",
"iot_class": "cloud_polling",
"loggers": ["mastodon"],
"quality_scale": "bronze",
"quality_scale": "silver",
"requirements": ["Mastodon.py==2.1.2"]
}

View File

@@ -34,10 +34,7 @@ rules:
integration-owner: done
log-when-unavailable: done
parallel-updates: done
reauthentication-flow:
status: todo
comment: |
Waiting to move to oAuth.
reauthentication-flow: done
test-coverage: done
# Gold
devices: done

View File

@@ -1,7 +1,10 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
"already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"wrong_account": "You have to use the same account that was used to configure the integration."
},
"error": {
"network_error": "The Mastodon instance was not found.",
@@ -9,6 +12,15 @@
"unknown": "Unknown error occurred when connecting to the Mastodon instance."
},
"step": {
"reauth_confirm": {
"data": {
"access_token": "[%key:common::config_flow::data::access_token%]"
},
"data_description": {
"access_token": "[%key:component::mastodon::config::step::user::data_description::access_token%]"
},
"description": "Please reauthenticate {account_name} with Mastodon."
},
"user": {
"data": {
"access_token": "[%key:common::config_flow::data::access_token%]",
@@ -69,6 +81,9 @@
}
},
"exceptions": {
"auth_failed": {
"message": "Authentication failed, please reauthenticate with Mastodon."
},
"idempotency_key_too_short": {
"message": "Idempotency key must be at least 4 characters long."
},

View File

@@ -1,6 +1,6 @@
"""Tests for the Mastodon config flow."""
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, patch
from mastodon.Mastodon import (
MastodonNetworkError,
@@ -204,3 +204,95 @@ async def test_duplicate(
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "token2"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_ACCESS_TOKEN] == "token2"
async def test_reauth_flow_wrong_account(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow with wrong account."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
with patch(
"homeassistant.components.mastodon.config_flow.construct_mastodon_username",
return_value="BAD_USERNAME",
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "token2"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_account"
@pytest.mark.parametrize(
("exception", "error"),
[
(MastodonNetworkError, "network_error"),
(MastodonUnauthorizedError, "unauthorized_error"),
(Exception, "unknown"),
],
)
async def test_reauth_flow_exceptions(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
error: str,
) -> None:
"""Test reauth flow errors."""
mock_config_entry.add_to_hass(hass)
mock_mastodon_client.account_verify_credentials.side_effect = exception
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "token"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": error}
mock_mastodon_client.account_verify_credentials.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: "token"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"

View File

@@ -2,7 +2,8 @@
from unittest.mock import AsyncMock
from mastodon.Mastodon import MastodonNotFoundError
from mastodon.Mastodon import MastodonNotFoundError, MastodonUnauthorizedError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.mastodon.config_flow import MastodonConfigFlow
@@ -33,18 +34,27 @@ async def test_device_info(
assert device_entry == snapshot
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(MastodonNotFoundError, ConfigEntryState.SETUP_RETRY),
(MastodonUnauthorizedError, ConfigEntryState.SETUP_ERROR),
],
)
async def test_initialization_failure(
hass: HomeAssistant,
mock_mastodon_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test initialization failure."""
mock_mastodon_client.instance_v1.side_effect = MastodonNotFoundError
mock_mastodon_client.instance_v2.side_effect = MastodonNotFoundError
mock_mastodon_client.instance_v1.side_effect = exception
mock_mastodon_client.instance_v2.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
assert mock_config_entry.state is expected_state
async def test_setup_integration_fallback_to_instance_v1(