From 94d0bb5b5eefdcdffb324f6385cae45a297e1f2b Mon Sep 17 00:00:00 2001 From: Hansanimadumali Date: Thu, 3 Jun 2021 18:59:19 +0530 Subject: [PATCH] added sim and hub --- README.md | 11 + device-sim/config/config-orig.json | 22 ++ device-sim/config/config.json | 1 + device-sim/index.js | 490 +++++++++++++++++++++++++++++ device-sim/package.json | 21 ++ device-sim/views/home.hbs | 10 + device-sim/views/layouts/main.hbs | 20 ++ device-sim/views/login.hbs | 29 ++ device-sim/views/protected.hbs | 154 +++++++++ hub/config.yaml | 15 + hub/main.py | 129 ++++++++ hub/requirements.txt | 4 + 12 files changed, 906 insertions(+) create mode 100644 README.md create mode 100755 device-sim/config/config-orig.json create mode 100755 device-sim/config/config.json create mode 100755 device-sim/index.js create mode 100755 device-sim/package.json create mode 100755 device-sim/views/home.hbs create mode 100755 device-sim/views/layouts/main.hbs create mode 100755 device-sim/views/login.hbs create mode 100755 device-sim/views/protected.hbs create mode 100755 hub/config.yaml create mode 100755 hub/main.py create mode 100755 hub/requirements.txt diff --git a/README.md b/README.md new file mode 100644 index 0000000..8b7af9a --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# ANS-Research-MS20920272 +ANS Reseach MS20920272 + +## Authentication and Authorization for IoT EdgeDevices + +### Temperature simulator +A NodeJS application which simulates a temperature sensor. It can be refractored to work with Raspberry PI module with package Node Gyp. + + +### IoT hub +A Python application to provide functionalities of a IoT hub. The configurations are in config directory. The program is only supporting Python3. Use pip3 version to install the dependancies needed. Try install the extract packages included in the requirement.txt folder. \ No newline at end of file diff --git a/device-sim/config/config-orig.json b/device-sim/config/config-orig.json new file mode 100755 index 0000000..512e5d8 --- /dev/null +++ b/device-sim/config/config-orig.json @@ -0,0 +1,22 @@ +{ + "user":{ + "username":"admin", + "password":"XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg=" + }, + "device_id":"temp-dev-0", + "hub":{ + "access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIwMUl2bV9mdEZ5ZjZJazBCS2RVaTNDM2FDQmdoVG5MMkZSUk8yNVYzaElJIn0.eyJleHAiOjE1OTM2ODExMTgsImlhdCI6MTU5MzY4MDgxOCwianRpIjoiMjIwYzc3ZGMtZmE1ZC00NDY3LWEzOGUtM2NiNmZhZDlhY2VkIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RlbW8tcmVhbG0iLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiYzQ3ZGY4MmYtZDY1MC00MzQ1LTg5YmEtMTcwN2RlZmU4ZjY1IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiaW90LWh1Yi1weXRob24iLCJzZXNzaW9uX3N0YXRlIjoiODVmYjUyNjEtZjYyMS00NWJjLTk3YzItY2U0MWFhYzdkMTE1IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwOi8vbG9jYWxob3N0OjgwODAiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6InByb2ZpbGUgZW1haWwiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6InNhbW15In0.AsNZcHxVjGaOTEnDI56xSHBBomi4UDP1TiaMnnoZtYB8-RGocgukDmgOCTBROuU_CxJOPrm-pDpVUk2cEbGWUxyLXCO8LlRrPS0_ehj6bGC2MnTuBFgAUzRL36EpLXwTufu4v-tc11p28T_aoR0DVSBl-hbhLvKNWw2UBWWJHNFgtJITyHIv8_595naoGrQA3Ejxi3KIF-cWTHEcOhJvpBgYlu5fwoVMjSlk690mpO0pxVk1_1jOFWipxzVr3uCHIcb0vmJMeau6X3FMwv83ZHVl-PTab0IKFcfCeab07DjRVA8IEN365qWfBKUNGAU-iTuiCqLzOuGbLV5JNVPqSg", + "hub_ip":"localhost", + "hub_port":"1883", + "client_id": "iot-hub-python", + "client_secret": "836be5ba-e8fc-4765-8df6-f1903c30a838", + "auth_user": "sammy", + "auth_password": "password" + }, + "mqtt":{ + "topic":"test", + "username":"sammy", + "password":"password" + } + +} \ No newline at end of file diff --git a/device-sim/config/config.json b/device-sim/config/config.json new file mode 100755 index 0000000..7d64bbc --- /dev/null +++ b/device-sim/config/config.json @@ -0,0 +1 @@ +{"user":{"username":"admin","password":"XohImNooBHFR0OVvjcYpJ3NgPQ1qq73WKhHvch0VQtg="},"device_id":"temp-dev-0","hub":{"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIwMUl2bV9mdEZ5ZjZJazBCS2RVaTNDM2FDQmdoVG5MMkZSUk8yNVYzaElJIn0.eyJleHAiOjE2MjI3NTYyMTgsImlhdCI6MTYyMjcyMDIxOCwianRpIjoiODFkYTZiNTMtMDE5OC00MTJiLWIxOTYtZWUyNzY2YjdlODRmIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RlbW8tcmVhbG0iLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiYzQ3ZGY4MmYtZDY1MC00MzQ1LTg5YmEtMTcwN2RlZmU4ZjY1IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiaW90LWh1Yi1weXRob24iLCJzZXNzaW9uX3N0YXRlIjoiNzAzNDJjZWUtOGI1OS00ZDRjLThmZjUtZDdmMDUzNjdlMWY2IiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwOi8vbG9jYWxob3N0OjgwODAiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIm9mZmxpbmVfYWNjZXNzIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJhY2NvdW50Ijp7InJvbGVzIjpbIm1hbmFnZS1hY2NvdW50IiwibWFuYWdlLWFjY291bnQtbGlua3MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJzYW1teSJ9.E0DOckxLb6jF6H9942_1AQUNoCzj5xHVH4egvVdhw2JPRDDozk-rNKUeH5X2yr8t3mnX9XIL9dIMPaT6fLyDapLR3QWD0H6b00qA3U5LuxBAGYVpWG4pn80hhQbxotOdtEwVQJGWtsn8DgTVSLe-HYIitjT2-_PNnOfuyDCLjGd9xybKQxLjWmKxBsPiPVy6tWqvbij8yp_onKzlAY5QkzzMIUe3OvgOTi-yyRviu-rDLMJksrAXlNHq1nwdXCuDCtuuf6gn6OOA-geSwCp-Wu6cU5ibXHCjzFq2y6Dy2Bxzu8uhkybYci6nav5GW75ysE2x-jyIguQXpZDn73Goug","hub_ip":"localhost","hub_port":"1883","client_id":"iot-hub-python","client_secret":"836be5ba-e8fc-4765-8df6-f1903c30a838","auth_user":"sammy","auth_password":"password"},"mqtt":{"topic":"test","username":"sammy","password":"password"}} \ No newline at end of file diff --git a/device-sim/index.js b/device-sim/index.js new file mode 100755 index 0000000..2db2f78 --- /dev/null +++ b/device-sim/index.js @@ -0,0 +1,490 @@ +const express = require('express'); +const exphbs = require('express-handlebars'); +const cookieParser = require('cookie-parser'); +const bodyParser = require('body-parser'); +const fs = require('fs'); +const mqtt = require('mqtt'); +const https = require('http'); +const cors = require("cors"); +const axios = require('axios'); +const querystring = require('querystring'); +// var sensorLib = require("node-dht-sensor"); + +const crypto = require('crypto'); +const { url } = require('inspector'); +const app = express(); +const authTokens = {}; +var settings = {}; + +const sensor = { + type: 11, + pin: 17 +}; + +const allowedOrigins = ["http://localhost:3000", "http://localhost:8080"]; + +// generate hashed password +const getHashedPassword = (password) => { + const sha256 = crypto.createHash('sha256'); + const hash = sha256.update(password).digest('base64'); + return hash; +} + + +// generate a auth token +const generateAuthToken = () => { + return crypto.randomBytes(30).toString('hex'); +} + + +// read settings +const readSettingsJson = () => { + let changeSettingsStr = fs.readFileSync('config/config.json'); + let changedSettings = JSON.parse(changeSettingsStr); + + if ('user' in changedSettings) { + settings = changedSettings; + } else { + let originalSettingsStr = fs.readFileSync('config/config-orig.json'); + settings = JSON.parse(originalSettingsStr); + } +} + +// write updated settings to file +const updateSettingsJson = () => { + let settingsString = JSON.stringify(settings); + fs.writeFileSync('config/config.json', settingsString); +} + + +// resotre the original settings +const restoreSettings = () => { + let originalSettingsStr = fs.readFileSync('config/config-orig.json'); + settings = JSON.parse(originalSettingsStr); + + fs.writeFileSync('config/config.json', "{}"); +} + + +// To support URL-encoded bodies +app.use(bodyParser.urlencoded({ extended: true })); + +// To parse cookies from the HTTP Request +app.use(cookieParser()); + +app.use((req, res, next) => { + const authToken = req.cookies['AuthToken']; + req.user = authTokens[authToken]; + + next(); +}); + +app.use( + cors({ + "origin": "*", + // function(origin, callback) { + // if (!origin) return callback(null, true); + // if (allowedOrigins.indexOf(origin) === -1) { + // var msg = + // "The CORS policy for this site does not " + + // "allow access from the specified Origin."; + // return callback(new Error(msg), false); + // } + // return callback(null, true); + // }, + "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", + "preflightContinue": false, + "optionsSuccessStatus": 204 + }) +); + +app.engine('hbs', exphbs({ + extname: '.hbs' +})); + +app.set('view engine', 'hbs'); + +////////////////////////////////////////////////////////////////////// +/// Controllers +////////////////////////////////////////////////////////////////////// + +// Our requests hadlers will be implemented here... +app.get('/', function (req, res) { + res.render('home'); +}); + +app.get('/login', (req, res) => { + res.render('login'); +}); + +app.post('/login', (req, res) => { + const { email, password } = req.body; + const hashedPassword = getHashedPassword(password); + + let user = undefined; + + if (settings.user.username === email && hashedPassword === settings.user.password) { + user = settings.user; + } + + if (user) { + const authToken = generateAuthToken(); + + authTokens[authToken] = email; + + res.cookie('AuthToken', authToken); + res.redirect('/protected'); + return; + } else { + res.render('login', { + message: 'Invalid username or password', + messageClass: 'alert-danger' + }); + } +}); + + +app.get('/protected', (req, res) => { + if (req.user) { + res.render('protected', { + settings: settings + }); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}); + + +app.get('/logout', (req, res) => { + if (req.user) { + res.cookie('AuthToken', ""); + res.redirect("/login"); + + } +}) + +app.post('/user/update', (req, res) => { + if (req.user) { + const { password } = req.body; + + if (password == "") { + res.render('protected', { + message: 'Invalid Password', + messageClass: 'alert-danger', + settings: settings + }); + + } else { + settings = { ...settings, user: { ...settings.user, password: getHashedPassword(password) } }; + updateSettingsJson(); + res.render('protected', { + message: 'Successfully updated hub details', + messageClass: 'alert-success', + settings: settings + }); + } + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger', + }); + } +}); + +app.post('/hub/update', (req, res) => { + if (req.user) { + const { hub_ip, hub_port, client_id, client_secret, auth_user, auth_password } = req.body; + settings = { + ...settings, + hub: { + ...settings.hub, + // access_token:access_token, + hub_ip: hub_ip, + hub_port: hub_port, + client_id: client_id, + client_secret: client_secret, + auth_user: auth_user, + auth_password: auth_password + } + } + + updateSettingsJson(); + res.render('protected', { + message: 'Successfully updated hub details', + messageClass: 'alert-success', + settings: settings + }); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}); + +app.get('/hub/update/token', (req, res) => { + if (req.user) { + updateAuthToken2(res); + + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}); + +app.get('/hub/delete/token', (req, res) => { + if (req.user) { + settings = { + ...settings, + hub: { + ...settings.hub, + access_token: "" + } + + } + updateSettingsJson(); + res.render('protected', { + message: 'Successfully updated token', + messageClass: 'alert-success', + settings: settings + }); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}) + +app.post('/mqtt/update', (req, res) => { + if (req.user) { + const { topic, username, password } = req.body; + settings = { + ...settings, + mqtt: { + ...settings.mqtt, + topic: topic, + username: username, + password: password + } + } + + updateSettingsJson(); + res.render('protected', { + message: 'Successfully updated hub details', + messageClass: 'alert-success', + settings: settings + }); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}); + + +app.post('/device/update', (req, res) => { + if (req.user) { + const { device_id } = req.body; + settings = { + ...settings, + device_id: device_id + } + + updateSettingsJson(); + res.render('protected', { + message: 'Successfully updated hub details', + messageClass: 'alert-success', + settings: settings + }); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}); + +app.get('/restore', (req, res) => { + if (req.user) { + restoreSettings(); + res.redirect("/login"); + } else { + res.render('login', { + message: 'Please login to continue', + messageClass: 'alert-danger' + }); + } +}) + + +// READ settings + +readSettingsJson(); + + +/////////////////////////////////////////////////////////////////////// +///// MQTT +/////////////////////////////////////////////////////////////////////// + + +function getRandomArbitrary(min, max) { + return Math.random() * (max - min) + min; +} + +// function readSensorData() { +// // https://www.npmjs.com/package/node-dht-sensor +// var readout = sensorLib.read( +// sensor.type, +// sensor.pin +// ); + +// return readout; +// } + +function publish_temp(mqttClient, accessToken, topic) { + let temp = parseInt(getRandomArbitrary(200, 300)) / 10; + // let readOutValue = readSensorData(); + // let temp = readOutValue.temperature.toFixed(1); + // let humid = readOutValue.humidity.toFixed(1); + let humid = parseInt(getRandomArbitrary(200, 300)) / 10; + + + tempObj = { + payload: { + temperature: temp, + humidity: humid + }, + authToken: accessToken + }; + + mqttClient.publish(topic, JSON.stringify(tempObj)); +} + +options = { + cliendId: settings.device_id, + username: settings.mqtt.username, + password: settings.mqtt.password, +} +console.log(options) +let mqttClient = mqtt.connect('mqtt://' + settings.hub.hub_ip, options) + +mqttClient.on('connect', function (err) { + console.log("Connected to broker"); + + setInterval(() => { + publish_temp(mqttClient, settings.hub.access_token, settings.mqtt.topic); + }, 2000); + +}) + +/////////////////////////////////////////////////////////////////////// +///// Auth tokens +/////////////////////////////////////////////////////////////////////// + +function updateAuthToken(response) { + let form = { + client_id: settings.hub.client_id, + client_secret: settings.hub.client_secret, + grant_type: "password", + scope: "openid", + username: settings.hub.auth_user, + password: settings.hub.auth_password + } + + console.log(form); + + let options = { + // host: settings.hub.hub_ip, + host: "localhost", + port: 8080, + // headers: { + // 'Content-Type': 'application/x-www-form-urlencoded', + // }, + // path: "/auth/realms/demo-realm/protocol/openid-connect/token", + path: "/auth/", + method: "GET", + // form: form + } + + + try { + https.request(options, function (err, res, success) { + updateSettingsJson(); + console.log("hello"); + response.render('protected', { + message: 'Successfully updated token', + messageClass: 'alert-success', + settings: settings + }); + }); + } catch (e) { + console.log(e); + } + +} + + +function updateAuthToken2(response) { + const form = { + client_id: settings.hub.client_id, + client_secret: settings.hub.client_secret, + grant_type: "password", + scope: "openid", + username: settings.hub.auth_user, + password: settings.hub.auth_password + } + const configSend = { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } + } + + axios.post( + "http://" + settings.hub.hub_ip + ":8080/auth/realms/demo-realm/protocol/openid-connect/token", + querystring.stringify(form), + configSend + ) + .then(res => { + let accessToken = res.data.access_token; + + console.log(accessToken); + settings = { + ...settings, + hub: { + ...settings.hub, + access_token: accessToken + } + + } + updateSettingsJson(); + response.render('protected', { + message: 'Successfully updated token', + messageClass: 'alert-success', + settings: settings + }); + }) + .catch(err => { + console.log(err); + response.render('protected', { + message: 'Failed to update token', + messageClass: 'alert-danger', + settings: settings + }); + }) +} + + +/////////////////////////////////////////////////////////////////////// +///// Initiate Server +/////////////////////////////////////////////////////////////////////// + + +app.listen(3000); +console.log("Server Listen on 127.0.0.1:3000"); \ No newline at end of file diff --git a/device-sim/package.json b/device-sim/package.json new file mode 100755 index 0000000..fca38f0 --- /dev/null +++ b/device-sim/package.json @@ -0,0 +1,21 @@ +{ + "name": "device-simulator", + "version": "1.0.0", + "description": "An IoT Temperature Edge Device Simulator", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "MIT", + "dependencies": { + "axios": "^0.21.1", + "body-parser": "^1.19.0", + "cookie-parser": "^1.4.5", + "cors": "^2.8.5", + "express": "^4.17.1", + "express-handlebars": "^4.0.4", + "mqtt": "^4.1.0", + "query-string": "^6.13.1" + } +} diff --git a/device-sim/views/home.hbs b/device-sim/views/home.hbs new file mode 100755 index 0000000..ebf5c6d --- /dev/null +++ b/device-sim/views/home.hbs @@ -0,0 +1,10 @@ + +
+
+
+

Temperature Edge Device Simulator

+
+ Login +
+ +
\ No newline at end of file diff --git a/device-sim/views/layouts/main.hbs b/device-sim/views/layouts/main.hbs new file mode 100755 index 0000000..5d680b7 --- /dev/null +++ b/device-sim/views/layouts/main.hbs @@ -0,0 +1,20 @@ + + + + + + Document + + + + + +
+ {{{body}}} +
+ + + + + + diff --git a/device-sim/views/login.hbs b/device-sim/views/login.hbs new file mode 100755 index 0000000..5589bd6 --- /dev/null +++ b/device-sim/views/login.hbs @@ -0,0 +1,29 @@ + + + +
+
+ + {{#if message}} + + {{/if}} + + +
+
+ + +
+
+ + +
+ +
+ +
+
\ No newline at end of file diff --git a/device-sim/views/protected.hbs b/device-sim/views/protected.hbs new file mode 100755 index 0000000..d944cf8 --- /dev/null +++ b/device-sim/views/protected.hbs @@ -0,0 +1,154 @@ + + {{#if message}} + +{{/if}} + +
+ +
+
+
User Details
+ +
+
+ + +
+ +
+ + +
+ + +
+
+
+ + +
+
+
Hub Details
+ +
+
+ + +
+ +
+ + +
+ + {{!--
+ + +
--}} + + +
+ + +
+ +
+ + +
+ +
+ + +
+ + +
+ + +
+ + + +
+ +
+
+ + +
+
+ +
+
+
+ +
+
+ +
+
+ +
+
+
+
+
+ + + +
+
+
Mqtt Details
+ +
+
+ + +
+ +
+ + +
+ +
+ + +

Current topic : {{settings.mqtt.topic}}/{{settings.device_id}}

+
+ + +
+
+
+ + +
+
+
Device Details
+ +
+ +
+ + +
+ + +
+
+
+ +
\ No newline at end of file diff --git a/hub/config.yaml b/hub/config.yaml new file mode 100755 index 0000000..7cba7f4 --- /dev/null +++ b/hub/config.yaml @@ -0,0 +1,15 @@ +mqtt: + ip: localhost + port: 1883 + topic: test + username: sammy + password: password + client_name: hub0 + +auth_server: + client_id: iot-hub-python + client_secret: 836be5ba-e8fc-4765-8df6-f1903c30a838 + realm_name: demo-realm + server_url: localhost + server_port: 8080 + \ No newline at end of file diff --git a/hub/main.py b/hub/main.py new file mode 100755 index 0000000..b2e1e9a --- /dev/null +++ b/hub/main.py @@ -0,0 +1,129 @@ +import yaml +import paho.mqtt.client as mqtt +import time +import keycloak +import json + +connectedBroker = False +coonectedAuth = False + +# read configuration files +def readConfig(): + file = open('config.yaml','r') + cfg = yaml.load(file) + return cfg + + + +# read yaml configurations +settings = readConfig() + +# +++++++++++++++++++++++++++++++++++++++++++++++++++++ +# Auth flow +# +++++++++++++++++++++++++++++++++++++++++++++++++++++ + +server_url="http://"+settings["auth_server"]["server_url"]+":"+str(settings["auth_server"]["server_port"])+"/auth/" + +print("Connecting to "+server_url) + +# Configure client +keycloak_openid = keycloak.KeycloakOpenID(server_url=server_url, + client_id=settings["auth_server"]["client_id"], + realm_name=settings["auth_server"]["realm_name"], + client_secret_key=settings["auth_server"]["client_secret"]) +config_well_know = keycloak_openid.well_know() + +KEYCLOAK_PUBLIC_KEY = keycloak_openid.public_key() +optionsAccessToken = {"verify_signature": True, "verify_aud": True, "exp": True} + +def verifyToken(token): + token_info = keycloak_openid.introspect(token) + # token_info = keycloak_openid.decode_token(token, key=KEYCLOAK_PUBLIC_KEY, options=optionsAccessToken) + return token_info + +###################################################### +## MQTT Callbacks +###################################################### + + +def on_message(client, userdata, message): + # print("message received", str(message.payload.decode("utf-8"))) + print("message topic=",message.topic) + print("message qos=",message.qos) + # print("message retain flag=",message.retain) + + payload = str(message.payload.decode("utf-8")) + jsonAcceptableString = payload.replace("'","\"") + jsonPayload = json.loads(jsonAcceptableString) + + # Introspect Token + token_info = verifyToken(jsonPayload["authToken"]) + print(token_info[u'active']) + if(token_info[u'active']): + print("++++++++++ Authenticated Data ++++++++++++++++++") + print(jsonPayload["payload"]) + else: + print("---------- Unauthenticated Data ----------------") + +def on_connect(client, userdata, flags, rc): + print(rc) + if rc == 0: + print("Connected to broker") + connectedBroker = True #Signal connection + client.subscribe(settings["mqtt"]["topic"]) + else: + print("Connection failed") + +def on_subscribe(topic): + print("Subscribing to topic :" + topic) + + +###################################################### +## Main flow +###################################################### + + + +# +++++++++++++++++++++++++++++++++++++++++++++++++++++ +# MQTT flow +# +++++++++++++++++++++++++++++++++++++++++++++++++++++ + +# setting up mqtt client +client = mqtt.Client(settings["mqtt"]["client_name"]) +client.username_pw_set(settings["mqtt"]["username"],settings["mqtt"]["password"]) + +client.loop_start() + +# callbacks +client.on_connect= on_connect + +client.connect(settings["mqtt"]["ip"],port=settings["mqtt"]["port"]) +print("Waiting for connection for "+settings["mqtt"]["ip"]+"....") + + +client.on_subscribe = on_subscribe +client.on_message=on_message + +# connection waiting loop +while connectedBroker != True: #Wait for connection + time.sleep(1) + +# main waiting loop +try: + while True: + time.sleep(1) + +except KeyboardInterrupt: + print("Existing") + client.disconnect() + client.loop_stop() + + + + + + + + + + diff --git a/hub/requirements.txt b/hub/requirements.txt new file mode 100755 index 0000000..d11079f --- /dev/null +++ b/hub/requirements.txt @@ -0,0 +1,4 @@ +PyYAML 5.3.1 +paho-mqtt 1.5.0 +python-keycloak-client 0.2.3 +python-keycloak 0.25.0 \ No newline at end of file