def on_post(self, req, resp): try: userId = None name = req.media["name"] lastName = req.media["lastName"] email = req.media["email"] password = req.media["password"] wantUpdates = req.media["wantUpdates"] gdprAcceptance = req.media["gdprAcceptance"] language = req.media["language"] # GDPR is mandatory if not gdprAcceptance: msg = "The GDPR must be accepted in order to enter the platform" resp.media = getResponseModel(False, msg) return # Register user in the auth system userId = self.auth0.addUser(email, name, password) # Register user in the database userId = dbinterface.insertUser( self.db, name, lastName, email, wantUpdates, gdprAcceptance, language, userId=userId, ) except exceptions.Auth0Error as e: logger.error(e.message) logger.error("Req.media: %s" % (req.media)) raise falcon.HTTPBadRequest("Error", e.message) except: logger.error( f"Exception. req.media: {req.media}", exc_info=True, extra={"area": "users"}, ) # If the user has been registered but failed the db operation # then remove it if userId: logger.warning( "The user has been registered in Auth0 but the" "database operation failed", extra={"area": "users"}, ) self.auth0.deleteUser(userId) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, userId)
def on_post(self, req, resp, userId, locationId): try: deviceId = dbinterface.insertDevice( self.db, userId, locationId, req.media.get("deviceVersion"), req.media.get("deviceInternalId"), [json.loads(sensor) for sensor in req.media.get("sensors")], deviceTargetVersion=req.media.get("deviceTargetVersion", None), deviceId=req.media.get("deviceId", None), ) notifyLocationUpdated(self.mqttclient, locationId, MqttActions.UPDATED) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, deviceId)
def on_post(self, req, resp, userId, locationId, deviceId): # First check if the user grantedRole = dbinterface.selectUserLocationRole( self.db, userId, locationId) if grantedRole < api_utils.Roles.viewer: raise falcon.HTTPUnauthorized( "Unauthorized", "The user is not authorized to retrive this data.") try: fromDate = calendar.timegm(parse(req.media["from"]).timetuple()) toDate = calendar.timegm(parse(req.media["to"]).timetuple()) data = influxdb_interface.getDeviceStatus(self.influxdb, locationId, deviceId, fromDate, toDate) processedData = [( calendar.timegm(parse(value["time"]).timetuple()) * 1000, value["status"], ) for value in data] except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, processedData)
def on_put(self, req, resp, userId, locationId, deviceId, sensorId): try: result = dbinterface.updateSensor( self.db, userId, locationId, deviceId, sensorId, req.media.get("sensorName", None), req.media.get("sensorMetadata", None), req.media.get("color", None), req.media.get("orderIndex", None), req.media.get("roomId", None), ) notifySensorUpdated(self.mqttclient, locationId, deviceId, sensorId, MqttActions.UPDATED) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}, deviceId: {deviceId}, sensorId: {sensorId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(result)
def on_get(self, req, resp, userId): try: locations = dbinterface.selectLocations(self.db, userId, True) except: raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True, locations)
def on_get(self, req, resp, userId, locationId, deviceId, sensorId): selectedDatetime = req.get_param_as_datetime("selectedDatetime") if not selectedDatetime: selectedDatetime = datetime.now() timeZoneId = req.get_param("timeZoneId") ( todayLocalMidnightTimestamp, todayLocalEndDayTimestamp, ) = datetime_utils.getDayTimestamps(selectedDatetime, timeZoneId) ( thisWeekLocalMidnightTimestamp, thisWeekLocalEndDayTimestamp, ) = datetime_utils.getThisWeekTimestamps(selectedDatetime, timeZoneId) ( thisMonthLocalMidnightTimestamp, thisMonthLocalEndDayTimestamp, ) = datetime_utils.getThisMonthTimestamps(selectedDatetime, timeZoneId) try: todayStats = influxdb_interface.getStats( self.influxdb, locationId, sensorId, todayLocalMidnightTimestamp, todayLocalEndDayTimestamp, ) thisWeekStats = influxdb_interface.getStats( self.influxdb, locationId, sensorId, thisWeekLocalMidnightTimestamp, thisWeekLocalEndDayTimestamp, ) thisMonthStats = influxdb_interface.getStats( self.influxdb, locationId, sensorId, thisMonthLocalMidnightTimestamp, thisMonthLocalEndDayTimestamp, ) data = { "todayStats": todayStats[0], "thisWeekStats": thisWeekStats[0], "thisMonthStats": thisMonthStats[0], } except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, data)
def on_post(self, req, resp): try: self.verifyPermissions(req) except falcon.HTTPUnauthorized: raise except: logger.error("Exception. params: %s" % (req.params), exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True)
def on_get(self, req, resp, userId, locationId): try: devices = dbinterface.selectDevices(self.db, userId, locationId) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, devices)
def on_get(self, req, resp): try: locations = dbinterface.findModulesLocations(self.db) except: logger.error( "Exception.", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, locations)
def on_get(self, req, resp, userId): try: sensors = dbinterface.selectUserSensors(self.db, userId) except: logger.error( f"Exception. userId: {userId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, sensors)
def on_get(self, req, resp, userId, locationId, deviceId): try: lastSeen = influxdb_interface.getDeviceLastTimeSeen( self.influxdb, locationId, deviceId) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, lastSeen)
def on_get(self, req, resp, locationId): try: location = dbinterface.findLocation(self.db, locationId) except: logger.error( f"Exception. locationId: {locationId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, location)
def on_put(self, req, resp, userId, shareId): try: updatedData = {"role": req.media["newRole"]} result = dbinterface.updateUserLocationShare( self.db, shareId, updatedData) except: logger.error("Exception. userId: %s" % (userId), exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(result)
def on_get(self, req, resp, userId, locationId, deviceId, sensorId): datetimeNow = datetime.utcnow() timestampNow = calendar.timegm(datetimeNow.timetuple()) oneHourAgo = timestampNow - 3600 oneDayAgo = timestampNow - 3600 * 24 try: currentRate = influxdb_interface.getTotalizerCurrentRate( self.influxdb, locationId, sensorId) try: currentRate = currentRate[0]["rate"] except (TypeError, KeyError): currentRate = 0 accumulatedLastHour = influxdb_interface.getHourlyAccumulation( self.influxdb, locationId, sensorId, oneHourAgo, timestampNow) try: accumulatedLastHour = accumulatedLastHour[0]["value"] except (TypeError, KeyError): accumulatedLastHour = 0 accumulatedLastDay = influxdb_interface.getHourlyAccumulation( self.influxdb, locationId, sensorId, oneDayAgo, timestampNow) try: accumulatedLastDay = sum(accumulated["value"] or 0.0 for accumulated in accumulatedLastDay) except (TypeError, KeyError): accumulatedLastDay = 0 trendRate = influxdb_interface.getTotalizerTrendRate( self.influxdb, locationId, sensorId) try: trendRate = [float(value["rate"]) for value in trendRate] except (TypeError, KeyError): trendRate = 0 data = { "currentRate": currentRate, "accumulatedLastHour": accumulatedLastHour, "accumulatedLastDay": accumulatedLastDay, "trendRate": trendRate, } except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, data)
def on_get(self, req, resp, userId, locationId, roomId): try: room = dbinterface.selectRoom(self.db, userId, locationId, roomId) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}, roomId: {roomId}", exc_info=True, extra={"area": "locations"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True, room)
def on_post(self, req, resp): try: token = req.params["username"] tokenData = verifyMqttToken(token) assert tokenData["role"] logger.info( f"Granted MQTT connection to the user with id: {token}") except: logger.error("Exception. params: %s" % (req.params), exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True)
def on_get(self, req, resp, userId): try: token = generateMqttToken(userId, MqttRoles.user) assert token except: logger.error( f"Exception. userId: {userId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, token)
def on_get(self, req, resp, userId): try: pendingShares = dbinterface.getPendingValidateShares( self.db, userId) except: logger.error( f"Exception. userId: {userId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, pendingShares)
def on_get(self, req, resp, userId): try: result = bitcoin_price.getHistoricalPrice() except: logger.error( f"Exception. userId: {userId}", exc_info=True, extra={"area": "bitcoin"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True, result)
def on_delete(self, req, resp, userId, shareId): try: result = dbinterface.deleteUserLocationShare( self.db, userId, shareId) except: logger.error( f"Exception. userId: {userId}.", exc_info=True, extra={"area": "locations"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(result)
def on_post(self, req, resp, userId, locationId): try: result = dbinterface.orderSensors(self.db, userId, locationId, req.media["newSensorsOrder"]) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}, " f"newSensorsOrder: {req.media['newSensorsOrder']}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(result)
def on_delete(self, req, resp, userId, locationId): try: result = dbinterface.deleteLocation(self.db, userId, locationId) notifyLocationUpdated(self.mqttclient, locationId, MqttActions.DELETED) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True, extra={"area": "locations"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(result)
def on_post(self, req, resp): try: token = req.params["username"] tokenData = verifyMqttToken(token) if tokenData["role"] != MqttRoles.admin: raiseUnauthorized() except falcon.HTTPUnauthorized: raise except: logger.error("Exception. params: %s" % (req.params), exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True)
def on_post(self, req, resp, userId): try: # Check we are the user to validate the share firebaseToken = req.media["firebaseToken"] dbinterface.setUserFirebaseToken(self.db, userId, firebaseToken) except: logger.error( f"Exception. req.media: {req.media}", exc_info=True, extra={"area": "users"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True)
def on_get(self, req, resp, userId, locationId): try: userLocations = dbinterface.selectLocations(self.db, userId, includeInherited=True) locationTags = [] deviceTags = [] sensorTags = [] for location in userLocations: # Filter the objects by location if locationId not in ["*", location["_id"]]: continue locationTags.append({ "text": location["locationName"], "value": location["_id"] }) for device in location["devices"]: deviceTags.append({ "text": device["deviceId"], "value": device["deviceId"] }) for sensor in device["sensors"]: if sensor["sensorType"] in ["analog", "thermostat"]: sensorTags.append({ "text": sensor["sensorName"], "value": sensor["sensorId"], }) response = { "locationTags": locationTags, "deviceTags": deviceTags, "sensorTags": sensorTags, } except: logger.error( f"Exception. userId: {userId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, response)
def on_post(self, req, resp, userId): try: response = self.auth0.changePassword(userId, req.media["password"]) except exceptions.Auth0Error as e: logger.error(e.message) logger.error("Req.media: %s" % (req.media)) raise falcon.HTTPBadRequest("Error", e.message) except: logger.error( f"Exception. req.media: {req.media}", exc_info=True, extra={"area": "users"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, response)
def on_post(self, req, resp, userId, locationId, deviceId, sensorId): try: data = influxdb_interface.getHourlyAccumulation( self.influxdb, locationId, sensorId, req.media["initialTimestamp"], req.media["finalTimestamp"], ) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, data)
def on_post(self, req, resp, userId): try: # Check we are the user to validate the share shareId = req.media["shareId"] locationShare = dbinterface.selectShare(self.db, shareId) assert locationShare["sharedToUserId"] == userId dbinterface.validateLocationPermissions(self.db, shareId) except: logger.error( f"Exception. userId: {userId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True)
def on_post(self, req, resp, userId, locationId): # First check if the user grantedRole = dbinterface.selectUserLocationRole( self.db, userId, locationId) if grantedRole < api_utils.Roles.viewer: raise falcon.HTTPUnauthorized( "Unauthorized", "The user is not authorized to retrive this data.") try: fromDate = calendar.timegm(parse(req.media["from"]).timetuple()) toDate = calendar.timegm(parse(req.media["to"]).timetuple()) data = influxdb_interface.getLocationActionsData( self.influxdb, locationId, fromDate, toDate) sensorsNames = getSensorsNames(self.db, userId, locationId) processedData = [] for value in data: try: sensorsName = sensorsNames[value["sensorId"]] except KeyError: continue action = value["state"] if action is None: action = value["setToogle"] processedData.append(( calendar.timegm(parse(value["time"]).timetuple()) * 1000, sensorsName, str(action), )) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, processedData)
def on_post(self, req, resp, userId, locationId): try: otherUserId = dbinterface.findUserIdByEmail( self.db, req.media["email"]) if not otherUserId: raise ValueError( "The email provided doesn't belong to any user.") elif otherUserId == userId: raise ValueError( "The permissions are granted to another user, please use other user's email" ) if dbinterface.existsShare(self.db, otherUserId, userId, locationId): raise ValueError( "The location has already been shared to this user") result = dbinterface.insertUserLocationShare( self.db, otherUserId, userId, locationId, req.media["email"], req.media["role"], ) except ValueError as e: logger.error( "The userId: %s has requested to give location permissions to the following email: %s that is not valid" % (userId, req.media["email"]), extra={"area": "locations"}, ) raise falcon.HTTPBadRequest("Bad Request: Invalid Email", e) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True, extra={"area": "locations"}, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = api_utils.getResponseModel(True, result)