Skip to content

Commit

Permalink
Simplify logic
Browse files Browse the repository at this point in the history
  • Loading branch information
jschlyter committed Jan 4, 2025
1 parent bca24be commit 62ea834
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions custom_components/polestar_api/pypolestar/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,26 +115,25 @@ async def get_token(self, refresh: bool = True, force: bool = False) -> None:

if refresh and self.refresh_token:
try:
response = await self._token_refresh()
self._parse_token_response(response)
await self._token_refresh()
self.logger.debug("Token refreshed")
except PolestarAuthException:
self.logger.warning("Unable to refresh token, retry with code")

try:
response = await self._authorization_code()
self._parse_token_response(response)
await self._authorization_code()
self.logger.debug("Initial token acquired")
return
except PolestarAuthException as exc:
raise PolestarAuthException("Unable to acquire initial token") from exc

def _parse_token_response(self, response: httpx.Response) -> None:
"""Parse response from token endpoint."""
"""Parse response from token endpoint and update token state."""

payload = response.json()
self.latest_call_code = response.status_code

payload = response.json()

if "error" in payload:
self.logger.error("Token error: %s", payload)
raise PolestarAuthException("Token error", response.status_code)
Expand All @@ -148,7 +147,7 @@ def _parse_token_response(self, response: httpx.Response) -> None:

self.logger.debug("Access token updated, valid until %s", self.token_expiry)

async def _authorization_code(self) -> httpx.Response:
async def _authorization_code(self) -> None:
"""Get initial token via authorization code."""

if (code := await self._get_code()) is None:
Expand All @@ -170,13 +169,15 @@ async def _authorization_code(self) -> httpx.Response:
"Call token endpoint with grant_type=%s", token_request["grant_type"]
)

return await self.client_session.post(
response = await self.client_session.post(
self.oidc_configuration["token_endpoint"],
data=token_request,
timeout=HTTPX_TIMEOUT,
)

async def _token_refresh(self) -> httpx.Response:
self._parse_token_response(response)

async def _token_refresh(self) -> None:
"""Refresh existing token."""

token_request = {
Expand All @@ -189,12 +190,14 @@ async def _token_refresh(self) -> httpx.Response:
"Call token endpoint with grant_type=%s", token_request["grant_type"]
)

return await self.client_session.post(
response = await self.client_session.post(
self.oidc_configuration["token_endpoint"],
data=token_request,
timeout=HTTPX_TIMEOUT,
)

self._parse_token_response(response)

async def _get_code(self) -> str | None:
query_params = await self._get_resume_path()

Expand Down

0 comments on commit 62ea834

Please sign in to comment.