Skip to content

Commit

Permalink
fix: sensitive fields filtering, logger improvement and UNRECORDED_AT…
Browse files Browse the repository at this point in the history
…TRIBUTES
  • Loading branch information
geertmeersman committed Nov 28, 2023
1 parent 3844ac3 commit 61e45dd
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 14 deletions.
6 changes: 5 additions & 1 deletion custom_components/nexxtmove/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Nexxtmove integration."""
from __future__ import annotations

import logging

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
Expand All @@ -9,10 +11,12 @@
from requests.exceptions import ConnectionError

from .client import NexxtmoveClient
from .const import _LOGGER, COORDINATOR_UPDATE_INTERVAL, DOMAIN, PLATFORMS
from .const import COORDINATOR_UPDATE_INTERVAL, DOMAIN, PLATFORMS
from .exceptions import NexxtmoveException, NexxtmoveServiceException
from .models import NexxtmoveItem

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Nexxtmove from a config entry."""
Expand Down
10 changes: 5 additions & 5 deletions custom_components/nexxtmove/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@

import copy
import datetime
import logging

from dateutil.relativedelta import relativedelta
from requests import Session

from .const import (
_LOGGER,
BASE_HEADERS,
CONNECTION_RETRY,
DEFAULT_NEXXTMOVE_ENVIRONMENT,
Expand All @@ -17,7 +17,9 @@
)
from .exceptions import BadCredentialsException, NexxtmoveServiceException
from .models import NexxtmoveEnvironment, NexxtmoveItem
from .utils import format_entity_name
from .utils import format_entity_name, mask_fields

_LOGGER = logging.getLogger(__name__)


class NexxtmoveClient:
Expand Down Expand Up @@ -64,8 +66,7 @@ def request(
)
else:
data_copy = copy.deepcopy(data)
if "password" in data_copy:
data_copy["password"] = "***FILTERED***"
mask_fields(data_copy, ["password"])
_LOGGER.debug(f"{caller} Calling POST {url} with {data_copy}")
response = self.session.post(
url,
Expand Down Expand Up @@ -117,7 +118,6 @@ def login(self) -> dict:
result = response.json()
try:
self.token = result.get("authToken")
_LOGGER.debug(f"Setting Token {self.token}")
self.profile = result.get("profile")
except Exception as exception:
raise BadCredentialsException(
Expand Down
5 changes: 4 additions & 1 deletion custom_components/nexxtmove/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Config flow to configure the Nexxtmove integration."""
from abc import ABC, abstractmethod
import logging
from typing import Any

from homeassistant.config_entries import ConfigEntry, ConfigFlow, OptionsFlow
Expand All @@ -16,10 +17,12 @@
import voluptuous as vol

from .client import NexxtmoveClient
from .const import _LOGGER, DOMAIN, NAME
from .const import DOMAIN, NAME
from .exceptions import BadCredentialsException, NexxtmoveServiceException
from .models import NexxtmoveConfigEntryData

_LOGGER = logging.getLogger(__name__)

DEFAULT_ENTRY_DATA = NexxtmoveConfigEntryData(
username=None,
password=None,
Expand Down
6 changes: 2 additions & 4 deletions custom_components/nexxtmove/const.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
"""Constants used by Nexxtmove."""
from datetime import timedelta
import json
import logging
from pathlib import Path
from typing import Final

from homeassistant.const import Platform

from .models import NexxtmoveEnvironment

_LOGGER = logging.getLogger(__name__)

PLATFORMS: Final = [Platform.SENSOR, Platform.SWITCH]

ATTRIBUTION: Final = "Data provided by Nexxtmove"
Expand All @@ -27,8 +24,9 @@
"Content-Type": "application/json; charset=utf-8",
}

UNRECORDED_ATTRIBUTES = {"charges", "events", "dates", "values"}

GRAPH_START_DATE = "20220101"
_LOGGER = logging.getLogger(__name__)

COORDINATOR_UPDATE_INTERVAL = timedelta(minutes=5)
CONNECTION_RETRY = 5
Expand Down
6 changes: 5 additions & 1 deletion custom_components/nexxtmove/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,25 @@
from __future__ import annotations

from datetime import datetime
import logging

from homeassistant.core import callback
from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo, EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import NexxtmoveDataUpdateCoordinator
from .const import _LOGGER, ATTRIBUTION, DOMAIN, NAME, VERSION, WEBSITE
from .const import ATTRIBUTION, DOMAIN, NAME, UNRECORDED_ATTRIBUTES, VERSION, WEBSITE
from .models import NexxtmoveItem

_LOGGER = logging.getLogger(__name__)


class NexxtmoveEntity(CoordinatorEntity[NexxtmoveDataUpdateCoordinator]):
"""Base Nexxtmove entity."""

_attr_attribution = ATTRIBUTION
_unrecorded_attributes = frozenset(UNRECORDED_ATTRIBUTES)

def __init__(
self,
Expand Down
5 changes: 4 additions & 1 deletion custom_components/nexxtmove/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections.abc import Callable
import copy
from dataclasses import dataclass
import logging
from typing import Any

from homeassistant.components.sensor import (
Expand All @@ -20,10 +21,12 @@
from homeassistant.helpers.typing import StateType

from . import NexxtmoveDataUpdateCoordinator
from .const import _LOGGER, DOMAIN
from .const import DOMAIN
from .entity import NexxtmoveEntity
from .models import NexxtmoveItem

_LOGGER = logging.getLogger(__name__)


@dataclass
class NexxtmoveSensorDescription(SensorEntityDescription):
Expand Down
5 changes: 4 additions & 1 deletion custom_components/nexxtmove/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import Any

from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
Expand All @@ -13,10 +14,12 @@
from homeassistant.helpers.typing import StateType

from . import NexxtmoveDataUpdateCoordinator
from .const import _LOGGER, DOMAIN
from .const import DOMAIN
from .entity import NexxtmoveEntity
from .models import NexxtmoveItem

_LOGGER = logging.getLogger(__name__)


@dataclass
class NexxtmoveSwitchDescription(SwitchEntityDescription):
Expand Down
19 changes: 19 additions & 0 deletions custom_components/nexxtmove/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,22 @@ def get_json_dict_path(dictionary, path):
if isinstance(json_dict, list):
json_dict = json_dict[0]
return json_dict


def mask_fields(json_data, fields_to_mask):
"""Mask sensitive fields."""
if isinstance(json_data, dict):
for field in fields_to_mask:
if field in json_data:
json_data[field] = "***FILTERED***"

for _, value in json_data.items():
mask_fields(
value, fields_to_mask
) # Recursively traverse the JSON structure

elif isinstance(json_data, list):
for item in json_data:
mask_fields(
item, fields_to_mask
) # Recursively traverse each item in the list

0 comments on commit 61e45dd

Please sign in to comment.