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

Add permissions and user menu

This commit is contained in:
Nick O'Leary 2014-12-10 14:16:07 +00:00
parent f5d7903ecb
commit a494954275
17 changed files with 458 additions and 211 deletions

View File

@ -79,20 +79,20 @@ module.exports = function(RED) {
delete this.cronjob;
}
}
RED.httpAdmin.post("/inject/:id", function(req,res) {
var node = RED.nodes.getNode(req.params.id);
if (node != null) {
try {
node.receive();
res.send(200);
} catch(err) {
res.send(500);
node.error("Inject failed:"+err);
console.log(err.stack);
}
} else {
res.send(404);
RED.httpAdmin.post("/inject/:id", RED.auth.needsPermission("inject.write"), function(req,res) {
var node = RED.nodes.getNode(req.params.id);
if (node != null) {
try {
node.receive();
res.send(200);
} catch(err) {
res.send(500);
node.error("Inject failed:"+err);
console.log(err.stack);
}
} else {
res.send(404);
}
});
}

View File

@ -119,7 +119,7 @@ module.exports = function(RED) {
});
RED.log.addHandler(DebugNode.logHandler);
RED.httpAdmin.post("/debug/:id/:state", function(req,res) {
RED.httpAdmin.post("/debug/:id/:state", RED.auth.needsPermission("debug.write"), function(req,res) {
var node = RED.nodes.getNode(req.params.id);
var state = req.params.state;
if (node !== null && typeof node !== "undefined" ) {

View File

@ -36,7 +36,7 @@
<a id="btn-deploy" class="action-deploy disabled" href="#"><img id="btn-icn-deploy" src="images/deploy-full-o.png"> <span>Deploy</span></a>
<a id="btn-deploy-options" data-toggle="dropdown" class="" href="#"><i class="fa fa-caret-down"></i></a>
</span></li>
<li><span class="user hide"><i class="fa fa-user"></i> <span class="username"></span></span></li>
<li><a id="btn-usermenu" class="button" data-toggle="dropdown" href="#"><i class="fa fa-user"></i></a></li>
<li><a id="btn-sidemenu" class="button" data-toggle="dropdown" href="#"><i class="fa fa-bars"></i></a></li>
<ul>
</div>
@ -240,14 +240,6 @@
</div>
</script>
<div id="node-dialog-login" class="hide">
<div style="display: inline-block;width: 250px; vertical-align: top; margin-right: 10px; margin-bottom: 20px;"><img src="node-red-256.png"/></div>
<div style="display: inline-block; width: 250px; vertical-align: bottom; margin-left: 10px; margin-bottom: 20px;">
<form id="node-dialog-login-fields" class="form-horizontal"></form>
</div>
</div>
<script src="jquery/js/jquery-1.11.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="jquery/js/jquery-ui-1.10.3.custom.min.js"></script>
@ -257,6 +249,7 @@
<script src="d3.v3.min.js"></script>
<script src="red/main.js"></script>
<script src="red/settings.js"></script>
<script src="red/user.js"></script>
<script src="red/comms.js"></script>
<script src="red/ui/state.js"></script>
<script src="red/nodes.js"></script>

View File

@ -21,10 +21,23 @@ RED.comms = (function() {
var subscriptions = {};
var ws;
var pendingAuth = false;
function connectWS() {
var path = location.hostname+":"+location.port+document.location.pathname;
path = path+(path.slice(-1) == "/"?"":"/")+"comms";
path = "ws"+(document.location.protocol=="https:"?"s":"")+"://"+path;
var auth_tokens = RED.settings.get("auth-tokens");
pendingAuth = (auth_tokens!=null);
function completeConnection() {
for (var t in subscriptions) {
if (subscriptions.hasOwnProperty(t)) {
ws.send(JSON.stringify({subscribe:t}));
}
}
}
ws = new WebSocket(path);
ws.onopen = function() {
if (errornotification) {
@ -33,19 +46,18 @@ RED.comms = (function() {
errornotification = null;
},1000);
}
var auth_tokens = RED.settings.get("auth-tokens");
if (auth_tokens) {
if (pendingAuth) {
ws.send(JSON.stringify({auth:auth_tokens.access_token}));
}
for (var t in subscriptions) {
if (subscriptions.hasOwnProperty(t)) {
ws.send(JSON.stringify({subscribe:t}));
}
} else {
completeConnection();
}
}
ws.onmessage = function(event) {
var msg = JSON.parse(event.data);
if (msg.topic) {
if (pendingAuth && msg.auth == "ok") {
pendingAuth = false;
completeConnection();
} else if (msg.topic) {
for (var t in subscriptions) {
if (subscriptions.hasOwnProperty(t)) {
var re = new RegExp("^"+t.replace(/([\[\]\?\(\)\\\\$\^\*\.|])/g,"\\$1").replace(/\+/g,"[^/]+").replace(/\/#$/,"(\/.*)?")+"$");

View File

@ -311,34 +311,46 @@ var RED = (function() {
});
if (RED.settings.user) {
$("#header .username").html(RED.settings.user.username);
$("#header .user").show();
RED.menu.addItem("btn-sidemenu", null);
RED.menu.addItem("btn-sidemenu",{
id:"btn-logout",
icon:"fa fa-user",
label:"Logout",
onselect:function() {
// TODO: invalidate token
$.ajax({
url: "auth/revoke",
type: "POST",
data: {token:RED.settings.get("auth-tokens").access_token},
success: function() {
RED.settings.remove("auth-tokens");
document.location.reload(true);
}
})
}
RED.menu.init({id:"btn-usermenu",
options: []
});
function updateUserMenu() {
$("#btn-usermenu-submenu li").remove();
if (RED.settings.user.anonymous) {
RED.menu.addItem("btn-usermenu",{
id:"btn-login",
label:"Login",
onselect: function() {
RED.user.login({cancelable:true},function() {
RED.settings.load(function() {
RED.notify("Logged in as "+RED.settings.user.username,"success");
updateUserMenu();
});
});
}
});
} else {
RED.menu.addItem("btn-usermenu",{
id:"btn-username",
icon:"fa fa-user",
label:"<b>"+RED.settings.user.username+"</b>"
});
RED.menu.addItem("btn-usermenu",{
id:"btn-logout",
label:"Logout",
onselect: function() {
RED.user.logout();
}
});
}
}
updateUserMenu();
}
$("#main-container").show();
$("#btn-deploy").show();
$("#btn-sidemenu").show();
$(".header-toolbar").show();
RED.library.init();
RED.palette.init();
@ -349,92 +361,14 @@ var RED = (function() {
RED.comms.connect();
loadNodeList();
}
function showLogin() {
var dialog = $("#node-dialog-login");
dialog.dialog({
autoOpen: false,
dialogClass: "ui-dialog-no-close",
modal: true,
closeOnEscape: false,
width: 600,
resizable: false,
draggable: false
});
$("#node-dialog-login-fields").empty();
$.ajax({
dataType: "json",
url: "auth/login",
success: function(data) {
if (data.type == "credentials") {
for (var i=0;i<data.prompts.length;i++) {
var field = data.prompts[i];
var row = $("<div/>",{class:"form-row"});
$('<label for="node-dialog-login-'+field.id+'">'+field.label+':</label><br/>').appendTo(row);
$('<input style="width: 100%" id="node-dialog-login-'+field.id+'" type="'+field.type+'"/>').appendTo(row);
row.appendTo("#node-dialog-login-fields");
}
$('<div class="form-row" style="text-align: right"><span id="node-dialog-login-failed" style="line-height: 2em;float:left;" class="hide">Login failed</span><img src="spin.svg" style="height: 30px" class="login-spinner hide"/> <a href="#" id="node-dialog-login-submit">Login</a></div>').appendTo("#node-dialog-login-fields");
$("#node-dialog-login-submit").button().click(function( event ) {
$("#node-dialog-login-submit").button("option","disabled",true);
$("#node-dialog-login-failed").hide();
$(".login-spinner").show();
var body = {
client_id: "node-red-admin",
grant_type: "password",
scope:"*"
}
for (var i=0;i<data.prompts.length;i++) {
var field = data.prompts[i];
body[field.id] = $("#node-dialog-login-"+field.id).val();
}
$.ajax({
url:"auth/token",
type: "POST",
data: body
}).done(function(data,textStatus,xhr) {
RED.settings.set("auth-tokens",data);
$("#node-dialog-login").dialog("close");
load();
}).fail(function(jqXHR,textStatus,errorThrown) {
RED.settings.remove("auth-tokens");
$("#node-dialog-login-failed").show();
}).always(function() {
$("#node-dialog-login-submit").button("option","disabled",false);
$(".login-spinner").hide();
});
event.preventDefault();
});
}
dialog.dialog("open");
}
});
}
function load() {
RED.settings.init(function(err,msg) {
if (err) {
if (err === 401) {
showLogin();
} else {
console.log("Unexpected error:",err,msg);
}
} else {
loadEditor();
}
});
}
$(function() {
if ((window.location.hostname !== "localhost") && (window.location.hostname !== "127.0.0.1")) {
document.title = "Node-RED : "+window.location.hostname;
}
$("#btn-deploy").hide();
$("#btn-sidemenu").hide();
load();
RED.settings.init(loadEditor);
});

View File

@ -16,6 +16,9 @@
RED.settings = (function () {
var loadedSettings = {};
var hasLocalStorage = function () {
try {
return 'localStorage' in window && window['localStorage'] !== null;
@ -51,15 +54,20 @@ RED.settings = (function () {
};
var setProperties = function(data) {
for(var prop in data) {
if(data.hasOwnProperty(prop)) {
for (var prop in loadedSettings) {
if (loadedSettings.hasOwnProperty(prop) && RED.settings.hasOwnProperty(prop)) {
delete RED.settings[prop];
}
}
for (prop in data) {
if (data.hasOwnProperty(prop)) {
RED.settings[prop] = data[prop];
}
}
loadedSettings = data;
};
var init = function (done) {
$.ajaxSetup({
beforeSend: function(jqXHR,settings) {
// Only attach auth header for requests to relative paths
@ -71,6 +79,11 @@ RED.settings = (function () {
}
}
});
load(done);
}
var load = function(done) {
$.ajax({
headers: {
@ -81,11 +94,18 @@ RED.settings = (function () {
url: 'settings',
success: function (data) {
setProperties(data);
if (RED.settings.user && RED.settings.user.anonymous) {
RED.settings.remove("auth-tokens");
}
console.log("Node-RED: " + data.version);
done(null);
done();
},
error: function(jqXHR,textStatus,errorThrown) {
done(jqXHR.status,textStatus);
if (jqXHR.status === 401) {
RED.user.login(function() { load(done); });
} else {
console.log("Unexpected error:",jqXHR.status,textStatus);
}
}
});
};
@ -93,6 +113,7 @@ RED.settings = (function () {
return {
init: init,
load: load,
set: set,
get: get,
remove: remove

View File

@ -140,7 +140,13 @@ RED.menu = (function() {
var button = $("#"+options.id);
var topMenu = $("<ul/>",{id:options.id+"-submenu", class:"dropdown-menu"}).insertAfter(button);
//button.click(function(event) {
// $("#"+options.id+"-submenu").show();
// event.preventDefault();
//});
var topMenu = $("<ul/>",{id:options.id+"-submenu", class:"dropdown-menu pull-right"}).insertAfter(button);
for (var i=0;i<options.options.length;i++) {
var opt = options.options[i];

117
public/red/user.js Normal file
View File

@ -0,0 +1,117 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
RED.user = (function() {
function login(opts,done) {
if (typeof opts == 'function') {
done = opts;
opts = {};
}
var dialog = $('<div id="node-dialog-login" class="hide">'+
'<div style="display: inline-block;width: 250px; vertical-align: top; margin-right: 10px; margin-bottom: 20px;"><img src="node-red-256.png"/></div>'+
'<div style="display: inline-block; width: 250px; vertical-align: bottom; margin-left: 10px; margin-bottom: 20px;">'+
'<form id="node-dialog-login-fields" class="form-horizontal" style="margin-bottom: 0px;"></form>'+
'</div>'+
'</div>');
dialog.dialog({
autoOpen: false,
dialogClass: "ui-dialog-no-close",
modal: true,
closeOnEscape: false,
width: 600,
resizable: false,
draggable: false
});
$("#node-dialog-login-fields").empty();
$.ajax({
dataType: "json",
url: "auth/login",
success: function(data) {
if (data.type == "credentials") {
var i=0;
for (;i<data.prompts.length;i++) {
var field = data.prompts[i];
var row = $("<div/>",{class:"form-row"});
$('<label for="node-dialog-login-'+field.id+'">'+field.label+':</label><br/>').appendTo(row);
$('<input style="width: 100%" id="node-dialog-login-'+field.id+'" type="'+field.type+'" tabIndex="'+(i+1)+'"/>').appendTo(row);
row.appendTo("#node-dialog-login-fields");
}
$('<div class="form-row" style="text-align: right; margin-top: 10px;"><span id="node-dialog-login-failed" style="line-height: 2em;float:left;" class="hide">Login failed</span><img src="spin.svg" style="height: 30px; margin-right: 10px; " class="login-spinner hide"/>'+
(opts.cancelable?'<a href="#" id="node-dialog-login-cancel" style="margin-right: 20px;" tabIndex="'+(i+1)+'">Cancel</a>':'')+
'<a href="#" id="node-dialog-login-submit" tabIndex="'+(i+2)+'">Login</a></div>').appendTo("#node-dialog-login-fields");
$("#node-dialog-login-submit").button().click(function( event ) {
$("#node-dialog-login-submit").button("option","disabled",true);
$("#node-dialog-login-failed").hide();
$(".login-spinner").show();
var body = {
client_id: "node-red-admin",
grant_type: "password",
scope:"*"
}
for (var i=0;i<data.prompts.length;i++) {
var field = data.prompts[i];
body[field.id] = $("#node-dialog-login-"+field.id).val();
}
$.ajax({
url:"auth/token",
type: "POST",
data: body
}).done(function(data,textStatus,xhr) {
RED.settings.set("auth-tokens",data);
$("#node-dialog-login").dialog('destroy').remove();
done();
}).fail(function(jqXHR,textStatus,errorThrown) {
RED.settings.remove("auth-tokens");
$("#node-dialog-login-failed").show();
}).always(function() {
$("#node-dialog-login-submit").button("option","disabled",false);
$(".login-spinner").hide();
});
event.preventDefault();
});
if (opts.cancelable) {
$("#node-dialog-login-cancel").button().click(function( event ) {
$("#node-dialog-login").dialog('destroy').remove();
});
}
}
dialog.dialog("open");
}
});
}
function logout() {
$.ajax({
url: "auth/revoke",
type: "POST",
data: {token:RED.settings.get("auth-tokens").access_token},
success: function() {
RED.settings.remove("auth-tokens");
document.location.reload(true);
}
})
}
return {
login: login,
logout: logout
}
})();

View File

@ -18,23 +18,29 @@ var passport = require("passport");
var oauth2orize = require("oauth2orize");
var strategies = require("./strategies");
var tokens = require("./tokens");
var Tokens = require("./tokens");
var Users = require("./users");
var settings = require("../../settings");
passport.use(strategies.bearerStrategy.BearerStrategy);
passport.use(strategies.clientPasswordStrategy.ClientPasswordStrategy);
passport.use(strategies.anonymousStrategy);
var server = oauth2orize.createServer();
server.exchange(oauth2orize.exchange.password(strategies.passwordTokenExchange));
function init() {
Users.init();
}
function authenticate(req,res,next) {
if (settings.adminAuth) {
if (/^\/auth\/.*/.test(req.originalUrl)) {
next();
} else {
return passport.authenticate('bearer', { session: false })(req,res,next);
return passport.authenticate(['bearer','anon'], { session: false })(req,res,next);
}
} else {
next();
@ -59,18 +65,18 @@ function login(req,res) {
"type":"credentials",
"prompts":[{id:"username",type:"text",label:"Username"},{id:"password",type:"password",label:"Password"}]
}
res.json(response);
}
function revoke(req,res) {
var token = req.body.token;
tokens.revoke(token).then(function() {
Tokens.revoke(token).then(function() {
res.send(200);
});
}
module.exports = {
init: init,
authenticate: authenticate,
ensureClientSecret: ensureClientSecret,
authenticateClient: authenticateClient,

View File

@ -0,0 +1,50 @@
/**
* Copyright 2014 IBM Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
var util = require('util');
var readRE = /^(.*)\.read$/
var writeRE = /^(.*)\.write$/
function needsPermission(perm) {
return function(req,res,next) {
if (!req.user) {
return next();
}
if (hasPermission(req.user,perm)) {
return next();
}
return res.send(401);
}
}
function hasPermission(user,permission) {
if (!user.permissions) {
return false;
}
if (user.permissions == "*") {
return true;
}
if (user.permissions == "read") {
return readRE.test(permission);
}
}
module.exports = {
hasPermission: hasPermission,
needsPermission: needsPermission,
}

View File

@ -16,9 +16,10 @@
var BearerStrategy = require('passport-http-bearer').Strategy;
var ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy;
var passport = require("passport");
var crypto = require("crypto");
var util = require("util");
var Tokens = require("./tokens");
var Users = require("./users");
var Clients = require("./clients");
@ -29,7 +30,7 @@ var bearerStrategy = function (accessToken, done) {
if (token) {
Users.get(token.user).then(function(user) {
if (user) {
done(null,{username:user.username},{scope:token.scope});
done(null,user,{scope:token.scope});
} else {
done(null,false);
}
@ -53,19 +54,38 @@ var clientPasswordStrategy = function(clientId, clientSecret, done) {
clientPasswordStrategy.ClientPasswordStrategy = new ClientPasswordStrategy(clientPasswordStrategy);
var passwordTokenExchange = function(client, username, password, scope, done) {
Users.get(username,password).then(function(user) {
Users.authenticate(username,password).then(function(user) {
if (user) {
Tokens.create(username,client.id,scope).then(function(token) {
done(null,token);
});
} else {
done(new Error("Invalid"),false);
done(null,false);
}
});
}
function AnonymousStrategy() {
passport.Strategy.call(this);
this.name = 'anon';
}
util.inherits(AnonymousStrategy, passport.Strategy);
AnonymousStrategy.prototype.authenticate = function(req) {
var authorization = req.headers['authorization'];
var self = this;
Users.anonymous().then(function(anon) {
if (anon) {
self.success(anon);
} else {
self.fail(401);
}
});
}
module.exports = {
bearerStrategy: bearerStrategy,
clientPasswordStrategy: clientPasswordStrategy,
passwordTokenExchange: passwordTokenExchange
passwordTokenExchange: passwordTokenExchange,
anonymousStrategy: new AnonymousStrategy()
}

View File

@ -19,30 +19,79 @@ var crypto = require("crypto");
var util = require("util");
var settings = require("../../settings");
/*
adminAuth: {
type: "credentials",
users: [{
username: "nol",
password: "5f4dcc3b5aa765d61d8327deb882cf99" // password
}],
anonymous: {}
},
adminAuth: {
type: "credentials",
api: {
get: function(username) {}
authenticate: function(username,password) {}
anonymous: function() {}
}
*/
//{username:"nick",password:crypto.createHash('md5').update("foo",'utf8').digest('hex')}
var users = {};
var passwords = {};
var api = {};
var anonymousUser = null;
if (settings.adminAuth) {
if (settings.adminAuth.type == "credentials") {
if (settings.adminAuth.users) {
if (util.isArray(settings.adminAuth.users)) {
for (var i=0;i<settings.adminAuth.users.length;i++) {
var u = settings.adminAuth.users[i];
users[u.username] = {
"username":u.username
};
passwords[u.username] = u.password;
var api = {
get: function(username) {
return when.resolve(null);
},
authenticate: function(username,password) {
return when.resolve(null);
},
anonymous: function() {
return when.resolve(null);
}
}
function init() {
users = {};
passwords = {};
anonymousUser = null;
if (settings.adminAuth) {
if (settings.adminAuth.type == "credentials") {
if (settings.adminAuth.api) {
api.get = settings.adminAuth.api.get || api.get;
api.authenticate = settings.adminAuth.api.authenticate || api.authenticate;
api.anonymous = settings.adminAuth.api.anonymous || api.anonymous;
} else {
if (settings.adminAuth.users) {
var us = settings.adminAuth.users;
if (!util.isArray(us)) {
us = [us];
}
for (var i=0;i<us.length;i++) {
var u = us[i];
users[u.username] = {
"username":u.username,
"permissions":u.permissions
};
passwords[u.username] = u.password;
}
}
var api = {
if (settings.adminAuth.anonymous) {
anonymousUser = {
"anonymous": true,
"permissions":settings.adminAuth.anonymous.permissions
}
}
api = {
get: function(username) {
return when.resolve(users[username]);
},
authenticate: function(username,password) {
return api.get(username).then(function(user) {
if (user) {
if (user) {
var pass = crypto.createHash('md5').update(password,'utf8').digest('hex');
if (pass == passwords[username]) {
return when.resolve(user);
@ -50,15 +99,20 @@ if (settings.adminAuth) {
}
return when.resolve(null);
});
},
anonymous: function() {
return when.resolve(anonymousUser);
}
}
} else {
api = settings.adminAuth.users;
}
}
}
}
module.exports = api;
module.exports = {
init: init,
get: function(username) { return api.get(username) },
authenticate: function(username,password) { return api.authenticate(username,password) },
anonymous: function() { return api.anonymous(); }
};

View File

@ -16,6 +16,7 @@
var express = require("express");
var util = require('util');
var path = require('path');
var passport = require('passport');
var ui = require("./ui");
@ -25,6 +26,7 @@ var library = require("./library");
var info = require("./info");
var auth = require("./auth");
var needsPermission = require("./auth/permissions").needsPermission;
var settings = require("../settings");
@ -35,6 +37,7 @@ var errorHandler = function(err,req,res,next) {
function init(adminApp) {
auth.init();
// Editor
if (!settings.disableEditor) {
@ -62,28 +65,28 @@ function init(adminApp) {
adminApp.post("/auth/revoke",auth.revoke);
// Flows
adminApp.get("/flows",flows.get);
adminApp.post("/flows",flows.post);
adminApp.get("/flows",needsPermission("flows.read"),flows.get);
adminApp.post("/flows",needsPermission("flows.write"),flows.post);
// Nodes
adminApp.get("/nodes",nodes.getAll);
adminApp.post("/nodes",nodes.post);
adminApp.get("/nodes",needsPermission("nodes.read"),nodes.getAll);
adminApp.post("/nodes",needsPermission("nodes.write"),nodes.post);
adminApp.get("/nodes/:mod",nodes.getModule);
adminApp.put("/nodes/:mod",nodes.putModule);
adminApp.delete("/nodes/:mod",nodes.delete);
adminApp.get("/nodes/:mod",needsPermission("nodes.read"),nodes.getModule);
adminApp.put("/nodes/:mod",needsPermission("nodes.write"),nodes.putModule);
adminApp.delete("/nodes/:mod",needsPermission("nodes.write"),nodes.delete);
adminApp.get("/nodes/:mod/:set",nodes.getSet);
adminApp.put("/nodes/:mod/:set",nodes.putSet);
adminApp.get("/nodes/:mod/:set",needsPermission("nodes.read"),nodes.getSet);
adminApp.put("/nodes/:mod/:set",needsPermission("nodes.write"),nodes.putSet);
// Library
library.init(adminApp);
adminApp.post(new RegExp("/library/flows\/(.*)"),library.post);
adminApp.get("/library/flows",library.getAll);
adminApp.get(new RegExp("/library/flows\/(.*)"),library.get);
adminApp.post(new RegExp("/library/flows\/(.*)"),needsPermission("library.write"),library.post);
adminApp.get("/library/flows",needsPermission("library.read"),library.getAll);
adminApp.get(new RegExp("/library/flows\/(.*)"),needsPermission("library.read"),library.get);
// Settings
adminApp.get("/settings",info.settings);
adminApp.get("/settings",needsPermission("settings.read"),info.settings);
// Error Handler
adminApp.use(errorHandler);

View File

@ -14,8 +14,6 @@
* limitations under the License.
**/
var tokens = require("./api/auth/tokens");
var ws = require("ws");
var log = require("./log");
@ -37,24 +35,23 @@ function init(_server,_settings) {
settings = _settings;
}
function start() {
function start() {
var Tokens = require("./api/auth/tokens");
var Users = require("./api/auth/users");
var Permissions = require("./api/auth/permissions");
if (!settings.disableEditor) {
var webSocketKeepAliveTime = settings.webSocketKeepAliveTime || 15000;
var path = settings.httpAdminRoot || "/";
path = path + (path.slice(-1) == "/" ? "":"/") + "comms";
wsServer = new ws.Server({server:server,path:path});
wsServer.on('connection',function(ws) {
var pendingAuth = (settings.adminAuth != null);
if (!pendingAuth) {
activeConnections.push(ws);
} else {
pendingConnections.push(ws);
}
ws.on('close',function() {
Users.anonymous().then(function(anonymousUser) {
var webSocketKeepAliveTime = settings.webSocketKeepAliveTime || 15000;
var path = settings.httpAdminRoot || "/";
path = path + (path.slice(-1) == "/" ? "":"/") + "comms";
wsServer = new ws.Server({server:server,path:path});
wsServer.on('connection',function(ws) {
var pendingAuth = (settings.adminAuth != null);
if (!pendingAuth) {
removeActiveConnection(ws);
activeConnections.push(ws);
} else {
removePendingConnection(ws);
}
@ -67,31 +64,64 @@ function start() {
log.warn("comms received malformed message : "+err.toString());
return;
}
if (!pendingAuth) {
if (msg.subscribe) {
handleRemoteSubscription(ws,msg.subscribe);
ws.on('close',function() {
removeActiveConnection(ws);
removePendingConnection(ws);
});
ws.on('message', function(data,flags) {
var msg = null;
try {
msg = JSON.parse(data);
} catch(err) {
util.log("[red:comms] received malformed message : "+err.toString());
return;
}
} else {
if (msg.auth) {
tokens.get(msg.auth).then(function(client) {
if (!client) {
if (!pendingAuth) {
if (msg.subscribe) {
handleRemoteSubscription(ws,msg.subscribe);
}
} else {
var completeConnection = function(user) {
if (!user || !Permissions.hasPermission(user,"status.read")) {
ws.close();
} else {
pendingAuth = false;
removePendingConnection(ws);
activeConnections.push(ws);
ws.send(JSON.stringify({auth:"ok"}));
}
});
} else {
ws.close();
}
if (msg.auth) {
Tokens.get(msg.auth).then(function(client) {
if (client) {
Users.get(client.user).then(completeConnection);
} else {
completeConnection(null);
}
});
} else {
completeConnection(anonymousUser);
}
}
}
});
ws.on('error', function(err) {
util.log("[red:comms] error : "+err.toString());
});
});
ws.on('error', function(err) {
log.warn("comms error : "+err.toString());
});
lastSentTime = Date.now();
heartbeatTimer = setInterval(function() {
var now = Date.now();
if (now-lastSentTime > webSocketKeepAliveTime) {
publish("hb",lastSentTime);
}
}, webSocketKeepAliveTime);
});
wsServer.on('error', function(err) {
log.warn("comms server error : "+err.toString());
});

View File

@ -23,6 +23,7 @@ var util = require("./util");
var fs = require("fs");
var settings = require("./settings");
var credentials = require("./nodes/credentials");
var permissions = require("./api/auth/permissions");
var path = require('path');
@ -50,6 +51,9 @@ var RED = {
comms: comms,
settings:settings,
util: util,
auth: {
needsPermission: permissions.needsPermission
},
version: function () {
var p = require(path.join(process.env.NODE_RED_HOME,"package.json"));
if (fs.existsSync(path.join(process.env.NODE_RED_HOME,".git"))) {

View File

@ -83,9 +83,6 @@ var persistentSettings = {
userSettings = null;
globalSettings = null;
storage = null;
}
}

View File