Drop redundant token error handling (#181079)

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Josef Zweck
2026-09-07 08:49:22 +02:00
committed by GitHub
co-authored by Copilot Autofix powered by AI
parent 00e0267a8c
commit 1c71fe9926
35 changed files with 66 additions and 403 deletions
@@ -1,16 +1,9 @@
"""The Aladdin Connect Genie integration."""
import aiohttp
from genie_partner_sdk.client import AladdinConnectClient
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import (
aiohttp_client,
config_entry_oauth2_flow,
@@ -36,12 +29,7 @@ async def async_setup_entry(
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(err) from err
except (OAuth2TokenRequestError, aiohttp.ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
client = AladdinConnectClient(
api.AsyncConfigEntryAuth(aiohttp_client.async_get_clientsession(hass), session)
+3 -5
View File
@@ -14,8 +14,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
OAuth2TokenRequestBaseError,
)
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -44,15 +43,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: AugustConfigEntry) -> bo
august_gateway = AugustGateway(Path(hass.config.config_dir), session, oauth_session)
try:
await async_setup_august(hass, entry, august_gateway)
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except OAuth2TokenRequestBaseError:
raise
except (RequireValidation, InvalidAuth) as err:
raise ConfigEntryAuthFailed from err
except TimeoutError as err:
raise ConfigEntryNotReady("Timed out connecting to august api") from err
except (
AugustApiAIOHTTPError,
OAuth2TokenRequestError,
ClientError,
CannotConnect,
) as err:
+3 -37
View File
@@ -1,7 +1,6 @@
"""Account linking via the cloud."""
from datetime import datetime
from http import HTTPStatus
import logging
from typing import Any, override
@@ -11,11 +10,6 @@ from hass_nabucasa import account_link
from homeassistant.const import __version__ as HA_VERSION
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import (
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
OAuth2TokenRequestTransientError,
)
from homeassistant.helpers import config_entry_oauth2_flow, event
from .const import DATA_CLOUD, DOMAIN
@@ -163,35 +157,7 @@ class CloudOAuth2Implementation(config_entry_oauth2_flow.AbstractOAuth2Implement
@override
async def _async_refresh_token(self, token: dict) -> dict:
"""Refresh a token."""
try:
new_token = await account_link.async_fetch_access_token(
self.hass.data[DATA_CLOUD], self.service, token["refresh_token"]
)
except aiohttp.ClientResponseError as err:
if err.status == HTTPStatus.TOO_MANY_REQUESTS or 500 <= err.status <= 599:
raise OAuth2TokenRequestTransientError(
request_info=err.request_info,
history=err.history,
status=err.status,
message=err.message,
headers=err.headers,
domain=self.service,
) from err
if 400 <= err.status <= 499:
raise OAuth2TokenRequestReauthError(
request_info=err.request_info,
history=err.history,
status=err.status,
message=err.message,
headers=err.headers,
domain=self.service,
) from err
raise OAuth2TokenRequestError(
request_info=err.request_info,
history=err.history,
status=err.status,
message=err.message,
headers=err.headers,
domain=self.service,
) from err
new_token = await account_link.async_fetch_access_token(
self.hass.data[DATA_CLOUD], self.service, token["refresh_token"]
)
return {**token, **new_token}
@@ -1,17 +1,11 @@
"""The Electric Kiwi integration."""
import aiohttp
from electrickiwi_api import ElectricKiwiApi
from electrickiwi_api.exceptions import ApiException, AuthException
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import (
aiohttp_client,
config_entry_oauth2_flow,
@@ -41,12 +35,7 @@ async def async_setup_entry(
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(err) from err
except (OAuth2TokenRequestError, aiohttp.ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
ek_api = ElectricKiwiApi(
api.ConfigEntryElectricKiwiAuth(
+2 -13
View File
@@ -6,7 +6,6 @@ import logging
import time
from typing import Any
import aiohttp
from gcal_sync.api import GoogleCalendarService
from gcal_sync.exceptions import ApiException, AuthException
import voluptuous as vol
@@ -20,12 +19,7 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_entry_oauth2_flow, config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import generate_entity_id
@@ -105,12 +99,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: GoogleConfigEntry) -> bo
if session.token["expires_at"] >= now + timedelta(days=365).total_seconds():
session.token["expires_in"] = 0
session.token["expires_at"] = now
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except (OAuth2TokenRequestError, aiohttp.ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
if not async_entry_has_scopes(entry):
raise ConfigEntryAuthFailed(
@@ -3,19 +3,12 @@
import asyncio
from typing import override
from aiohttp import ClientError
from gassist_text import TextAssistantAsync
from google.oauth2.credentials import Credentials
from homeassistant.components import conversation
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_NAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import config_validation as cv, discovery, intent
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
@@ -55,14 +48,7 @@ async def async_setup_entry(
"""Set up Google Assistant SDK from a config entry."""
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="reauth_required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
mem_storage = InMemoryStorage(hass)
hass.http.register_view(GoogleAssistantSDKAudioView(mem_storage))
@@ -37,9 +37,6 @@
},
"grpc_error": {
"message": "Failed to communicate with Google Assistant"
},
"reauth_required": {
"message": "Credentials are invalid, re-authentication required"
}
},
"options": {
@@ -1,15 +1,8 @@
"""The Google Photos integration."""
from aiohttp import ClientError
from google_photos_library_api.api import GooglePhotosLibraryApi
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import config_entry_oauth2_flow, config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.typing import ConfigType
@@ -45,14 +38,7 @@ async def async_setup_entry(
web_session = async_get_clientsession(hass)
oauth_session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
auth = api.AsyncConfigEntryAuth(web_session, oauth_session)
try:
await auth.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await auth.async_get_access_token()
coordinator = GooglePhotosUpdateCoordinator(
hass, entry, GooglePhotosLibraryApi(auth)
)
@@ -1,16 +1,9 @@
"""Support for Google Sheets."""
import aiohttp
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
@@ -40,16 +33,7 @@ async def async_setup_entry(
"""Set up Google Sheets from a config entry."""
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady from err
except aiohttp.ClientError as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
if not async_entry_has_scopes(hass, entry):
raise ConfigEntryAuthFailed("Required scopes are not present, reauth required")
@@ -2,16 +2,9 @@
import asyncio
from aiohttp import ClientError
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_entry_oauth2_flow
from . import api
@@ -35,14 +28,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: GoogleTasksConfigEntry)
)
session = config_entry_oauth2_flow.OAuth2Session(hass, entry, implementation)
auth = api.AsyncConfigEntryAuth(hass, session)
try:
await auth.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await auth.async_get_access_token()
try:
task_lists = await auth.list_task_lists()
@@ -5,17 +5,10 @@ from typing import Any
from aiohomeconnect.client import Client as HomeConnectClient
from aiohomeconnect.model import EventKey
import aiohttp
import jwt
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
@@ -63,12 +56,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: HomeConnectConfigEntry)
session = OAuth2Session(hass, entry, implementation)
config_entry_auth = AsyncConfigEntryAuth(hass, session)
try:
await config_entry_auth.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except (OAuth2TokenRequestError, aiohttp.ClientError) as err:
raise ConfigEntryNotReady from err
await config_entry_auth.async_get_access_token()
home_connect_client = HomeConnectClient(config_entry_auth)
@@ -4,12 +4,7 @@ from aioautomower.session import AutomowerSession
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import (
aiohttp_client,
config_entry_oauth2_flow,
@@ -61,12 +56,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: AutomowerConfigEntry) ->
api_api,
await dt_util.async_get_time_zone(time_zone_str),
)
try:
await api_api.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady from err
await api_api.async_get_access_token()
if "amc:api" not in entry.data["token"]["scope"]:
# We raise ConfigEntryAuthFailed here because the websocket can't be used
+1 -17
View File
@@ -1,16 +1,9 @@
"""The Miele integration."""
from aiohttp import ClientError
from pymiele import MieleAPI
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -57,16 +50,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: MieleConfigEntry) -> boo
session = OAuth2Session(hass, entry, implementation)
auth = AsyncConfigEntryAuth(async_get_clientsession(hass), session)
try:
await auth.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="config_entry_auth_failed"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN, translation_key="config_entry_not_ready"
) from err
await auth.async_get_access_token()
# Setup MieleAPI and coordinator for data fetch
_api = MieleAPI(auth)
@@ -1146,12 +1146,6 @@
}
},
"exceptions": {
"config_entry_auth_failed": {
"message": "Authentication failed. Please log in again."
},
"config_entry_not_ready": {
"message": "Error while loading the integration."
},
"get_programs_error": {
"message": "'Get programs' action failed: {status} / {message}"
},
+2 -13
View File
@@ -2,19 +2,13 @@
import logging
from aiohttp import ClientError
from pybotvac import Account
from pybotvac.exceptions import NeatoException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
@@ -55,12 +49,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: NeatoConfigEntry) -> boo
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as ex:
raise ConfigEntryAuthFailed from ex
except (OAuth2TokenRequestError, ClientError) as ex:
raise ConfigEntryNotReady from ex
await session.async_ensure_token_valid()
neato_session = api.ConfigEntryAuth(hass, entry, implementation)
hub = NeatoHub(hass, Account(neato_session))
+2 -17
View File
@@ -6,7 +6,7 @@ from http import HTTPStatus
import logging
from typing import override
from aiohttp import ClientError, web
from aiohttp import web
from google_nest_sdm.camera_traits import CameraClipPreviewTrait
from google_nest_sdm.device import Device
from google_nest_sdm.device_manager import DeviceManager
@@ -42,8 +42,6 @@ from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
HomeAssistantError,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
Unauthorized,
)
from homeassistant.helpers import (
@@ -251,20 +249,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: NestConfigEntry) -> bool
)
auth = await api.new_auth(hass, entry)
try:
await auth.async_get_access_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="reauth_required"
) from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN, translation_key="auth_server_error"
) from err
except ClientError as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN, translation_key="auth_client_error"
) from err
await auth.async_get_access_token()
subscriber = await api.new_subscriber(hass, entry, auth)
if not subscriber:
@@ -129,12 +129,6 @@
}
},
"exceptions": {
"auth_client_error": {
"message": "Client error during authentication, please check your network connection."
},
"auth_server_error": {
"message": "Error response from authentication server, please see logs for details."
},
"device_api_error": {
"message": "Error communicating with the Device Access API, please see logs for details."
},
+2 -13
View File
@@ -3,19 +3,13 @@
import logging
from typing import Any
from aiohttp import ClientError
import pyatmo
from homeassistant.components import cloud
from homeassistant.components.webhook import async_unregister as webhook_unregister
from homeassistant.const import CONF_WEBHOOK_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import (
aiohttp_client,
config_validation as cv,
@@ -60,12 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: NetatmoConfigEntry) -> b
hass.config_entries.async_update_entry(entry, unique_id=DOMAIN)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as ex:
raise ConfigEntryAuthFailed("Token not valid, trigger renewal") from ex
except (OAuth2TokenRequestError, ClientError) as ex:
raise ConfigEntryNotReady from ex
await session.async_ensure_token_valid()
required_scopes = api.get_api_scopes(entry.data["auth_implementation"])
if not (set(session.token["scope"]) & set(required_scopes)):
+2 -16
View File
@@ -15,12 +15,7 @@ from onedrive_personal_sdk.exceptions import (
from homeassistant.const import CONF_ACCESS_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -174,16 +169,7 @@ async def _get_onedrive_client(
session = OAuth2Session(hass, entry, implementation)
# Refresh up front, so a failure surfaces here instead of from inside the client
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="authentication_failed"
) from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN, translation_key="connection_error"
) from err
await session.async_ensure_token_valid()
async def get_access_token() -> str:
await session.async_ensure_token_valid()
@@ -13,12 +13,7 @@ from onedrive_personal_sdk.exceptions import (
from homeassistant.const import CONF_ACCESS_TOKEN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
@@ -99,16 +94,7 @@ async def _get_onedrive_client(
session = OAuth2Session(hass, entry, implementation)
# Refresh up front, so a failure surfaces here instead of from inside the client
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN, translation_key="authentication_failed"
) from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN, translation_key="connection_error"
) from err
await session.async_ensure_token_valid()
async def get_access_token() -> str:
await session.async_ensure_token_valid()
@@ -49,12 +49,7 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import Event, HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -136,12 +131,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: SmartThingsConfigEntry)
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
client = SmartThings(session=async_get_clientsession(hass))
@@ -110,12 +110,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslaFleetConfigEntry) -
implementation = await async_get_config_entry_implementation(hass, entry)
oauth_session = OAuth2Session(hass, entry, implementation)
try:
await oauth_session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except OAuth2TokenRequestError as err:
raise ConfigEntryNotReady from err
await oauth_session.async_ensure_token_valid()
access_token = oauth_session.token[CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
+2 -15
View File
@@ -6,17 +6,11 @@ import logging
from typing import Final
import aiohttp
from aiohttp.client_exceptions import ClientError
import tibber
from homeassistant.const import CONF_ACCESS_TOKEN, EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import Event, HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -116,14 +110,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: TibberConfigEntry) -> bo
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauthentication required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
entry.runtime_data = TibberRuntimeData(
session=session,
+1 -15
View File
@@ -2,17 +2,10 @@
from typing import cast
from aiohttp.client_exceptions import ClientError
from twitchAPI.twitch import Twitch
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers.config_entry_oauth2_flow import (
LocalOAuth2Implementation,
OAuth2Session,
@@ -30,14 +23,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: TwitchConfigEntry) -> bo
await async_get_config_entry_implementation(hass, entry),
)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
access_token = entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN]
client = Twitch(
+2 -19
View File
@@ -2,18 +2,12 @@
from typing import override
from aiohttp import ClientError
from httpx import AsyncClient, HTTPStatusError, RequestError
from pythonxbox.authentication.manager import AuthenticationManager
from pythonxbox.authentication.models import OAuth2TokenResponse
from pythonxbox.common.exceptions import AuthenticationException
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestReauthError,
OAuth2TokenRequestTransientError,
)
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
from homeassistant.util.dt import utc_from_timestamp
@@ -35,18 +29,7 @@ class AsyncConfigEntryAuth(AuthenticationManager):
"""Return a valid access token."""
if not self._oauth_session.valid_token:
try:
await self._oauth_session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as e:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_exception",
) from e
except (OAuth2TokenRequestTransientError, ClientError) as e:
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="request_exception",
) from e
await self._oauth_session.async_ensure_token_valid()
self.oauth = self._get_oauth_token()
# This will skip the OAuth refresh and only refresh User and XSTS tokens
+3 -5
View File
@@ -16,8 +16,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
OAuth2TokenRequestBaseError,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.config_entry_oauth2_flow import (
@@ -41,15 +40,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: YaleConfigEntry) -> bool
yale_gateway = YaleGateway(Path(hass.config.config_dir), session, oauth_session)
try:
await async_setup_yale(hass, entry, yale_gateway)
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed from err
except OAuth2TokenRequestBaseError:
raise
except (RequireValidation, InvalidAuth) as err:
raise ConfigEntryAuthFailed from err
except TimeoutError as err:
raise ConfigEntryNotReady("Timed out connecting to yale api") from err
except (
YaleApiError,
OAuth2TokenRequestError,
ClientError,
CannotConnect,
) as err:
+1 -18
View File
@@ -1,21 +1,12 @@
"""The Yoto integration."""
import aiohttp
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
async_get_config_entry_implementation,
)
from .const import DOMAIN
from .coordinator import YotoConfigEntry, YotoDataUpdateCoordinator
PLATFORMS: list[Platform] = [
@@ -34,15 +25,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: YotoConfigEntry) -> bool
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
try:
await session.async_ensure_token_valid()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="authentication_failed",
) from err
except (aiohttp.ClientError, OAuth2TokenRequestError) as err:
raise ConfigEntryNotReady from err
await session.async_ensure_token_valid()
coordinator = YotoDataUpdateCoordinator(hass, entry, session)
await coordinator.async_config_entry_first_refresh()
+1 -16
View File
@@ -1,15 +1,7 @@
"""Support for YouTube."""
from aiohttp.client_exceptions import ClientError
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.config_entry_oauth2_flow import (
OAuth2Session,
@@ -27,14 +19,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: YouTubeConfigEntry) -> b
implementation = await async_get_config_entry_implementation(hass, entry)
session = OAuth2Session(hass, entry, implementation)
auth = AsyncConfigEntryAuth(hass, session)
try:
await auth.check_and_refresh_token()
except OAuth2TokenRequestReauthError as err:
raise ConfigEntryAuthFailed(
"OAuth session is not valid, reauth required"
) from err
except (OAuth2TokenRequestError, ClientError) as err:
raise ConfigEntryNotReady from err
await auth.check_and_refresh_token()
coordinator = YouTubeDataUpdateCoordinator(hass, entry, auth)
await coordinator.async_config_entry_first_refresh()
@@ -12,6 +12,7 @@ from homeassistant.components.aladdin_connect import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
OAuth2TokenRequestConnectionError,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
@@ -106,7 +107,7 @@ async def test_setup_entry_token_connection_error(
"""Test setup entry retries when token validation has a connection error."""
with patch(
"homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid",
side_effect=ClientConnectionError(),
side_effect=OAuth2TokenRequestConnectionError(domain=DOMAIN),
):
await init_integration(hass, mock_config_entry)
+2 -2
View File
@@ -288,7 +288,7 @@ async def test_refresh_token_error(
status: int,
expected_exception: type[OAuth2TokenRequestError],
) -> None:
"""Test that _async_refresh_token wraps ClientResponseError."""
"""Test a failing token request reports the service, not the cloud domain."""
hass.data[DATA_CLOUD] = None
impl = account_link.CloudOAuth2Implementation(hass, "test")
@@ -299,7 +299,7 @@ async def test_refresh_token_error(
),
pytest.raises(expected_exception) as exc_info,
):
await impl._async_refresh_token(
await impl.async_refresh_token(
{"refresh_token": "mock-refresh", "access_token": "mock-access"}
)
+6 -6
View File
@@ -62,26 +62,26 @@ async def test_load_unload_config_entry(
@pytest.mark.parametrize(
("status", "state", "reason", "reauth_expected"),
("status", "state", "translation_key", "reauth_expected"),
[
pytest.param(
HTTPStatus.BAD_REQUEST,
ConfigEntryState.SETUP_ERROR,
"Authentication failed",
"oauth2_helper_reauth_required",
True,
id="reauth",
),
pytest.param(
HTTPStatus.TOO_MANY_REQUESTS,
ConfigEntryState.SETUP_RETRY,
"Failed to connect to OneDrive",
"oauth2_helper_refresh_transient",
False,
id="transient",
),
pytest.param(
HTTPStatus.INTERNAL_SERVER_ERROR,
ConfigEntryState.SETUP_RETRY,
"Failed to connect to OneDrive",
"oauth2_helper_refresh_transient",
False,
id="server_error",
),
@@ -94,7 +94,7 @@ async def test_token_refresh_errors(
aioclient_mock: AiohttpClientMocker,
status: HTTPStatus,
state: ConfigEntryState,
reason: str,
translation_key: str,
reauth_expected: bool,
) -> None:
"""Test a failing token refresh during setup."""
@@ -105,7 +105,7 @@ async def test_token_refresh_errors(
await hass.async_block_till_done()
assert mock_config_entry.state is state
assert mock_config_entry.reason == reason
assert mock_config_entry.error_reason_translation_key == translation_key
assert bool(hass.config_entries.flow.async_progress()) is reauth_expected
@@ -56,26 +56,26 @@ async def test_load_unload_config_entry(
@pytest.mark.parametrize(
("status", "state", "reason", "reauth_expected"),
("status", "state", "translation_key", "reauth_expected"),
[
pytest.param(
HTTPStatus.BAD_REQUEST,
ConfigEntryState.SETUP_ERROR,
"Authentication failed",
"oauth2_helper_reauth_required",
True,
id="reauth",
),
pytest.param(
HTTPStatus.TOO_MANY_REQUESTS,
ConfigEntryState.SETUP_RETRY,
"Failed to connect to OneDrive",
"oauth2_helper_refresh_transient",
False,
id="transient",
),
pytest.param(
HTTPStatus.INTERNAL_SERVER_ERROR,
ConfigEntryState.SETUP_RETRY,
"Failed to connect to OneDrive",
"oauth2_helper_refresh_transient",
False,
id="server_error",
),
@@ -88,7 +88,7 @@ async def test_token_refresh_errors(
aioclient_mock: AiohttpClientMocker,
status: HTTPStatus,
state: ConfigEntryState,
reason: str,
translation_key: str,
reauth_expected: bool,
) -> None:
"""Test a failing token refresh during setup."""
@@ -103,7 +103,7 @@ async def test_token_refresh_errors(
await hass.async_block_till_done()
assert mock_config_entry.state is state
assert mock_config_entry.reason == reason
assert mock_config_entry.error_reason_translation_key == translation_key
assert bool(hass.config_entries.flow.async_progress()) is reauth_expected
+2 -2
View File
@@ -4,12 +4,12 @@ import http
import time
from unittest.mock import AsyncMock, patch
from aiohttp.client_exceptions import ClientError
import pytest
from homeassistant.components.twitch.const import DOMAIN, OAUTH2_TOKEN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import OAuth2TokenRequestConnectionError
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
@@ -113,7 +113,7 @@ async def test_expired_token_refresh_client_error(
with patch(
"homeassistant.components.twitch.OAuth2Session.async_ensure_token_valid",
side_effect=ClientError,
side_effect=OAuth2TokenRequestConnectionError(domain=DOMAIN),
):
config_entry.add_to_hass(hass)
+2 -1
View File
@@ -15,6 +15,7 @@ from homeassistant.components.yoto.const import (
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
OAuth2TokenRequestConnectionError,
OAuth2TokenRequestError,
OAuth2TokenRequestReauthError,
)
@@ -151,7 +152,7 @@ async def test_setup_retries_when_implementation_missing(
@pytest.mark.parametrize(
"side_effect",
[
aiohttp.ClientError("boom"),
OAuth2TokenRequestConnectionError(domain=DOMAIN),
OAuth2TokenRequestError(request_info=Mock(), domain=DOMAIN),
],
)
+2 -2
View File
@@ -4,12 +4,12 @@ import http
import time
from unittest.mock import patch
from aiohttp.client_exceptions import ClientError
import pytest
from homeassistant.components.youtube.const import CONF_CHANNELS, DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import OAuth2TokenRequestConnectionError
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
@@ -110,7 +110,7 @@ async def test_expired_token_refresh_client_error(
with patch(
"homeassistant.components.youtube.OAuth2Session.async_ensure_token_valid",
side_effect=ClientError,
side_effect=OAuth2TokenRequestConnectionError(domain=DOMAIN),
):
await setup_integration()