예제 #1
0
import logging
import logging.config

from docker_secrets import getDocketSecrets
from check_service import checkService
import requests

logger = logging.getLogger()

session = requests.Session()

homeToken = getDocketSecrets("iotcloud_home_token")

url = "https://home.iotcloud.es"


@checkService("Home API")
def checkHome():
    headers = {"Authorization": f"Bearer {homeToken}"}
    requestId = "ff36a3cc-ec34-11e6-b1a0-64510650abcf"
    payload = {
        "requestId": requestId,
        "inputs": [{
            "intent": "action.devices.SYNC"
        }],
    }

    response = session.post(url, json=payload, headers=headers)
    decodedResponse = response.json()

    assert decodedResponse["requestId"] == requestId
예제 #2
0
import logging
import json

import firebase_admin
from firebase_admin import messaging
from docker_secrets import getDocketSecrets

logger = logging.getLogger(__name__)

firebaseCredentials = {
    "type": getDocketSecrets("type"),
    "project_id": getDocketSecrets("project_id"),
    "private_key_id": getDocketSecrets("private_key_id"),
    "private_key": getDocketSecrets("private_key"),
    "client_email": getDocketSecrets("client_email"),
    "client_id": getDocketSecrets("client_id"),
    "auth_uri": getDocketSecrets("auth_uri"),
    "token_uri": getDocketSecrets("token_uri"),
    "auth_provider_x509_cert_url": getDocketSecrets("auth_provider_x509_cert_url"),
    "client_x509_cert_url": getDocketSecrets("client_x509_cert_url"),
}

cred = firebase_admin.credentials.Certificate(firebaseCredentials)
firebase_admin.initialize_app(cred)


def sendLocationNotification(
    locationId,
    notificationTitle,
    notificationBody,
    userToken,
예제 #3
0
파일: weather.py 프로젝트: csanz91/IotCloud
from urllib3 import poolmanager
import time
from dateutil import tz

import datetime

from stations_list import stationsList
from location_list import locationsList
from geocodes_list import geocodesList
from cache import cache_disk
from docker_secrets import getDocketSecrets
import utils

logger = logging.getLogger(__name__)

googleApiKey = getDocketSecrets("googleApiKey")
aemetApiKey = getDocketSecrets("aemetApiKey")

measurements = {
    "temperature": {
        "observationMeasurementName": "ta",
        "predictionMeasurementName": "temperatura",
    },
    "humidity": {
        "observationMeasurementName": "hr",
        "predictionMeasurementName": "humedadRelativa",
    },
}

# Requiered to fix the AEMET cipher
예제 #4
0
class IotCloudApi:

    iotcloudApiUrl = getDocketSecrets("api_url")
    client_id = getDocketSecrets("api_client_id")
    client_secret = getDocketSecrets("api_client_secret")
    auth_url = getDocketSecrets("auth_url")
    audience = getDocketSecrets("api_audience")

    accessToken = ""

    def __init__(self):
        self.token = ""
        self.session = requests.session()

    def getAuthHeader(self):
        headers = {"Authorization": "Bearer " + self.accessToken}
        return headers

    def authenticate(self):

        data = {
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "grant_type": "client_credentials",
            "audience": self.audience,
        }

        result = requests.post(self.auth_url, json=data)

        try:
            decodedResult = result.json()
            self.accessToken = decodedResult["access_token"]
        except (KeyError, TypeError, ValueError):
            logger.error(
                "authenticate: User could NOT be successfully authenticated.")
            return False

        logger.info("authenticate: User authenticated successfully.")
        return True

    def validateResponse(self, response: requests.Response) -> dict:

        assert response.status_code == 200

        try:
            result = response.json()
        except ValueError:
            logger.warning(
                "validateResponse: the response could not be json decoded. Response: %s"
                % response.text)
            raise

        try:
            return result["data"]
        except KeyError:
            return {}

    def get(self, url, auth=False) -> dict:

        headers = self.getAuthHeader() if auth else None

        # First we try to post de data without validating the token,
        # if we get the unauthorized code then we ask for a new token,
        # and if we are not able to get the token after 1 try we abandon
        for numRetries in range(2):
            r = self.session.get(self.iotcloudApiUrl + url,
                                 headers=headers,
                                 timeout=10)
            if r.status_code != requests.codes.unauthorized:
                break

            # Get the auth token
            authenticationResult = self.authenticate()
            if numRetries == 1 or not authenticationResult:
                raise Exception("Could not authenticate")
            # Send again the data with the new token
            headers = self.getAuthHeader()

        return self.validateResponse(r)

    def post(self, url, data, auth=False) -> dict:

        headers = self.getAuthHeader() if auth else None

        # First we try to post de data without validating the token,
        # if we get the unauthorized code then we ask for a new token,
        # and if we are not able to get the token after 1 try we abandon
        for numRetries in range(2):
            r = self.session.post(self.iotcloudApiUrl + url,
                                  json=data,
                                  headers=headers,
                                  timeout=30)
            if r.status_code != requests.codes.unauthorized:
                break

            # Get the auth token
            authenticationResult = self.authenticate()
            if numRetries == 1 or not authenticationResult:
                raise Exception("Could not authenticate")
            # Send again the data with the new token
            headers = self.getAuthHeader()

        return self.validateResponse(r)

    def getSensor(self, locationId, deviceId, sensorId) -> dict:

        sensor = self.get(
            f"locations/{locationId}/devices/{deviceId}/sensors/{sensorId}",
            auth=True)

        return sensor

    def getLocation(self, locationId):

        location = self.get(f"locations/{locationId}/devices", auth=True)

        return location

    def getModulesLocations(self):
        return self.get("locations/modulesEnabled", auth=True)

    def getLocationSunSchedule(self, locationId):

        sunSchedule = self.get(f"locations/{locationId}/sunschedule",
                               auth=True)
        return sunSchedule

    def notifyLocationOffline(self, locationId, locationName):

        data = {
            "notificationTitle": "locationOfflineTitle",
            "notificationBody": "locationOfflineBody",
            "notificationTitleArgs": [locationName],
            "notificationBodyArgs": [locationName],
        }

        self.post(f"locations/{locationId}/locationnotification",
                  data=data,
                  auth=True)
예제 #5
0
import logging
import logging.config

from notifiers import get_notifier
from docker_secrets import getDocketSecrets

logger = logging.getLogger()

TELEGRAM_TOKEN = getDocketSecrets("telegram_token")
TELEGRAM_CHAT_ID = getDocketSecrets("telegram_chat_id")

telegram = get_notifier("telegram")


def sendNotification(message):
    logger.info(message, exc_info=True)
    telegram.notify(
        message=f"[IotCloud]: {message}",
        token=TELEGRAM_TOKEN,
        chat_id=TELEGRAM_CHAT_ID,
        parse_mode="markdown",
    )
예제 #6
0
import logging
import requests
import threading

from docker_secrets import getDocketSecrets
import dbinterface

logger = logging.getLogger(__name__)

googleHomegraphKey = getDocketSecrets("google_homegraph_key")


def resync(db, userId, locationId):
    locationUsers = dbinterface.getLocationUsers(db, locationId)
    if not locationUsers:
        threading.Thread(target=requestResync, args=(userId, )).start()
        return

    ownerUserId = None
    for share in locationUsers:
        threading.Thread(target=requestResync,
                         args=(share["sharedToUserId"], )).start()
        ownerUserId = share["ownerUserId"]
    threading.Thread(target=requestResync, args=(ownerUserId, )).start()


def requestResync(agentUserId):
    logger.info("Requesting resync for the userId: %s" % agentUserId)
    url = ("https://homegraph.googleapis.com/v1/devices:requestSync?key=%s" %
           googleHomegraphKey)
    try:
예제 #7
0
class Auth0Api:
    domain = getDocketSecrets("auth0_domain")
    non_interactive_client_id = getDocketSecrets("auth0_non_interactive_client_id")
    application_client_id = getDocketSecrets("auth0_application_client_id")
    non_interactive_client_secret = getDocketSecrets(
        "auth0_non_interactive_client_secret"
    )
    interactive_client_secret = getDocketSecrets("auth0_interactive_client_secret")
    audience = getDocketSecrets("auth0_audience")
    connection = "Username-Password-Authentication"

    def __init__(self):

        self.initAuth0()
        if not self.token:
            raise ValueError("Could not get the auth token.")

    def getToken(self):
        token = self.tokenManager.client_credentials(
            self.non_interactive_client_id,
            self.non_interactive_client_secret,
            "https://{}/api/v2/".format(self.domain),
        )
        mgmt_api_token = token["access_token"]
        self.token = mgmt_api_token

    def initAuth0(self):
        self.tokenManager = GetToken(self.domain)
        self.databaseManager = Database(self.domain)
        self.getToken()
        self.auth0 = Auth0(self.domain, self.token)

    @autoAuthenticate
    def addUser(self, username, name, password, verifyEmail=False):
        userData = {
            "connection": "Username-Password-Authentication",
            "email": username,
            "name": name,
            "password": password,
            "verify_email": verifyEmail,
        }

        result = self.auth0.users.create(userData)

        try:
            userId = result["user_id"]
        except (KeyError, TypeError):
            logger.error(
                f"It was not possible to add the username: {username}.",
                exc_info=True,
                extra={"area": "users"},
            )
            return
        logger.info(f"User added with id: {userId}",)
        return userId

    @autoAuthenticate
    def deleteUser(self, userId):
        logger.info(f"Deleted user with id: {userId}")
        return self.auth0.users.delete(userId)

    @autoAuthenticate
    def updateUser(self, userId, updatedData):
        """
        {
            "blocked": false,
            "email_verified": false,
            "email": "*****@*****.**",
            "verify_email": false,
            "phone_number": "+199999999999999",
            "phone_verified": false,
            "verify_phone_number": false,
            "password": "******",
            "user_metadata": {},
            "app_metadata": {},
            "connection": "Initial-Connection",
            "username": "******",
            "client_id": "DaM8bokEXBWrTUFCiJjWn50jei6ardyX"
        }
        """

        result = self.auth0.users.update(userId, updatedData)

        try:
            assert result["user_id"]
        except (KeyError, TypeError, AssertionError):
            logger.error(
                "It was not possible to update the user with id: %s." % userId,
                exc_info=True,
                extra={"area": "users"},
            )
            return

        logger.info("Updated user with id: %s" % userId)
        return result

    @autoAuthenticate
    def getUser(self, userId):
        userData = self.auth0.users.get(userId)
        return userData

    def login(self, username, password):

        token = self.tokenManager.login(
            self.application_client_id,
            self.interactive_client_secret,
            username,
            password,
            "",
            "",
            self.audience,
            "password",
        )

        auth_api_token = token["access_token"]
        if username != "*****@*****.**":
            logger.info(f"Loging from user: {username}")
        return auth_api_token

    def recoverPassword(self, username):
        result = self.databaseManager.change_password(
            self.application_client_id, username, self.connection
        )

        logger.info(f"User: {username} requests a new password")
        return result

    def changePassword(self, userId, password):
        result = self.auth0.users.update(userId, {"password": password})
        logger.info(f"User: {userId} requests to change the password")
        return result
예제 #8
0
    M2MLocationActionData,
    M2MLocationDevicesStatusStats,
    M2MLocationDeviceStatus,
    M2MModulesLocations,
)
from mqtt import MqttAuth, MqttAcl, MqttSuperUser
from weather_api import Weather, SunSchedule
from bitcoin.bitcoin_api import BitcoinCurrent, BitcoinHistorical, BitcoinPrice

##############################################
# Configuration
##############################################

cfg = {
    "alg": ["RS256"],
    "audience": getDocketSecrets("auth0_audience"),
    "domain": getDocketSecrets("auth0_full_domain"),
    "jwks_uri": getDocketSecrets("auth0_jwks_uri"),
}

claims = {
    "email_verified": "verified",
    "email": "email",
    "clientID": "id",
    "updated_at": "updated",
    "name": "name",
    "picture": "avatar",
    "user_id": "user_id",
    "nickname": "profile_name",
    "identities": "profiles",
    "created_at": "created",
예제 #9
0
import logging
import logging.config
import time
from json.decoder import JSONDecodeError

from docker_secrets import getDocketSecrets
from check_service import checkService
import mqtt_client
import requests

logger = logging.getLogger()

session = requests.Session()

userId = getDocketSecrets("iotcloud_userId")
locationId = getDocketSecrets("iotcloud_locationId")
deviceId = getDocketSecrets("iotcloud_deviceId")
switchSensorId = "healthcheck_switch"
thermostatSensorId = "healthcheck_thermostat"


def updateSensorTimer(apiToken):

    headers = {"Authorization": f"Bearer {apiToken}"}

    # Turn of the switch for 5 seconds
    now = int(time.time())
    payload = {
        "sensorMetadata": {
            "timer": {
                "initialTimestamp": now,
예제 #10
0
import logging
import logging.config
from json.decoder import JSONDecodeError

from docker_secrets import getDocketSecrets
from check_service import checkService
import requests

logger = logging.getLogger()

session = requests.Session()

userId = getDocketSecrets("iotcloud_userId")


@checkService("Weather")
def checkWeatherData(apiToken):
    headers = {"Authorization": f"Bearer {apiToken}"}

    payload = {
        "postalCode": "44002",
        "measurement": "temperature",
    }

    response = session.post(
        f"https://api.iotcloud.es/api/v1/users/{userId}/weather",
        json=payload,
        headers=headers,
    )
    try:
        decodedResponse = response.json()
예제 #11
0
파일: modules.py 프로젝트: csanz91/IotCloud
def onConnect(mqttclient, userdata, flags, rc):
    logger.info("Connected to the MQTT broker")
    mqttclient.subscribe(updatedLocationTopic)
    with locationsLock:
        for location in locations.values():
            location.subscribe(mqttclient)


logger.info("Starting...")

# IotHub api setup
api = IotCloudApi()

# Setup MQTT client
mqttclient = mqtt.Client(userdata={"api": api})
token = getDocketSecrets("mqtt_token")
mqttclient.username_pw_set(token, "_")
updatedLocationTopic = "v1/+/updatedLocation"

mqttclient.message_callback_add(updatedLocationTopic, onLocationUpdated)
mqttclient.on_connect = onConnect

# Get the locations
modulesLocations = api.getModulesLocations()
for locationData in modulesLocations:
    locationId = locationData["_id"]
    locations[locationId] = Location(locationId, locationData, mqttclient, api)

# Connect
mqttclient.connect("mosquitto")
mqttclient.loop_start()
예제 #12
0
import logging
import logging.config
import random
import ssl
import time

from docker_secrets import getDocketSecrets
import paho.mqtt.client as mqtt
from check_service import checkService

logger = logging.getLogger()

locationId = getDocketSecrets("iotcloud_locationId")
deviceId = getDocketSecrets("iotcloud_deviceId")
mqttToken = getDocketSecrets("iotcloud_mqtt_device_token")
analogSensorId = "healthcheck_analog"
switchSensorId = "healthcheck_switch"

url = "mqtt.iotcloud.es"
mqttHeader = f"v1/{locationId}/{deviceId}/"
switchState = False


def on_connect(client, userdata, flags, rc):
    logger.info(f"Connected with result code: {rc}")
    client.subscribe(mqttHeader + switchSensorId + "/setState")
    client.publish(mqttHeader + "status", "online", retain=True)


def on_disconnect(client, userdata, rc):
    logger.info(f"Disconnected result code: {rc}")
예제 #13
0
import logging
import time

import falcon
import jwt

import api_utils
from api_utils import Roles
import dbinterface
from docker_secrets import getDocketSecrets

logger = logging.getLogger(__name__)
secret = getDocketSecrets("mqtt_auth_secret")


class MqttActions:
    ADDED = "added"
    UPDATED = "updated"
    DELETED = "deleted"


class MqttRoles:
    user = "******"
    device = "Device"
    subdevice = "Subdevice"
    admin = "Admin"


class ACL:
    NO_ACCESS = 0
    READ = 1
예제 #14
0
import logging
import logging.config

from docker_secrets import getDocketSecrets
from check_service import checkService
import requests

logger = logging.getLogger()

session = requests.Session()

iotcloudMail = getDocketSecrets("iotcloud_mail")
iotcloudPassword = getDocketSecrets("iotcloud_password")
iotcloudUserId = getDocketSecrets("iotcloud_userId")

url = "https://api.iotcloud.es/api/v1/login"


@checkService("API")
def login():
    payload = {
        "email": iotcloudMail,
        "password": iotcloudPassword,
    }

    response = session.post(url, json=payload)
    decodedResponse = response.json()
    assert decodedResponse["data"]["userId"] == iotcloudUserId
    token = decodedResponse["data"]["token"]
    return token