Commit 5b630875 by Chavee Issariyapat

reverse content to revision 58b6cecc which is using on k8s

parent 267dea68
...@@ -9,15 +9,11 @@ RUN apk add --update --no-cache python \ ...@@ -9,15 +9,11 @@ RUN apk add --update --no-cache python \
py-pip \ py-pip \
yarn \ yarn \
openssh-client \ openssh-client \
git \ && rm -rf /var/cache/apk/*
&& rm -rf /var/cache/apk/*
COPY . . COPY . .
RUN npm install RUN npm install
RUN apk del git \
&& rm -rf /var/cache/apk/*
EXPOSE 40000 EXPOSE 40000
CMD npm start CMD npm start
var config = require('config'); var config = require('config');
// https://github.com/isaacs/node-lru-cache // https://github.com/isaacs/node-lru-cache
var LRU = require("lru-cache"), var LRU = require("lru-cache") ,
cache = LRU({ cache = LRU({
max: 500, max: 500,
maxAge: 1000 * 60 * 5 maxAge: 1000 * 60 * 5
}); });
// for testing
function authCheck(client_id, username, topic, callback) {
callback(true);
}
module.exports = function (options = {}) { module.exports = function(options={}) {
return function (req, res, next) { return function(req, res, next) {
if (req.header('vernemq-hook') == 'auth_on_publish' && req && req.body) { if (req.header('vernemq-hook') == 'auth_on_publish' && req && req.body) {
if (options.debug) { if (options.debug) {
...@@ -18,57 +23,29 @@ module.exports = function (options = {}) { ...@@ -18,57 +23,29 @@ module.exports = function (options = {}) {
var authstatus; var authstatus;
var topic = req.body.topic; var topic = req.body.topic;
var cachekey = 'pub:' + req.body.client_id + ':' + req.body.username + ':' + topic; var cachekey = 'pub:'+req.body.client_id +':'+ req.body.username+':'+topic;
var authstatus = cache.get(cachekey); var authstatus = cache.get(cachekey);
if (typeof (authstatus) === 'undefined') {
cache.set(cachekey, true); // cache missed
}
var response
var decoded = require('jwt-verify').verify(req.body.username).res
if (decoded) { if (typeof(authstatus)=='undefined') {
if (decoded.role === 'realtimedb') response = { 'result': 'ok' } // cache missed
else response = { 'result': 'no' } authCheck(req.body.client_id, req.body.username, topic, function(result) {
res.send(response); cache.set(cachekey, result);
next(); res.send({
"result": result?"ok":"no"
});
});
} }
else { else {
var GGID = require('./utils/getGroupID'); res.send({
"result": authstatus?"ok":"no"
var output = {};
GGID.getGroupID(req.body.username, req.body.client_id, function (group) {
if (group) {
var _ftopic = require('./utils/router').rewriteTopic(topic, 'pub', group, req.body.client_id, output); // get topic where concat with groupID
response = {
'result': 'ok',
'modifiers': {
'topic': _ftopic,
'qos': 0,
'retain': false
}
}
if (options.debug) {
console.log(response);
}
if (output.verb == 'get' || output.verb == 'read') {
response.modifiers.payload = Buffer.from(req.body.client_id).toString('base64');
}
res.send(response);
next();
}
else {
res.send({ "result": "no" });
next();
}
}); });
} }
next();
} }
else { else {
res.send({ "result": "no" }); res.send({
"result": "no"
});
next(); next();
} }
} }
......
var validator = require('./validator');
var config = require('config'); var config = require('config');
// var seneca = require('seneca')({log: 'silent'}).client({ port: config.get('device_registry_port'), host: config.get('device_registry_host') });
var seneca = require('seneca')({ log: 'silent' }).client({ port: config.get('token_registry_port'), host: config.get('token_registry_host') });
// https://github.com/isaacs/node-lru-cache // https://github.com/isaacs/node-lru-cache
var LRU = require("lru-cache"), var LRU = require("lru-cache") ,
cache = LRU({ cache = LRU({
max: 500, max: 500,
maxAge: 1000 * 60 * 5 maxAge: 1000 * 60 * 5
}); });
var debug = false;
// var authclient = require('seneca')({ log: 'silent' })
// .client({ port: config.get('authserv_port'), host: config.get('authserv_host') });
var authclient = require('seneca')({log: 'silent'})
.client({port: config.get('authserv_port'), host: config.get('authserv_host')});
// for testing
function authCheck(client_id, token, password, callback) { function authCheck(client_id, token, password, callback) {
const util = require('util')
// console.log(util.inspect(myObject, false, null, true));
// console.log('jwt-result:' + util.inspect(require('jwt-verify').verify(token), false, null, true))
if (require('jwt-verify').verify(token).res) { // auth realtimedb by token
callback(true);
}
else {
console.log('token :' + token)
seneca.act('ms:tokenregistry, cmd:getAttributes, type:device, tokencode:' + token, function (err, res) {
console.log('result : ' + util.inspect(res.result, false, null, true))
if (res.result) {
var token_profile = (res && res.result && res.result[0]) ? res.result[0] : {};
var mqttauth = {
clientid: client_id,
token: token,
password: password
};
console.log(util.inspect(validator.auth_connect(mqttauth, token_profile), false, null, true))
callback(validator.auth_connect(mqttauth, token_profile).status);
}
else {
callback(false);
}
});
// seneca.act('cmd:getAccessTokenInfo, tokencode:'+token, function(err,res) {
// if (!err && res) {
// var token_profile = (res&&res.result&&res.result[0])?res.result[0]:{};
// var mqttauth = {
// clientid : client_id,
// token : token,
// password : password
// };
// callback( validator.auth_connect(mqttauth, token_profile) );
// }
// else {
// callback(false);
// }
// });
// authclient.act({ role: 'auth', cmd: 'token', action: 'info', token: token }, function (err, res) { // auth client device by query from db
// if (debug) {
// console.log("res ------>\n");
// console.log(res);
// }
// if (res && res.data) { authclient.act({role:'auth',cmd:'token',action:'info',token: token}, function(err, res) {
// try { if (res && res.data) {
// var jdata = JSON.parse(res.data); callback(true);
// if (jdata && jdata.code == 200) { }
// callback(true); else {
// } callback(false);
// else callback(false); }
// } catch (e) { });
// callback(false);
// }
// callback(true);
// }
// else {
// callback(false);
// }
// });
}
} }
module.exports = function (options = {}) { module.exports = function(options={}) {
return function(req, res, next) {
debug = options.debug || false;
return function (req, res, next) {
if (req.header('vernemq-hook') == 'auth_on_register' && req && req.body) { if (req.header('vernemq-hook') == 'auth_on_register' && req && req.body) {
if (debug) { if (options.debug) {
console.log('auth_on_register-------------'); console.log('auth_on_register-------------');
console.log(req.body); console.log(req.body);
} }
var cachekey = 'auth:' + req.body.client_id + ':' + req.body.username + ':' + req.body.password; var cachekey = 'auth:'+req.body.client_id +':'+ req.body.username +':'+ req.body.password;
var authstatus = cache.get(cachekey); var authstatus = cache.get(cachekey);
if (typeof (authstatus) == 'undefined') { if (typeof(authstatus)=='undefined') {
// cache missed // cache missed
authCheck(req.body.client_id, req.body.username, req.body.password, function (result) { authCheck(req.body.client_id, req.body.username, req.body.password, function(result) {
cache.set(cachekey, result); cache.set(cachekey, result);
res.send({ res.send({
"result": result ? "ok" : "no" "result": result?"ok":"no"
}); });
}); });
} }
else { else {
res.send({ res.send({
"result": authstatus ? "ok" : "no" "result": authstatus?"ok":"no"
}); });
} }
next(); next();
......
var config = require('config'); var config = require('config');
// https://github.com/isaacs/node-lru-cache // https://github.com/isaacs/node-lru-cache
var LRU = require("lru-cache"), var LRU = require("lru-cache") ,
cache = LRU({ cache = LRU({
max: 500, max: 500,
maxAge: 1000 * 60 * 5 maxAge: 1000 * 60 * 5
}); });
module.exports = function (options = {}) { // for testing
return function (req, res, next) { function authCheck(client_id, token, topic, callback) {
callback(true);
}
if (options.debug) { module.exports = function(options={}) {
console.log('auth_on_subscribe-------------'); return function(req, res, next) {
console.log(req.body);
}
if (req.header('vernemq-hook') == 'auth_on_subscribe' && req && req.body) { if (req.header('vernemq-hook') == 'auth_on_subscribe' && req && req.body) {
if (options.debug) {
console.log('auth_on_subscribe-------------');
console.log(req.body);
}
var authstatus; var authstatus;
var topic = req.body.topics[0].topic; var topic = req.body.topics[0].topic;
var cachekey = 'sub:' + req.body.client_id + ':' + req.body.username + ':' + topic; var cachekey = 'sub:'+req.body.client_id +':'+ req.body.username+':'+topic;
var authstatus = cache.get(cachekey); var authstatus = cache.get(cachekey);
if (typeof (authstatus) == 'undefined') {
cache.set(cachekey, true); // cache missed
}
var response
var decoded = require('jwt-verify').verify(req.body.username).res
if (decoded) { if (typeof(authstatus)=='undefined') {
if (decoded.role === 'realtimedb') response = { 'result': 'ok' } // cache missed
else response = { 'result': 'no' } authCheck(req.body.client_id, req.body.username, topic, function(result) {
res.send(response); cache.set(cachekey, result);
next(); res.send({
"result": result?"ok":"no"
});
});
} }
else { else {
var GGID = require('./utils/getGroupID'); res.send({
"result": authstatus?"ok":"no"
GGID.getGroupID(req.body.username, req.body.client_id, function (group) {
if (group) {
var _ftopic = require('./utils/router').rewriteTopic(topic, 'sub', group, req.body.client_id) // get topic where concat with groupID
var _topic = [{ // setTopic for response
'topic': _ftopic,
'qos': 0
}]
response = {
'result': 'ok',
'topics': _topic
}
if (options.debug) {
console.log(response);
}
res.send(response);
next();
}
else {
res.send({ "result": "no" });
next();
}
}); });
} }
next();
} }
else { else {
res.send({ "result": "no" }); res.send({
"result": "no"
});
next(); next();
} }
} }
......
{ {
"authserv_host" : "AUTH_SERVICE_HOST", "authserv_host" : "AUTH_SERVICE_HOST",
"authserv_port" : "AUTH_SERVICE_PORT", "authserv_port" : "AUTH_SERVICE_PORT"
}
"device_registry_host" : "DEVICE_REGISTRY_HOST",
"device_registry_port" : "DEVICE_REGISTRY_PORT",
"token_registry_host" : "TOKEN_REGISTRY_HOST",
"token_registry_port" : "TOKEN_REGISTRY_PORT",
"auth_on_register_debug" : "AUTH_ON_REGISTER_DEBUG",
"auth_on_publish_debug" : "AUTH_ON_PUBLISH_DEBUG",
"auth_on_subscribe_debug" : "AUTH_ON_SUBSCRIBE_DEBUG",
"on_publish_debug" : "ON_PUBLISH_DEBUG",
"on_deliver_debug" : "ON_DELIVER_DEBUG",
"on_unsubscribe_debug" : "ON_UNSUBSCRIBE_DEBUG",
"on_offline_debug" : "ON_OFFLINE_DEBUG"
}
\ No newline at end of file
{
"device_registry_host" : "127.0.0.1",
"device_registry_port" : 8990,
"auth_on_register_debug" : false,
"auth_on_publish_debug" : false,
"auth_on_subscribe_debug" : false,
"on_publish_debug" : false,
"on_deliver_debug" : false,
"on_unsubscribe_debug" : false,
"on_offline_debug" : false
}
{ {
"authserv_host" : "203.151.51.4", "authserv_host" : "203.154.135.231",
"authserv_port" : 31081, "authserv_port" : 31088
"pubca": "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0oW2b1az7MLTRBQojy8e\nYTmVUcbrHBykyMZCkwt4OdL/4zD6jhOmE9JMr3NfRxEJ2BVj7gasEH2h/mpNRtSK\nHjKsgmFWt22QR/TNwNu7AHUiu+7pxyeOz6IDW9bzrptwwwvFz8wc0oKah6fs0cNY\n/Ln5QwY5CWpGJmHF5BOFE5R9PjC3bY2roKwDbKiw4Kx1rbRxwbSzvFGtBMVyK0Rv\nJpWEN6wTEesAI/bLkPth712zfY/PXFi9Vei/gcLxptceISj/o+PUZm4F6u+rHGGt\nOlcBI8lKiCBO8bggmGgpGCZ1fomj5pOPfInl/6Nn4X0gk/4s0MB7zuhBv45zxF8J\ntbzqQ9TVPdUewMtR5UWoPMGiGt6ZOYRAAmGYSWCsa7hD3plcg0NXYXVuLinyxmgd\nKUv0JmmDqWdkNme9W6m42Jb/zEACcneIIVgUeDkadYaJSjY05d2gn/Vn24f0hqp2\nSQ41fYBxw8eKUJLBNo2c9l+Vz7w/dln4cqI/hatXqOVvLml3CKBGwT9hFjufVTpr\nX5WgDzAxGAl0kO0IucInL/XROezsVcxhyJ2dp44KPOoSIUW8dFz7HNq4t9ENzcPV\nvYfvyS0l00p+ivaqT9iV53Ash6f+tHOR5arTNsuM3DHTi3Fi6qIhXSW5qGUl401c\nzSaVroFHIeQI0ZcTxzAOvS0CAwEAAQ==\n-----END PUBLIC KEY-----",
"device_registry_host" : "127.0.0.1",
"device_registry_port" : 8080
} }
{
"device_registry_host" : "alpha.nexpie.io",
"device_registry_port" : 8990,
"token_registry_host" : "alpha.nexpie.io",
"token_registry_port" : 8790,
"auth_on_register_debug" : true,
"auth_on_publish_debug" : true,
"auth_on_subscribe_debug" : true,
"on_publish_debug" : true,
"on_deliver_debug" : true,
"on_unsubscribe_debug" : true,
"on_offline_debug" : true
}
process.env["NODE_ENV"] = "development";
process.env["NODE_CONFIG_DIR"] = __dirname + "/config/"; process.env["NODE_CONFIG_DIR"] = __dirname + "/config/";
var config = require('config');
var auth_on_register_debug = config.get('auth_on_register_debug');
var auth_on_publish_debug = config.get('auth_on_publish_debug');
var auth_on_subscribe_debug = config.get('auth_on_subscribe_debug');
var on_publish_debug = config.get('on_publish_debug');
var on_deliver_debug = config.get('on_deliver_debug');
var on_unsubscribe_debug = config.get('on_unsubscribe_debug');
var on_offline_debug = config.get('on_offline_debug');
var restify = require('restify'); var restify = require('restify');
var auth_on_register = require('./auth_on_register')({ debug: auth_on_register_debug }); var auth_on_register = require('./auth_on_register')({debug:true});
var auth_on_publish = require('./auth_on_publish')({ debug: auth_on_publish_debug }); var auth_on_publish = require('./auth_on_publish')({debug:true});
var auth_on_subscribe = require('./auth_on_subscribe')({ debug: auth_on_subscribe_debug }); var auth_on_subscribe = require('./auth_on_subscribe')({debug:true});
var on_publish = require('./on_publish')({ debug: on_publish_debug }); var on_publish = require('./on_publish')({debug:true});
var on_deliver = require('./on_deliver')({ debug: on_deliver_debug });
var on_unsubscribe = require('./on_unsubscribe')({ debug: on_unsubscribe_debug });
var on_offline = require('./on_offline')({ debug: on_offline_debug });
const server = restify.createServer({ const server = restify.createServer({
name: 'authhook', name: 'authhook',
version: '1.0.1', version: '1.0.0',
}); });
const port = 40000; const port = 40000;
...@@ -28,7 +17,7 @@ server.use(restify.plugins.bodyParser()); ...@@ -28,7 +17,7 @@ server.use(restify.plugins.bodyParser());
// for testing // for testing
function authByUserPasswd(client_id, username, password) { function authByUserPasswd(client_id, username, password) {
if (!client_id || !username || !password) return false; if (!client_id || !username || !password) return false;
else return true; else return true;
} }
...@@ -39,15 +28,7 @@ server.get('/about', function (req, res, next) { ...@@ -39,15 +28,7 @@ server.get('/about', function (req, res, next) {
server.post('/authreg', auth_on_register); server.post('/authreg', auth_on_register);
server.post('/authpub', auth_on_publish); server.post('/authpub', auth_on_publish);
server.post('/authsub', auth_on_subscribe); server.post('/authsub', auth_on_subscribe);
server.post('/onsub', (req, res, next) => { server.post('/onpub', on_publish);
console.log(req.body)
res.send('')
})
server.post('/onunsub', on_unsubscribe)
server.post('/ondeliver', on_deliver)
server.post('/onpub', on_publish)
server.post('/onoff', on_offline)
server.post('/ongone', on_offline)
server.listen(port, function () { server.listen(port, function () {
console.log('%s listening at %s', server.name, server.url); console.log('%s listening at %s', server.name, server.url);
......
var modify = require('./utils/modify');
module.exports = function(options = {}) {
return function (req, res, next) {
console.log('----on_deliver-----')
var topics = modify.removeTempWordInTopic(req.body.topic)
console.log(req.body)
// console.log(topics)
var response = {
'result': 'ok',
'modifiers': {
"topic": topics
}
}
console.log(response);
res.send(response)
}
module.exports.on_deliver = on_deliver
function joinTopic(topics) {
var topic = topics.split('/!')[1]
return topics.split('/!')[0] + topic.substring(topic.indexOf('/'), topic.length)
}
}
module.exports = function(options = {}) {
return function (req, res, next) {
doRedis()
}
function doRedis() {
}
}
\ No newline at end of file
...@@ -14,7 +14,7 @@ module.exports = function(options={}) { ...@@ -14,7 +14,7 @@ module.exports = function(options={}) {
console.log('on_publish-------------'); console.log('on_publish-------------');
console.log(req.body); console.log(req.body);
} }
console.log(req.body)
var topic = req.body.topic; var topic = req.body.topic;
var cachekey = 'pub:'+req.body.client_id +':'+ req.body.username+':'+topic; var cachekey = 'pub:'+req.body.client_id +':'+ req.body.username+':'+topic;
......
module.exports = function(options = {}) {
return function (req, res, next) {
console.log('------on unsubscribe-------')
console.log(req.body)
var topic = req.body.topics[0];
var token = req.body.username
var client_id = req.body.client_id
var response
var decoded = require('jwt-verify').verify(token).res
if (decoded) {
if (decoded.role === 'realtimedb') {
response = { 'result': 'ok' }
}
else response = { 'result': 'no' }
res.send(response);
next()
}
else {
var GGID = require('./utils/getGroupID');
GGID.getGroupID(token, client_id, function(group) {
if (group) {
var _ftopic = require('./utils/router').rewriteTopic(topic, 'unsub', group, client_id)
response = {
"result": "ok",
"topics": [_ftopic]
}
}
else response = { 'result': 'no' }
if (options.debug) {
console.log('on_unsubscribe-------------');
console.log(response);
}
res.send(response);
next()
});
}
}
}
...@@ -4,21 +4,14 @@ ...@@ -4,21 +4,14 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node index.js", "start": "node index.js"
"test": "mocha"
}, },
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"config": "^1.30.0", "config": "^1.30.0",
"jsonwebtoken": "^8.3.0",
"jwt-verify": "git+https://nexpienpm:CCqLQjg4ytvzN7QbssUV@dev.nexpie.com/npm/jwt-verify.git",
"lru-cache": "^4.1.3", "lru-cache": "^4.1.3",
"restify": "^7.1.1", "restify": "^7.1.1",
"seneca": "^3.6.0", "seneca": "^3.6.0"
"util": "^0.11.0"
},
"devDependencies": {
"mocha": "^5.2.0"
} }
} }
REGISTRY_HOST=dock.nexpie.com REGISTRY_HOST=dock.nexpie.com
GROUPNAME=stack GROUPNAME=stack
PROJECTNAME=vernemq/authhook PROJECTNAME=vernemq/authhook
RELEASE=1.0.0 RELEASE=1.0.1kb
var assert = require('assert')
var getTopic = require('../utils/router').rewriteTopic
describe('GetTopic', () => {
describe('realtime msg', () => {
it('should return topic that id_group have insert between @msg and topic', () => {
var topic = '@msg/any/light'
var id_group = 'bulb'
var tgConcat = '@msg/!bulb/any/light'
var _topic = getTopic(topic, id_group)
assert.equal(_topic, tgConcat)
})
})
describe('shadow', () => {
describe('update pub', () => {
it('should return topic that id have insert between @shadow/update and topic', () => {
var topic = '@shadow/update/any/light'
var id = 'd4484cdb-a47a-4936-bcfd-33c1af39b857'
var tgConcat = '@shadow/update/!d4484cdb-a47a-4936-bcfd-33c1af39b857/any/light'
var _topic = getTopic(topic, id)
assert.equal(_topic, tgConcat)
})
})
describe('update sub', () => {
it('should return topic that id have insert behind @shadow/updated', () => {
var topic = '@shadow/updated'
var id = 'd4484cdb-a47a-4936-bcfd-33c1af39b857'
var tgConcat = '@shadow/updated/!d4484cdb-a47a-4936-bcfd-33c1af39b857'
var _topic = getTopic(topic, id)
assert.equal(_topic, tgConcat)
})
})
describe('get pub', () => {
it('should return topic that id have insert between @shadow/get and topic', () => {
var topic = '@shadow/get/any/light'
var id = 'd4484cdb-a47a-4936-bcfd-33c1af39b857'
var tgConcat = '@shadow/get/!d4484cdb-a47a-4936-bcfd-33c1af39b857/any/light'
var _topic = getTopic(topic, id)
assert.equal(_topic, tgConcat)
})
})
describe('get sub', () => {
it('should return topic that id have insert between @client and #', () => {
var topic = '@client/#'
var id = 'd4484cdb-a47a-4936-bcfd-33c1af39b857'
var tgConcat = '@client/!d4484cdb-a47a-4936-bcfd-33c1af39b857/#'
var _topic = getTopic(topic, id)
assert.equal(_topic, tgConcat)
})
})
})
})
module.exports.getGroupID = getGroupID
var config = require('config');
var seneca = require('seneca')({log: 'silent'}).client({ port: config.get('device_registry_port'), host: config.get('device_registry_host') });
// var getRole = require('../checkClientRole').getRole
function getGroupID(token, client_id, callback) {
var role = require('jwt-verify').verify(token).res
if (role && role.hasOwnProperty('groupId')) {
callback(role.groupId);
}
else {
doDB(client_id, function(group) {
callback(group);
});
}
}
function doDB(client_id, callback) {
seneca.act('cmd:getGroupByClientid, clientid:'+client_id, function(err, res) {
if (err) callback(null);
else callback((res && res.result &&res.result[0])?res.result[0]:null);
});
}
module.exports.insertWordIntoTopic = insertWordIntoTopic
module.exports.removeTempWordInTopic = removeTempWordInTopic
module.exports.replaceWords = replaceWords
module.exports.cleanUpTopic = cleanUpTopic
/*
Ex: insertWordIntoTopic('@shadow/home/temp', '!GROUP', 1)
expected return : "@shadow/!GROUP/home/temp"
*/
function insertWordIntoTopic(topic, word, pos) {
var a = topic.split('/');
a.splice(pos, 0, word);
// console.log('>>> insertWordIntoTopic('+topic +','+ word +','+ pos +');');
// console.log(a.join('/'));
return a.join('/');
}
/*
Ex : removeTempWordInTopic('@shadow/!GROUP/home/temp')
expected return : "@shadowhome/temp"
*/
function removeTempWordInTopic(topic) {
var a = topic.split('/');
var k=0, l=a.length;
while (k<l) {
if (a[k].substr(0,1)=='!') {
a.splice(k,1);
l--;
}
else k++;
}
return a.join('/');
}
function replaceWords(topic, word, from, to) {
var a = topic.split('/');
a.splice(from,to-from+1);
if (word != null) a.splice(from, 0, word);
return a.join('/');
}
// Sample
// var str = insertWordIntoTopic('@shadow/home/temp', '!GROUP', 0);
// console.log(str);
// console.log(removeTempWordInTopic(str));
//console.log(replaceWords('@shadow/set/home/bob/bedroom/temp', 'CLIENTID-XXXXX', 2, 3));
function cleanUpTopic(topic) {
topic = topic.trim();
if (topic.substr(-1)=='/') return topic.slice(-1);
}
var modify = require('./modify');
function rewriteTopic(topic, op, groupid, clientid, output) {
var chunk = topic.split('/');
switch (chunk[0]) {
case '@msg' :
return modify.insertWordIntoTopic(topic, '!'+groupid, 1);
case '@shadow' :
if (chunk[1] == 'set' || chunk[1] == 'overset' || chunk[1] == 'get') {
output.verb = chunk[1];
return modify.insertWordIntoTopic(topic, ''+clientid, 2);
}
else if (chunk[1] == 'write' || chunk[1] == 'overwrite' || chunk[1] == 'read') {
output.verb = chunk[1];
return modify.insertWordIntoTopic(topic, groupid, 2);
}
else if (chunk[1] == 'changed') {
if (op == 'pub') {
if ( chunk.length > 2 )
return modify.insertWordIntoTopic(topic, '!'+groupid, 2);
else if ( chunk.length == 2 )
return modify.insertWordIntoTopic(topic, '!'+clientid, 2);
else return "";
}
else {
if ( chunk.length > 2 )
return modify.insertWordIntoTopic(topic, '!'+groupid, 2);
else if ( chunk.length == 2 )
return modify.insertWordIntoTopic(topic, '!'+clientid, 2);
else return "";
}
}
else return "";
case '@private' :
return modify.insertWordIntoTopic(topic, '!'+clientid, 1);
}
}
module.exports.rewriteTopic = rewriteTopic
module.exports.auth_connect = auth_connect
/*
{ _key: '1196651',
_id: 'access_token/1196651',
_rev: '_XdtTzQK--_',
"type": "v1",
"code": "f2a05d9a420e141d2d268b0c41f2af8e",
"device": "bd2w9fkc-bobclient",
"scope": [
"w:@shadow/read",
"w:@shadow/write"
],
"iat": 1537502874269,
"nbf": 1537502874269,
"exp": 1537609874269,
"for": [
{
"clientid": "bd2w9fkc-bobclient",
"verify": false
}
],
"user": "nexpie"
}
*/
function auth_connect(mqttauth, token_profile) {
var dateNow = Math.floor(Date.now() / 1000)
var res = {
status : true
}
if (token_profile) {
if (token_profile.for) {
var found = false;
for (var i=0; i<token_profile.for.length; i++) {
if (token_profile.for[i].clientid == mqttauth.clientid) {
found = true;
break;
}
}
if (!found) return {status: false, reason: 'uneligible'};
}
if (dateNow > token_profile.exp) return {status: false, reason: 'expired'};
if (token_profile.nbf && (dateNow < token_profile.nbf)) return {status: false, reason: 'uneligible'};
return {status: true};
}
else return false;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment