def initial_run(self): """Run this at startup to initialize the platform data.""" users, tokens = load_authentications( self.hass.config.path(".storage/auth"), self.exclude ) if os.path.isfile(self.out): self.stored = get_outfile_content(self.out) else: _LOGGER.debug("File has not been created, no data pressent.") for access in tokens: try: ValidateIP(access) except ValueError: continue accessdata = AuthenticatedData(access, tokens[access]) if accessdata.ipaddr in self.stored: store = AuthenticatedData(accessdata.ipaddr, self.stored[access]) accessdata.ipaddr = access if store.user_id is not None: accessdata.user_id = store.user_id if store.hostname is not None: accessdata.hostname = store.hostname if store.country is not None: accessdata.country = store.country if store.region is not None: accessdata.region = store.region if store.city is not None: accessdata.city = store.city if store.last_access is not None: accessdata.last_access = store.last_access elif store.attributes.get("last_authenticated") is not None: accessdata.last_access = store.attributes["last_authenticated"] elif store.attributes.get("last_used_at") is not None: accessdata.last_access = store.attributes["last_used_at"] if store.prev_access is not None: accessdata.prev_access = store.prev_access elif store.attributes.get("previous_authenticated_time") is not None: accessdata.prev_access = store.attributes[ "previous_authenticated_time" ] elif store.attributes.get("prev_used_at") is not None: accessdata.prev_access = store.attributes["prev_used_at"] ipaddress = IPData(accessdata, users, self.provider, False) if accessdata.ipaddr not in self.stored: ipaddress.lookup() self.hass.data[PLATFORM_NAME][access] = ipaddress self.write_to_file()
def update(self): """Method to update sensor value""" updated = False users, tokens = load_authentications( self.hass.config.path(".storage/auth"), self.exclude, self.exclude_clients) _LOGGER.debug("Users %s", users) _LOGGER.debug("Access %s", tokens) for access in tokens: try: ValidateIP(access) except ValueError: continue if access in self.hass.data[PLATFORM_NAME]: ipaddress = self.hass.data[PLATFORM_NAME][access] try: new = humanize_time(tokens[access]["last_used_at"]) stored = humanize_time(ipaddress.last_used_at) if new == stored: continue if new is None or stored is None: continue elif new > stored: updated = True _LOGGER.info("New successful login from known IP (%s)", access) ipaddress.prev_used_at = ipaddress.last_used_at ipaddress.last_used_at = tokens[access]["last_used_at"] except Exception: # pylint: disable=broad-except pass else: updated = True _LOGGER.warning("New successful login from unknown IP (%s)", access) accessdata = AuthenticatedData(access, tokens[access]) ipaddress = IPData(accessdata, users, self.provider) ipaddress.lookup() if ipaddress.hostname is None: ipaddress.hostname = get_hostname(ipaddress.ip_address) if ipaddress.new_ip: if self.notify: ipaddress.notify(self.hass) ipaddress.new_ip = False self.hass.data[PLATFORM_NAME][access] = ipaddress for ipaddr in sorted(tokens, key=lambda x: tokens[x]["last_used_at"], reverse=True): self.last_ip = self.hass.data[PLATFORM_NAME][ipaddr] break if self.last_ip is not None: self._state = self.last_ip.ip_address if updated: self.write_to_file()
def update(self): """Method to update sensor value""" updated = False users, tokens = load_authentications(self.hass.config.path(".storage/auth")) for access in tokens: try: ValidateIP(access) except ValueError: continue if access in self.hass.data[PLATFORM_NAME]: ipaddress = self.hass.data[PLATFORM_NAME][access] try: new = datetime.strptime(access["last_used_at"][:19], "%Y-%m-%dT%H:%M") stored = datetime.strptime(ipaddress.last_used_at[:19], "%Y-%m-%dT%H:%M") if new == stored: continue elif new > stored: updated = True _LOGGER.info("New successfull login from known IP (%s)", access) ipaddress.prev_used_at = ipaddress.last_used_at ipaddress.last_used_at = access["last_used_at"] except Exception: # pylint: disable=broad-except pass else: updated = True _LOGGER.warning("New successfull login from unknown IP (%s)", access) accessdata = AuthenticatedData(access, tokens[access]) ipaddress = IPData(accessdata, users, self.provider) ipaddress.lookup() if ipaddress.new_ip: if self.notify: ipaddress.notify(self.hass) ipaddress.new_ip = False if ipaddress.hostname is None: ipaddress.hostname = get_hostname(ipaddress.ip_address) self.hass.data[PLATFORM_NAME][access] = ipaddress for ipaddr in sorted(tokens, key=lambda x:tokens[x]['last_used_at'], reverse=True): self.last_ip = self.hass.data[PLATFORM_NAME][ipaddr] break self._state = self.last_ip.ip_address if updated: self.write_to_file()
def load_authentications(authfile, exclude, exclude_clients): """Load info from auth file.""" if not os.path.exists(authfile): _LOGGER.critical("File is missing %s", authfile) return False with open(authfile, "r") as authfile: auth = json.loads(authfile.read()) users = {} for user in auth["data"]["users"]: users[user["id"]] = user["name"] tokens = auth["data"]["refresh_tokens"] tokens_cleaned = {} for token in tokens: try: for excludeaddress in exclude: if ValidateIP(token["last_used_ip"]) in ip_network( excludeaddress, False ): raise Exception("IP in excluded address configuration") if token["client_id"] in exclude_clients: raise Exception("Client in excluded clients configuration") if token.get("last_used_at") is None: continue if token["last_used_ip"] in tokens_cleaned: if ( token["last_used_at"] > tokens_cleaned[token["last_used_ip"]]["last_used_at"] ): tokens_cleaned[token["last_used_ip"]]["last_used_at"] = token[ "last_used_at" ] tokens_cleaned[token["last_used_ip"]]["user_id"] = token["user_id"] else: tokens_cleaned[token["last_used_ip"]] = {} tokens_cleaned[token["last_used_ip"]]["last_used_at"] = token[ "last_used_at" ] tokens_cleaned[token["last_used_ip"]]["user_id"] = token["user_id"] except Exception: # Gotta Catch 'Em All pass return users, tokens_cleaned