Skip to content

Add token refresh and 401 retry for expired auth#558

Open
JeffSteinbok wants to merge 1 commit intomainfrom
copilot/token-refresh
Open

Add token refresh and 401 retry for expired auth#558
JeffSteinbok wants to merge 1 commit intomainfrom
copilot/token-refresh

Conversation

@JeffSteinbok
Copy link
Owner

Fixes High #2 from code review: Token refresh / auth retry

Tokens were fetched once at login with no refresh mechanism. If the token expired during runtime, all REST API calls and WebSocket reconnections would fail silently until a full HA restart.

Changes

helpers.py

  • Return actual HTTP status code on non-200 responses (was returning None for error codes)

pydreo/__init__.py

  • _re_login() — Re-authenticates and updates the WebSocket transport token
  • call_dreo_api() — Detects 401 responses and automatically retries once after re-login (login API itself is excluded to prevent infinite loops)

commandtransport.py

  • update_token() — Allows the PyDreo manager to inject a refreshed token
  • _start_websocket() — Restructured to rebuild the WebSocket URL on each reconnect attempt, picking up any token updates. Previously the URL was built once and reused for all reconnection attempts.

Tests

10 new tests:

  • 401 retry with successful re-login
  • No retry on login API itself (prevents infinite loop)
  • No retry when re-login fails
  • No retry on 200 (no false positives)
  • _re_login updates transport token
  • _re_login failure returns False
  • _re_login skips transport update in debug mode
  • update_token updates stored token
  • WebSocket reconnect picks up fresh token
  • URL format test updated for new loop structure

Tokens were fetched once at login with no refresh mechanism. If the
token expired during runtime, all REST API calls and WebSocket
reconnections would fail silently until a full HA restart.

Changes:
- helpers.py: Return actual HTTP status code on non-200 responses
- pydreo/__init__.py: Add _re_login() method that re-authenticates
  and updates the WebSocket transport token. call_dreo_api() now
  detects 401 responses and automatically retries once after re-login
  (login API itself is excluded to prevent infinite loops).
- commandtransport.py: Add update_token() method. Restructure
  _start_websocket() to rebuild the WebSocket URL on each reconnect
  attempt, picking up any token updates from re-login.

Includes 10 new tests covering 401 retry, re-login success/failure,
transport token update, and WebSocket reconnect with fresh tokens.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant