Skip to content

Commit

Permalink
Support for re-configuring the username/password and better handling …
Browse files Browse the repository at this point in the history
…of login failures after a password change
  • Loading branch information
c99koder committed Oct 10, 2024
1 parent 6af48b6 commit 9dee96a
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 14 deletions.
3 changes: 3 additions & 0 deletions custom_components/medisafe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Config
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.helpers.update_coordinator import UpdateFailed
Expand Down Expand Up @@ -76,6 +77,8 @@ async def _async_update_data(self):
"""Update data via library."""
try:
return await self.config_entry.runtime_data.client.async_get_data()
except ConfigEntryAuthFailed as exception:
raise exception
except Exception as exception:
raise UpdateFailed() from exception

Expand Down
1 change: 1 addition & 0 deletions custom_components/medisafe/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ async def async_get_data(self) -> dict:
{"username": self._username, "password": self._password},
)
if "error" in auth:
print(auth)
if "message" in auth["error"]:
_LOGGER.error(f"Authentication failed: {auth['error']['message']}")
raise ConfigEntryAuthFailed(auth["error"]["message"])
Expand Down
38 changes: 28 additions & 10 deletions custom_components/medisafe/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.helpers.aiohttp_client import async_create_clientsession
Expand All @@ -19,6 +20,8 @@
from .const import CONF_USERNAME
from .const import DOMAIN

CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)


class MedisafeFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Config flow for medisafe."""
Expand All @@ -31,28 +34,42 @@ def __init__(self):
self._errors = {}

async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
self._errors = {}

# Uncomment the next 2 lines if only a single instance of the integration is allowed:
# if self._async_current_entries():
# return self.async_abort(reason="single_instance_allowed")

if user_input is not None:
valid = await self._test_credentials(
user_input[CONF_USERNAME], user_input[CONF_PASSWORD]
)
if valid:
return self.async_create_entry(
title=user_input[CONF_USERNAME], data=user_input
)
if (
self.source == config_entries.SOURCE_RECONFIGURE
or self.source == config_entries.SOURCE_REAUTH
):
return self.async_update_reload_and_abort(
self.hass.config_entries.async_get_entry(
self.context["entry_id"]
),
data=user_input,
)
else:
return self.async_create_entry(
title=user_input[CONF_USERNAME], data=user_input
)
else:
self._errors["base"] = "auth"

return await self._show_config_form(user_input)

return await self._show_config_form(user_input)

async def async_step_reconfigure(self, user_input=None):
self._errors = {}
return await self._show_config_form(user_input)

async def async_step_reauth(self, user_input=None):
self._errors = {}
return await self._show_config_form(user_input)

async def _show_config_form(self, user_input): # pylint: disable=unused-argument
"""Show the configuration form to edit location data."""
return self.async_show_form(
Expand All @@ -66,8 +83,9 @@ async def _show_config_form(self, user_input): # pylint: disable=unused-argumen
async def _test_credentials(self, username, password):
"""Return true if credentials is valid."""
try:
session = async_create_clientsession(self.hass)
client = MedisafeApiClient(username, password, session)
client = MedisafeApiClient(
username, password, async_create_clientsession(self.hass)
)
await client.async_get_data()
return True
except Exception: # pylint: disable=broad-except
Expand Down
8 changes: 4 additions & 4 deletions custom_components/medisafe/manifest.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"domain": "medisafe",
"name": "Medisafe",
"documentation": "https://github.com/c99koder/ha-medisafe",
"issue_tracker": "https://github.com/c99koder/ha-medisafe/issues",
"dependencies": ["http"],
"config_flow": true,
"codeowners": ["@c99koder"],
"config_flow": true,
"dependencies": ["http"],
"documentation": "https://github.com/c99koder/ha-medisafe",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/c99koder/ha-medisafe/issues",
"requirements": [],
"version": "0.1.1"
}
4 changes: 4 additions & 0 deletions custom_components/medisafe/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
},
"error": {
"auth": "Username/Password is wrong."
},
"abort": {
"reauth_successful": "Configuration was updated successfully",
"reconfigure_successful": "Configuration was updated successfully"
}
}
}

0 comments on commit 9dee96a

Please sign in to comment.