1
0
mirror of https://github.com/node-red/node-red.git synced 2023-10-10 13:36:53 +02:00

Move to express 4.x

This commit is contained in:
Nick O'Leary 2015-07-15 22:43:24 +01:00
parent ca91a5dd95
commit d668d43a0a
18 changed files with 143 additions and 148 deletions

View File

@ -81,13 +81,13 @@ module.exports = function(RED) {
if (node != null) { if (node != null) {
try { try {
node.receive(); node.receive();
res.send(200); res.sendStatus(200);
} catch(err) { } catch(err) {
res.send(500); res.sendStatus(500);
node.error(RED._("inject.failed",{error:err.toString()})); node.error(RED._("inject.failed",{error:err.toString()}));
} }
} else { } else {
res.send(404); res.sendStatus(404);
} }
}); });
} }

View File

@ -142,15 +142,15 @@ module.exports = function(RED) {
if (node !== null && typeof node !== "undefined" ) { if (node !== null && typeof node !== "undefined" ) {
if (state === "enable") { if (state === "enable") {
node.active = true; node.active = true;
res.send(200); res.sendStatus(200);
} else if (state === "disable") { } else if (state === "disable") {
node.active = false; node.active = false;
res.send(201); res.sendStatus(201);
} else { } else {
res.send(404); res.sendStatus(404);
} }
} else { } else {
res.send(404); res.sendStatus(404);
} }
}); });
}; };

View File

@ -19,13 +19,13 @@ module.exports = function(RED) {
var http = require("follow-redirects").http; var http = require("follow-redirects").http;
var https = require("follow-redirects").https; var https = require("follow-redirects").https;
var urllib = require("url"); var urllib = require("url");
var express = require("express"); var bodyParser = require("body-parser");
var getBody = require('raw-body'); var getBody = require('raw-body');
var mustache = require("mustache"); var mustache = require("mustache");
var querystring = require("querystring"); var querystring = require("querystring");
var cors = require('cors'); var cors = require('cors');
var jsonParser = express.json(); var jsonParser = bodyParser.json();
var urlencParser = express.urlencoded(); var urlencParser = bodyParser.urlencoded({extended:true});
var onHeaders = require('on-headers'); var onHeaders = require('on-headers');
function rawBodyParser(req, res, next) { function rawBodyParser(req, res, next) {
@ -43,6 +43,7 @@ module.exports = function(RED) {
}); });
} }
var corsSetup = false;
function HTTPIn(n) { function HTTPIn(n) {
RED.nodes.createNode(this,n); RED.nodes.createNode(this,n);
@ -60,7 +61,7 @@ module.exports = function(RED) {
this.errorHandler = function(err,req,res,next) { this.errorHandler = function(err,req,res,next) {
node.warn(err); node.warn(err);
res.send(500); res.sendStatus(500);
}; };
this.callback = function(req,res) { this.callback = function(req,res) {
@ -77,9 +78,10 @@ module.exports = function(RED) {
var corsHandler = function(req,res,next) { next(); } var corsHandler = function(req,res,next) { next(); }
if (RED.settings.httpNodeCors) { if (RED.settings.httpNodeCors && !corsSetup) {
corsHandler = cors(RED.settings.httpNodeCors); corsHandler = cors(RED.settings.httpNodeCors);
RED.httpNode.options(this.url,corsHandler); RED.httpNode.options("*",corsHandler);
corsSetup = true;
} }
var httpMiddleware = function(req,res,next) { next(); } var httpMiddleware = function(req,res,next) { next(); }
@ -121,24 +123,12 @@ module.exports = function(RED) {
} }
this.on("close",function() { this.on("close",function() {
var routes = RED.httpNode.routes[this.method]; var node = this;
for (var i = 0; i<routes.length; i++) { RED.httpNode._router.stack.forEach(function(route,i,routes) {
if (routes[i].path == this.url) { if (route.route && route.route.path === node.url && route.route.methods[node.method]) {
routes.splice(i,1); routes.splice(i,1);
//break;
} }
} });
if (RED.settings.httpNodeCors) {
var routes = RED.httpNode.routes['options'];
if (routes) {
for (var j = 0; j<routes.length; j++) {
if (routes[j].path == this.url) {
routes.splice(j,1);
//break;
}
}
}
}
}); });
} else { } else {
this.warn(RED._("httpin.errors.not-created")); this.warn(RED._("httpin.errors.not-created"));
@ -157,7 +147,7 @@ module.exports = function(RED) {
} }
var statusCode = msg.statusCode || 200; var statusCode = msg.statusCode || 200;
if (typeof msg.payload == "object" && !Buffer.isBuffer(msg.payload)) { if (typeof msg.payload == "object" && !Buffer.isBuffer(msg.payload)) {
msg.res.jsonp(statusCode,msg.payload); msg.res.status(statusCode).jsonp(msg.payload);
} else { } else {
if (msg.res.get('content-length') == null) { if (msg.res.get('content-length') == null) {
var len; var len;

View File

@ -25,7 +25,8 @@
"editor", "messaging", "iot", "m2m", "pi", "arduino", "beaglebone", "ibm", "flow" "editor", "messaging", "iot", "m2m", "pi", "arduino", "beaglebone", "ibm", "flow"
], ],
"dependencies": { "dependencies": {
"express": "3.20.3", "express": "4.13.1",
"body-parser": "1.13.2",
"when": "3.7.3", "when": "3.7.3",
"bcryptjs": "2.2.0", "bcryptjs": "2.2.0",
"nopt": "3.0.3", "nopt": "3.0.3",

View File

@ -55,7 +55,7 @@ function needsPermission(permission) {
return next(); return next();
} }
log.audit({event: "permission.fail"},req); log.audit({event: "permission.fail"},req);
return res.send(401); return res.status(401).end();
}); });
} else { } else {
next(); next();
@ -95,7 +95,7 @@ function revoke(req,res) {
// TODO: audit log // TODO: audit log
Tokens.revoke(token).then(function() { Tokens.revoke(token).then(function() {
log.audit({event: "auth.login.revoke"},req); log.audit({event: "auth.login.revoke"},req);
res.send(200); res.status(200).end();
}); });
} }

View File

@ -29,11 +29,11 @@ module.exports = {
var deploymentType = req.get("Node-RED-Deployment-Type")||"full"; var deploymentType = req.get("Node-RED-Deployment-Type")||"full";
log.audit({event: "flows.set",type:deploymentType},req); log.audit({event: "flows.set",type:deploymentType},req);
redNodes.setFlows(flows,deploymentType).then(function() { redNodes.setFlows(flows,deploymentType).then(function() {
res.send(204); res.status(204).end();
}).otherwise(function(err) { }).otherwise(function(err) {
log.warn(log._("api.flows.error-save",{message:err.message})); log.warn(log._("api.flows.error-save",{message:err.message}));
log.warn(err.stack); log.warn(err.stack);
res.json(500,{error:"unexpected_error", message:err.message}); res.status(500).json({error:"unexpected_error", message:err.message});
}); });
} }
} }

View File

@ -15,6 +15,7 @@
**/ **/
var express = require("express"); var express = require("express");
var bodyParser = require("body-parser");
var util = require('util'); var util = require('util');
var path = require('path'); var path = require('path');
var passport = require('passport'); var passport = require('passport');
@ -34,7 +35,7 @@ var settings = require("../settings");
var errorHandler = function(err,req,res,next) { var errorHandler = function(err,req,res,next) {
console.log(err.stack); console.log(err.stack);
res.json(400,{error:"unexpected_error", message:err.toString()}); res.status(400).json({error:"unexpected_error", message:err.toString()});
}; };
function init(adminApp,storage) { function init(adminApp,storage) {
@ -54,8 +55,8 @@ function init(adminApp,storage) {
adminApp.use(editorApp); adminApp.use(editorApp);
} }
adminApp.use(express.json()); adminApp.use(bodyParser.json());
adminApp.use(express.urlencoded()); adminApp.use(bodyParser.urlencoded({extended:true}));
adminApp.get("/auth/login",auth.login); adminApp.get("/auth/login",auth.login);

View File

@ -29,7 +29,7 @@ function createLibrary(type) {
if (typeof result === "string") { if (typeof result === "string") {
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(result); res.write(result);
res.end(); res.end();
} else { } else {
res.json(result); res.json(result);
} }
@ -38,33 +38,33 @@ function createLibrary(type) {
log.warn(log._("api.library.error-load-entry",{path:path,message:err.toString()})); log.warn(log._("api.library.error-load-entry",{path:path,message:err.toString()}));
if (err.code === 'forbidden') { if (err.code === 'forbidden') {
log.audit({event: "library.get",type:type,error:"forbidden"},req); log.audit({event: "library.get",type:type,error:"forbidden"},req);
res.send(403); res.status(403).end();
return; return;
} }
} }
log.audit({event: "library.get",type:type,error:"not_found"},req); log.audit({event: "library.get",type:type,error:"not_found"},req);
res.send(404); res.status(404).end();
}); });
}); });
redApp.post(new RegExp("/library/"+type+"\/(.*)"),needsPermission("library.write"),function(req,res) { redApp.post(new RegExp("/library/"+type+"\/(.*)"),needsPermission("library.write"),function(req,res) {
var path = req.params[0]; var path = req.params[0];
var meta = req.body; var meta = req.body;
var text = meta.text; var text = meta.text;
delete meta.text; delete meta.text;
storage.saveLibraryEntry(type,path,meta,text).then(function() { storage.saveLibraryEntry(type,path,meta,text).then(function() {
log.audit({event: "library.set",type:type},req); log.audit({event: "library.set",type:type},req);
res.send(204); res.status(204).end();
}).otherwise(function(err) { }).otherwise(function(err) {
log.warn(log._("api.library.error-save-entry",{path:path,message:err.toString()})); log.warn(log._("api.library.error-save-entry",{path:path,message:err.toString()}));
if (err.code === 'forbidden') { if (err.code === 'forbidden') {
log.audit({event: "library.set",type:type,error:"forbidden"},req); log.audit({event: "library.set",type:type,error:"forbidden"},req);
res.send(403); res.status(403).end();
return; return;
} }
log.audit({event: "library.set",type:type,error:"unexpected_error",message:err.toString()},req); log.audit({event: "library.set",type:type,error:"unexpected_error",message:err.toString()},req);
res.json(500,{error:"unexpected_error", message:err.toString()}); res.status(500).json({error:"unexpected_error", message:err.toString()});
}); });
}); });
} }
@ -74,7 +74,7 @@ module.exports = {
redApp = app; redApp = app;
}, },
register: createLibrary, register: createLibrary,
getAll: function(req,res) { getAll: function(req,res) {
storage.getAllFlows().then(function(flows) { storage.getAllFlows().then(function(flows) {
log.audit({event: "library.get.all",type:"flow"},req); log.audit({event: "library.get.all",type:"flow"},req);
@ -92,28 +92,28 @@ module.exports = {
log.warn(log._("api.library.error-load-flow",{path:req.params[0],message:err.toString()})); log.warn(log._("api.library.error-load-flow",{path:req.params[0],message:err.toString()}));
if (err.code === 'forbidden') { if (err.code === 'forbidden') {
log.audit({event: "library.get",type:"flow",path:req.params[0],error:"forbidden"},req); log.audit({event: "library.get",type:"flow",path:req.params[0],error:"forbidden"},req);
res.send(403); res.status(403).end();
return; return;
} }
} }
log.audit({event: "library.get",type:"flow",path:req.params[0],error:"not_found"},req); log.audit({event: "library.get",type:"flow",path:req.params[0],error:"not_found"},req);
res.send(404); res.status(404).end();
}); });
}, },
post: function(req,res) { post: function(req,res) {
var flow = JSON.stringify(req.body); var flow = JSON.stringify(req.body);
storage.saveFlow(req.params[0],flow).then(function() { storage.saveFlow(req.params[0],flow).then(function() {
log.audit({event: "library.set",type:"flow",path:req.params[0]},req); log.audit({event: "library.set",type:"flow",path:req.params[0]},req);
res.send(204); res.status(204).end();
}).otherwise(function(err) { }).otherwise(function(err) {
log.warn(log._("api.library.error-save-flow",{path:req.params[0],message:err.toString()})); log.warn(log._("api.library.error-save-flow",{path:req.params[0],message:err.toString()}));
if (err.code === 'forbidden') { if (err.code === 'forbidden') {
log.audit({event: "library.set",type:"flow",path:req.params[0],error:"forbidden"},req); log.audit({event: "library.set",type:"flow",path:req.params[0],error:"forbidden"},req);
res.send(403); res.status(403).end();
return; return;
} }
log.audit({event: "library.set",type:"flow",path:req.params[0],error:"unexpected_error",message:err.toString()},req); log.audit({event: "library.set",type:"flow",path:req.params[0],error:"unexpected_error",message:err.toString()},req);
res.send(500,{error:"unexpected_error", message:err.toString()}); res.status(500).send({error:"unexpected_error", message:err.toString()});
}); });
} }
} }

View File

@ -19,7 +19,7 @@ module.exports = {
get: function(req,res) { get: function(req,res) {
var namespace = req.params[0]; var namespace = req.params[0];
namespace = namespace.replace(/\.json$/,""); namespace = namespace.replace(/\.json$/,"");
var lang = i18n.determineLangFromHeaders(req.acceptedLanguages || []); var lang = i18n.determineLangFromHeaders(req.acceptsLanguages() || []);
var prevLang = i18n.i.lng(); var prevLang = i18n.i.lng();
i18n.i.setLng(lang, function(){ i18n.i.setLng(lang, function(){
var catalog = i18n.catalog(namespace,lang); var catalog = i18n.catalog(namespace,lang);

View File

@ -29,7 +29,7 @@ module.exports = {
log.audit({event: "nodes.list.get"},req); log.audit({event: "nodes.list.get"},req);
res.json(redNodes.getNodeList()); res.json(redNodes.getNodeList());
} else { } else {
var lang = i18n.determineLangFromHeaders(req.acceptedLanguages); var lang = i18n.determineLangFromHeaders(req.acceptsLanguages());
log.audit({event: "nodes.configs.get"},req); log.audit({event: "nodes.configs.get"},req);
res.send(redNodes.getNodeConfigs(lang)); res.send(redNodes.getNodeConfigs(lang));
} }
@ -38,7 +38,7 @@ module.exports = {
post: function(req,res) { post: function(req,res) {
if (!settings.available()) { if (!settings.available()) {
log.audit({event: "nodes.install",error:"settings_unavailable"},req); log.audit({event: "nodes.install",error:"settings_unavailable"},req);
res.json(400,{error:"settings_unavailable", message:"Settings unavailable"}); res.status(400).json({error:"settings_unavailable", message:"Settings unavailable"});
return; return;
} }
var node = req.body; var node = req.body;
@ -47,7 +47,7 @@ module.exports = {
var module = redNodes.getModuleInfo(node.module); var module = redNodes.getModuleInfo(node.module);
if (module) { if (module) {
log.audit({event: "nodes.install",module:node.module,error:"module_already_loaded"},req); log.audit({event: "nodes.install",module:node.module,error:"module_already_loaded"},req);
res.json(400,{error:"module_already_loaded", message:"Module already loaded"}); res.status(400).json({error:"module_already_loaded", message:"Module already loaded"});
return; return;
} }
promise = server.installModule(node.module); promise = server.installModule(node.module);
@ -55,7 +55,7 @@ module.exports = {
promise = server.installNode(node.file); promise = server.installNode(node.file);
} else { } else {
log.audit({event: "nodes.install",module:node.module,error:"invalid_request"},req); log.audit({event: "nodes.install",module:node.module,error:"invalid_request"},req);
res.json(400,{error:"invalid_request", message:"Invalid request"}); res.status(400).json({error:"invalid_request", message:"Invalid request"});
return; return;
} }
promise.then(function(info) { promise.then(function(info) {
@ -69,13 +69,13 @@ module.exports = {
}).otherwise(function(err) { }).otherwise(function(err) {
if (err.code === 404) { if (err.code === 404) {
log.audit({event: "nodes.install",module:node.module,file:node.file,error:"not_found"},req); log.audit({event: "nodes.install",module:node.module,file:node.file,error:"not_found"},req);
res.send(404); res.status(404).end();
} else if (err.code) { } else if (err.code) {
log.audit({event: "nodes.install",module:node.module,error:err.code},req); log.audit({event: "nodes.install",module:node.module,error:err.code},req);
res.json(400,{error:err.code, message:err.message}); res.status(400).json({error:err.code, message:err.message});
} else { } else {
log.audit({event: "nodes.install",module:node.module,file:node.file,error:err.code||"unexpected_error",message:err.toString()},req); log.audit({event: "nodes.install",module:node.module,file:node.file,error:err.code||"unexpected_error",message:err.toString()},req);
res.json(400,{error:err.code||"unexpected_error", message:err.toString()}); res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
} }
}); });
}, },
@ -83,7 +83,7 @@ module.exports = {
delete: function(req,res) { delete: function(req,res) {
if (!settings.available()) { if (!settings.available()) {
log.audit({event: "nodes.remove",error:"settings_unavailable"},req); log.audit({event: "nodes.remove",error:"settings_unavailable"},req);
res.json(400,{error:"settings_unavailable", message:"Settings unavailable"}); res.status(400).json({error:"settings_unavailable", message:"Settings unavailable"});
return; return;
} }
var mod = req.params.mod; var mod = req.params.mod;
@ -92,7 +92,7 @@ module.exports = {
var module = redNodes.getModuleInfo(mod); var module = redNodes.getModuleInfo(mod);
if (!module) { if (!module) {
log.audit({event: "nodes.remove",module:mod,error:"not_found"},req); log.audit({event: "nodes.remove",module:mod,error:"not_found"},req);
res.send(404); res.status(404).end();
return; return;
} else { } else {
promise = server.uninstallModule(mod); promise = server.uninstallModule(mod);
@ -100,14 +100,14 @@ module.exports = {
promise.then(function() { promise.then(function() {
log.audit({event: "nodes.remove",module:mod},req); log.audit({event: "nodes.remove",module:mod},req);
res.send(204); res.status(204).end();
}).otherwise(function(err) { }).otherwise(function(err) {
log.audit({event: "nodes.remove",module:mod,error:err.code||"unexpected_error",message:err.toString()},req); log.audit({event: "nodes.remove",module:mod,error:err.code||"unexpected_error",message:err.toString()},req);
res.json(400,{error:err.code||"unexpected_error", message:err.toString()}); res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
}); });
} catch(err) { } catch(err) {
log.audit({event: "nodes.remove",module:mod,error:err.code||"unexpected_error",message:err.toString()},req); log.audit({event: "nodes.remove",module:mod,error:err.code||"unexpected_error",message:err.toString()},req);
res.json(400,{error:err.code||"unexpected_error", message:err.toString()}); res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
} }
}, },
@ -122,17 +122,17 @@ module.exports = {
res.send(result); res.send(result);
} else { } else {
log.audit({event: "nodes.info.get",id:id,error:"not_found"},req); log.audit({event: "nodes.info.get",id:id,error:"not_found"},req);
res.send(404); res.status(404).end();
} }
} else { } else {
var lang = i18n.determineLangFromHeaders(req.acceptedLanguages); var lang = i18n.determineLangFromHeaders(req.acceptsLanguages());
result = redNodes.getNodeConfig(id,lang); result = redNodes.getNodeConfig(id,lang);
if (result) { if (result) {
log.audit({event: "nodes.config.get",id:id},req); log.audit({event: "nodes.config.get",id:id},req);
res.send(result); res.send(result);
} else { } else {
log.audit({event: "nodes.config.get",id:id,error:"not_found"},req); log.audit({event: "nodes.config.get",id:id,error:"not_found"},req);
res.send(404); res.status(404).end();
} }
} }
}, },
@ -145,20 +145,20 @@ module.exports = {
res.json(result); res.json(result);
} else { } else {
log.audit({event: "nodes.module.get",module:module,error:"not_found"},req); log.audit({event: "nodes.module.get",module:module,error:"not_found"},req);
res.send(404); res.status(404).end();
} }
}, },
putSet: function(req,res) { putSet: function(req,res) {
if (!settings.available()) { if (!settings.available()) {
log.audit({event: "nodes.info.set",error:"settings_unavailable"},req); log.audit({event: "nodes.info.set",error:"settings_unavailable"},req);
res.json(400,{error:"settings_unavailable", message:"Settings unavailable"}); res.status(400).json({error:"settings_unavailable", message:"Settings unavailable"});
return; return;
} }
var body = req.body; var body = req.body;
if (!body.hasOwnProperty("enabled")) { if (!body.hasOwnProperty("enabled")) {
log.audit({event: "nodes.info.set",error:"invalid_request"},req); log.audit({event: "nodes.info.set",error:"invalid_request"},req);
res.json(400,{error:"invalid_request", message:"Invalid request"}); res.status(400).json({error:"invalid_request", message:"Invalid request"});
return; return;
} }
try { try {
@ -167,7 +167,7 @@ module.exports = {
var info; var info;
if (!node) { if (!node) {
log.audit({event: "nodes.info.set",id:id,error:"not_found"},req); log.audit({event: "nodes.info.set",id:id,error:"not_found"},req);
res.send(404); res.status(404).end();
} else { } else {
delete node.loaded; delete node.loaded;
putNode(node, body.enabled).then(function(result) { putNode(node, body.enabled).then(function(result) {
@ -177,20 +177,20 @@ module.exports = {
} }
} catch(err) { } catch(err) {
log.audit({event: "nodes.info.set",id:id,enabled:body.enabled,error:err.code||"unexpected_error",message:err.toString()},req); log.audit({event: "nodes.info.set",id:id,enabled:body.enabled,error:err.code||"unexpected_error",message:err.toString()},req);
res.json(400,{error:err.code||"unexpected_error", message:err.toString()}); res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
} }
}, },
putModule: function(req,res) { putModule: function(req,res) {
if (!settings.available()) { if (!settings.available()) {
log.audit({event: "nodes.module.set",error:"settings_unavailable"},req); log.audit({event: "nodes.module.set",error:"settings_unavailable"},req);
res.json(400,{error:"settings_unavailable", message:"Settings unavailable"}); res.status(400).json({error:"settings_unavailable", message:"Settings unavailable"});
return; return;
} }
var body = req.body; var body = req.body;
if (!body.hasOwnProperty("enabled")) { if (!body.hasOwnProperty("enabled")) {
log.audit({event: "nodes.module.set",error:"invalid_request"},req); log.audit({event: "nodes.module.set",error:"invalid_request"},req);
res.json(400,{error:"invalid_request", message:"Invalid request"}); res.status(400).json({error:"invalid_request", message:"Invalid request"});
return; return;
} }
try { try {
@ -198,7 +198,7 @@ module.exports = {
var module = redNodes.getModuleInfo(mod); var module = redNodes.getModuleInfo(mod);
if (!module) { if (!module) {
log.audit({event: "nodes.module.set",module:mod,error:"not_found"},req); log.audit({event: "nodes.module.set",module:mod,error:"not_found"},req);
return res.send(404); return res.status(404).end();
} }
var nodes = module.nodes; var nodes = module.nodes;
@ -211,7 +211,7 @@ module.exports = {
}); });
} catch(err) { } catch(err) {
log.audit({event: "nodes.module.set",module:mod,enabled:body.enabled,error:err.code||"unexpected_error",message:err.toString()},req); log.audit({event: "nodes.module.set",module:mod,enabled:body.enabled,error:err.code||"unexpected_error",message:err.toString()},req);
res.json(400,{error:err.code||"unexpected_error", message:err.toString()}); res.status(400).json({error:err.code||"unexpected_error", message:err.toString()});
} }
} }
}; };
@ -227,7 +227,7 @@ function putNode(node, enabled) {
} else { } else {
promise = redNodes.disableNode(node.id); promise = redNodes.disableNode(node.id);
} }
return promise.then(function(info) { return promise.then(function(info) {
if (info.enabled === enabled && !info.err) { if (info.enabled === enabled && !info.err) {
comms.publish("node/"+(enabled?"enabled":"disabled"),info,false); comms.publish("node/"+(enabled?"enabled":"disabled"),info,false);

View File

@ -43,7 +43,7 @@ function serveFile(app,baseUrl,file) {
var url = baseUrl+path.basename(file); var url = baseUrl+path.basename(file);
//console.log(url,"->",file); //console.log(url,"->",file);
app.get(url,function(req, res) { app.get(url,function(req, res) {
res.sendfile(file); res.sendFile(file);
}); });
return "theme"+url; return "theme"+url;
} catch(err) { } catch(err) {
@ -58,13 +58,13 @@ module.exports = {
var url; var url;
themeContext = clone(defaultContext); themeContext = clone(defaultContext);
themeSettings = null; themeSettings = null;
if (settings.editorTheme) { if (settings.editorTheme) {
var theme = settings.editorTheme; var theme = settings.editorTheme;
themeSettings = {}; themeSettings = {};
var themeApp = express(); var themeApp = express();
if (theme.page) { if (theme.page) {
if (theme.page.css) { if (theme.page.css) {
var styles = theme.page.css; var styles = theme.page.css;
@ -72,7 +72,7 @@ module.exports = {
styles = [styles]; styles = [styles];
} }
themeContext.page.css = []; themeContext.page.css = [];
for (i=0;i<styles.length;i++) { for (i=0;i<styles.length;i++) {
url = serveFile(themeApp,"/css/",styles[i]); url = serveFile(themeApp,"/css/",styles[i]);
if (url) { if (url) {
@ -80,25 +80,25 @@ module.exports = {
} }
} }
} }
if (theme.page.favicon) { if (theme.page.favicon) {
url = serveFile(themeApp,"/favicon/",theme.page.favicon) url = serveFile(themeApp,"/favicon/",theme.page.favicon)
if (url) { if (url) {
themeContext.page.favicon = url; themeContext.page.favicon = url;
} }
} }
themeContext.page.title = theme.page.title || themeContext.page.title; themeContext.page.title = theme.page.title || themeContext.page.title;
} }
if (theme.header) { if (theme.header) {
themeContext.header.title = theme.header.title || themeContext.header.title; themeContext.header.title = theme.header.title || themeContext.header.title;
if (theme.header.hasOwnProperty("url")) { if (theme.header.hasOwnProperty("url")) {
themeContext.header.url = theme.header.url; themeContext.header.url = theme.header.url;
} }
if (theme.header.hasOwnProperty("image")) { if (theme.header.hasOwnProperty("image")) {
if (theme.header.image) { if (theme.header.image) {
url = serveFile(themeApp,"/header/",theme.header.image); url = serveFile(themeApp,"/header/",theme.header.image);
@ -110,7 +110,7 @@ module.exports = {
} }
} }
} }
if (theme.deployButton) { if (theme.deployButton) {
if (theme.deployButton.type == "simple") { if (theme.deployButton.type == "simple") {
themeSettings.deployButton = { themeSettings.deployButton = {
@ -127,11 +127,11 @@ module.exports = {
} }
} }
} }
if (theme.hasOwnProperty("userMenu")) { if (theme.hasOwnProperty("userMenu")) {
themeSettings.userMenu = theme.userMenu; themeSettings.userMenu = theme.userMenu;
} }
if (theme.login) { if (theme.login) {
if (theme.login.image) { if (theme.login.image) {
url = serveFile(themeApp,"/login/",theme.login.image); url = serveFile(themeApp,"/login/",theme.login.image);
@ -142,11 +142,11 @@ module.exports = {
} }
} }
} }
if (theme.hasOwnProperty("menu")) { if (theme.hasOwnProperty("menu")) {
themeSettings.menu = theme.menu; themeSettings.menu = theme.menu;
} }
return themeApp; return themeApp;
} }
}, },

View File

@ -42,7 +42,7 @@ module.exports = {
editorTemplate = fs.readFileSync(path.join(templateDir,"index.mst"),"utf8"); editorTemplate = fs.readFileSync(path.join(templateDir,"index.mst"),"utf8");
Mustache.parse(editorTemplate); Mustache.parse(editorTemplate);
}, },
ensureSlash: function(req,res,next) { ensureSlash: function(req,res,next) {
var parts = req.originalUrl.split("?"); var parts = req.originalUrl.split("?");
if (parts[0].slice(-1) != "/") { if (parts[0].slice(-1) != "/") {
@ -55,17 +55,17 @@ module.exports = {
}, },
icon: function(req,res) { icon: function(req,res) {
if (iconCache[req.params.icon]) { if (iconCache[req.params.icon]) {
res.sendfile(iconCache[req.params.icon]); // if not found, express prints this to the console and serves 404 res.sendFile(iconCache[req.params.icon]); // if not found, express prints this to the console and serves 404
} else { } else {
for (var p=0;p<icon_paths.length;p++) { for (var p=0;p<icon_paths.length;p++) {
var iconPath = path.join(icon_paths[p],req.params.icon); var iconPath = path.join(icon_paths[p],req.params.icon);
if (fs.existsSync(iconPath)) { if (fs.existsSync(iconPath)) {
res.sendfile(iconPath); res.sendFile(iconPath);
iconCache[req.params.icon] = iconPath; iconCache[req.params.icon] = iconPath;
return; return;
} }
} }
res.sendfile(defaultIcon); res.sendFile(defaultIcon);
} }
}, },
editor: function(req,res) { editor: function(req,res) {

View File

@ -20,7 +20,7 @@ var path = require("path");
var fs = require("fs"); var fs = require("fs");
var defaultLang = "en-US"; var defaultLang = "en-US";
var supportedLangs = null; var supportedLangs = [];
var resourceMap = { var resourceMap = {
"runtime": { "runtime": {

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
**/ **/
var should = require("should"); var should = require("should");
var when = require("when"); var when = require("when");
var sinon = require("sinon"); var sinon = require("sinon");
@ -28,7 +28,7 @@ var settings = require("../../../../red/settings");
describe("api auth middleware",function() { describe("api auth middleware",function() {
describe("ensureClientSecret", function() { describe("ensureClientSecret", function() {
it("leaves client_secret alone if not present",function(done) { it("leaves client_secret alone if not present",function(done) {
var req = { var req = {
@ -51,26 +51,26 @@ describe("api auth middleware",function() {
}) })
}); });
}); });
describe("revoke", function() { describe("revoke", function() {
it("revokes a token", function(done) { it("revokes a token", function(done) {
var revokeToken = sinon.stub(Tokens,"revoke",function() { var revokeToken = sinon.stub(Tokens,"revoke",function() {
return when.resolve(); return when.resolve();
}); });
var req = { body: { token: "abcdef" } }; var req = { body: { token: "abcdef" } };
var res = { send: function(resp) { var res = { status: function(resp) {
revokeToken.restore(); revokeToken.restore();
resp.should.equal(200); resp.should.equal(200);
done(); done();
}}; }};
auth.revoke(req,res); auth.revoke(req,res);
}); });
}); });
describe("login", function() { describe("login", function() {
beforeEach(function() { beforeEach(function() {
sinon.stub(Tokens,"init",function(){}); sinon.stub(Tokens,"init",function(){});
@ -96,7 +96,7 @@ describe("api auth middleware",function() {
done(); done();
}}); }});
}); });
}); });
}); });

View File

@ -17,6 +17,7 @@
var should = require("should"); var should = require("should");
var request = require('supertest'); var request = require('supertest');
var express = require('express'); var express = require('express');
var bodyParser = require('body-parser');
var sinon = require('sinon'); var sinon = require('sinon');
var when = require('when'); var when = require('when');
@ -25,16 +26,16 @@ var redNodes = require("../../../red/nodes");
var flows = require("../../../red/api/flows"); var flows = require("../../../red/api/flows");
describe("flows api", function() { describe("flows api", function() {
var app; var app;
before(function() { before(function() {
app = express(); app = express();
app.use(express.json()); app.use(bodyParser.json());
app.get("/flows",flows.get); app.get("/flows",flows.get);
app.post("/flows",flows.post); app.post("/flows",flows.post);
}); });
it('returns flow', function(done) { it('returns flow', function(done) {
var getFlows = sinon.stub(redNodes,'getFlows', function() { var getFlows = sinon.stub(redNodes,'getFlows', function() {
return [1,2,3]; return [1,2,3];
@ -52,7 +53,7 @@ describe("flows api", function() {
done(); done();
}); });
}); });
it('sets flows', function(done) { it('sets flows', function(done) {
var setFlows = sinon.stub(redNodes,'setFlows', function() { var setFlows = sinon.stub(redNodes,'setFlows', function() {
return when.resolve(); return when.resolve();
@ -86,5 +87,5 @@ describe("flows api", function() {
done(); done();
}); });
}); });
}); });

View File

@ -17,6 +17,7 @@
var should = require("should"); var should = require("should");
var request = require('supertest'); var request = require('supertest');
var express = require('express'); var express = require('express');
var bodyParser = require('body-parser');
var when = require('when'); var when = require('when');
@ -27,7 +28,7 @@ var library = require("../../../red/api/library");
var auth = require("../../../red/api/auth"); var auth = require("../../../red/api/auth");
describe("library api", function() { describe("library api", function() {
function initStorage(_flows,_libraryEntries) { function initStorage(_flows,_libraryEntries) {
var flows = _flows; var flows = _flows;
var libraryEntries = _libraryEntries; var libraryEntries = _libraryEntries;
@ -67,13 +68,13 @@ describe("library api", function() {
describe("flows", function() { describe("flows", function() {
var app; var app;
before(function() { before(function() {
app = express(); app = express();
app.use(express.json()); app.use(bodyParser.json());
app.get("/library/flows",library.getAll); app.get("/library/flows",library.getAll);
app.post(new RegExp("/library/flows\/(.*)"),library.post); app.post(new RegExp("/library/flows\/(.*)"),library.post);
app.get(new RegExp("/library/flows\/(.*)"),library.get); app.get(new RegExp("/library/flows\/(.*)"),library.get);
}); });
it('returns empty result', function(done) { it('returns empty result', function(done) {
initStorage({},{flows:{}}); initStorage({},{flows:{}});
@ -97,8 +98,8 @@ describe("library api", function() {
.expect(404) .expect(404)
.end(done); .end(done);
}); });
it('can store and retrieve item', function(done) { it('can store and retrieve item', function(done) {
initStorage({},{flows:{}}); initStorage({},{flows:{}});
var flow = '[]'; var flow = '[]';
@ -122,7 +123,7 @@ describe("library api", function() {
}); });
}); });
}); });
it('lists a stored item', function(done) { it('lists a stored item', function(done) {
initStorage({f:["bar"]}); initStorage({f:["bar"]});
request(app) request(app)
@ -137,7 +138,7 @@ describe("library api", function() {
done(); done();
}); });
}); });
it('returns 403 for malicious get attempt', function(done) { it('returns 403 for malicious get attempt', function(done) {
initStorage({}); initStorage({});
// without the userDir override the malicious url would be // without the userDir override the malicious url would be
@ -162,10 +163,10 @@ describe("library api", function() {
describe("type", function() { describe("type", function() {
var app; var app;
before(function() { before(function() {
app = express(); app = express();
app.use(express.json()); app.use(bodyParser.json());
library.init(app); library.init(app);
auth.init({}); auth.init({});
RED.library.register("test"); RED.library.register("test");
@ -184,7 +185,7 @@ describe("library api", function() {
done(); done();
}); });
}); });
it('returns 404 for non-existent entry', function(done) { it('returns 404 for non-existent entry', function(done) {
initStorage({},{}); initStorage({},{});
request(app) request(app)
@ -192,7 +193,7 @@ describe("library api", function() {
.expect(404) .expect(404)
.end(done); .end(done);
}); });
it('can store and retrieve item', function(done) { it('can store and retrieve item', function(done) {
initStorage({},{'test':{}}); initStorage({},{'test':{}});
var flow = {text:"test content"}; var flow = {text:"test content"};
@ -216,7 +217,7 @@ describe("library api", function() {
}); });
}); });
}); });
it('lists a stored item', function(done) { it('lists a stored item', function(done) {
initStorage({},{'test':{'a':['abc','def']}}); initStorage({},{'test':{'a':['abc','def']}});
request(app) request(app)
@ -232,22 +233,22 @@ describe("library api", function() {
done(); done();
}); });
}); });
it('returns 403 for malicious access attempt', function(done) { it('returns 403 for malicious access attempt', function(done) {
request(app) request(app)
.get('/library/test/../../../../../../../../../../etc/passwd') .get('/library/test/../../../../../../../../../../etc/passwd')
.expect(403) .expect(403)
.end(done); .end(done);
}); });
it('returns 403 for malicious access attempt', function(done) { it('returns 403 for malicious access attempt', function(done) {
request(app) request(app)
.get('/library/test/..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\etc\\passwd') .get('/library/test/..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\etc\\passwd')
.expect(403) .expect(403)
.end(done); .end(done);
}); });
it('returns 403 for malicious access attempt', function(done) { it('returns 403 for malicious access attempt', function(done) {
request(app) request(app)
.post('/library/test/../../../../../../../../../../etc/passwd') .post('/library/test/../../../../../../../../../../etc/passwd')
@ -256,6 +257,6 @@ describe("library api", function() {
.expect(403) .expect(403)
.end(done); .end(done);
}); });
}); });
}); });

View File

@ -17,6 +17,7 @@
var should = require("should"); var should = require("should");
var request = require('supertest'); var request = require('supertest');
var express = require('express'); var express = require('express');
var bodyParser = require('body-parser');
var sinon = require('sinon'); var sinon = require('sinon');
var when = require('when'); var when = require('when');
@ -32,7 +33,7 @@ describe("nodes api", function() {
before(function() { before(function() {
app = express(); app = express();
app.use(express.json()); app.use(bodyParser.json());
app.get("/nodes",nodes.getAll); app.get("/nodes",nodes.getAll);
app.post("/nodes",nodes.post); app.post("/nodes",nodes.post);
app.get("/nodes/:mod",nodes.getModule); app.get("/nodes/:mod",nodes.getModule);

View File

@ -26,12 +26,12 @@ var ui = require("../../../red/api/ui");
describe("ui api", function() { describe("ui api", function() {
var app; var app;
describe("slash handler", function() { describe("slash handler", function() {
before(function() { before(function() {
app = express(); app = express();
app.get("/foo",ui.ensureSlash,function(req,res) { res.send(200);}); app.get("/foo",ui.ensureSlash,function(req,res) { res.sendStatus(200);});
}); });
it('redirects if the path does not end in a slash',function(done) { it('redirects if the path does not end in a slash',function(done) {
request(app) request(app)
@ -57,13 +57,13 @@ describe("ui api", function() {
.expect(200,done); .expect(200,done);
}); });
}); });
describe("icon handler", function() { describe("icon handler", function() {
before(function() { before(function() {
app = express(); app = express();
app.get("/icons/:icon",ui.icon); app.get("/icons/:icon",ui.icon);
}); });
function binaryParser(res, callback) { function binaryParser(res, callback) {
res.setEncoding('binary'); res.setEncoding('binary');
res.data = ''; res.data = '';
@ -80,7 +80,7 @@ describe("ui api", function() {
b1[i].should.equal(b2[i]); b1[i].should.equal(b2[i]);
} }
} }
it('returns the default icon when getting an unknown icon', function(done) { it('returns the default icon when getting an unknown icon', function(done) {
var defaultIcon = fs.readFileSync(path.resolve(__dirname+'/../../../public/icons/arrow-in.png')); var defaultIcon = fs.readFileSync(path.resolve(__dirname+'/../../../public/icons/arrow-in.png'));
request(app) request(app)
@ -96,7 +96,7 @@ describe("ui api", function() {
compareBuffers(res.body,defaultIcon); compareBuffers(res.body,defaultIcon);
done(); done();
}); });
}); });
it('returns a known icon', function(done) { it('returns a known icon', function(done) {
var injectIcon = fs.readFileSync(path.resolve(__dirname+'/../../../public/icons/inject.png')); var injectIcon = fs.readFileSync(path.resolve(__dirname+'/../../../public/icons/inject.png'));
@ -114,7 +114,7 @@ describe("ui api", function() {
done(); done();
}); });
}); });
it('returns a registered icon' , function(done) { it('returns a registered icon' , function(done) {
var testIcon = fs.readFileSync(path.resolve(__dirname+'/../../resources/icons/test_icon.png')); var testIcon = fs.readFileSync(path.resolve(__dirname+'/../../resources/icons/test_icon.png'));
events.emit("node-icon-dir", path.resolve(__dirname+'/../../resources/icons')); events.emit("node-icon-dir", path.resolve(__dirname+'/../../resources/icons'));
@ -133,7 +133,7 @@ describe("ui api", function() {
}); });
}); });
}); });
describe("editor ui handler", function() { describe("editor ui handler", function() {
before(function() { before(function() {
app = express(); app = express();
@ -153,7 +153,7 @@ describe("ui api", function() {
}); });
}); });
}); });
describe("editor ui resource handler", function() { describe("editor ui resource handler", function() {
before(function() { before(function() {
app = express(); app = express();
@ -172,7 +172,7 @@ describe("ui api", function() {
}); });
}); });
}); });