|
6 | 6 | from aiorinnai.errors import RequestError |
7 | 7 |
|
8 | 8 | from homeassistant.config_entries import ConfigEntry |
9 | | -from homeassistant.const import CONF_EMAIL |
| 9 | +from homeassistant.const import CONF_EMAIL, CONF_PASSWORD |
10 | 10 | from homeassistant.core import HomeAssistant |
11 | 11 | from homeassistant.exceptions import ConfigEntryNotReady, ConfigEntryAuthFailed |
12 | 12 | from homeassistant.helpers.aiohttp_client import async_get_clientsession |
@@ -91,10 +91,28 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry): |
91 | 91 | if config_entry.version == 1: |
92 | 92 | data = {**config_entry.data} |
93 | 93 |
|
94 | | - if not data.get(CONF_ACCESS_TOKEN): |
95 | | - data[CONF_ACCESS_TOKEN] = config_entry.data[CONF_REFRESH_TOKEN] |
96 | | - if not data.get(CONF_REFRESH_TOKEN): |
97 | | - data[CONF_REFRESH_TOKEN] = config_entry.data[CONF_REFRESH_TOKEN] |
| 94 | + # Set default values if keys are missing |
| 95 | + data.setdefault(CONF_ACCESS_TOKEN, "") |
| 96 | + data.setdefault(CONF_REFRESH_TOKEN, "") |
| 97 | + |
| 98 | + if not data[CONF_ACCESS_TOKEN] or not data[CONF_REFRESH_TOKEN]: |
| 99 | + # Fetch new tokens from the API using existing credentials |
| 100 | + client = API() |
| 101 | + try: |
| 102 | + # Assuming you have CONF_EMAIL and CONF_PASSWORD in the config_entry.data |
| 103 | + await client.async_login(config_entry.data[CONF_EMAIL], config_entry.data[CONF_PASSWORD]) |
| 104 | + user_info = await client.user.get_info() |
| 105 | + _LOGGER.debug("User info retrieved during migration: %s", user_info) |
| 106 | + |
| 107 | + # Update tokens in data |
| 108 | + data[CONF_ACCESS_TOKEN] = client.access_token |
| 109 | + data[CONF_REFRESH_TOKEN] = client.refresh_token |
| 110 | + except Unauthenticated as err: |
| 111 | + _LOGGER.error("Authentication error during migration: %s", err) |
| 112 | + raise ConfigEntryAuthFailed from err |
| 113 | + except RequestError as err: |
| 114 | + _LOGGER.error("Request error during migration: %s", err) |
| 115 | + raise ConfigEntryNotReady from err |
98 | 116 |
|
99 | 117 | hass.config_entries.async_update_entry(config_entry, data=data, version=2) |
100 | 118 |
|
|
0 commit comments