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

@ -80,7 +80,7 @@ module.exports = function(RED) {
} }
} }
RED.httpAdmin.post("/inject/:id", function(req,res) { RED.httpAdmin.post("/inject/:id", RED.auth.needsPermission("inject.write"), function(req,res) {
var node = RED.nodes.getNode(req.params.id); var node = RED.nodes.getNode(req.params.id);
if (node != null) { if (node != null) {
try { try {

View File

@ -119,7 +119,7 @@ module.exports = function(RED) {
}); });
RED.log.addHandler(DebugNode.logHandler); 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 node = RED.nodes.getNode(req.params.id);
var state = req.params.state; var state = req.params.state;
if (node !== null && typeof node !== "undefined" ) { 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" 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> <a id="btn-deploy-options" data-toggle="dropdown" class="" href="#"><i class="fa fa-caret-down"></i></a>
</span></li> </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> <li><a id="btn-sidemenu" class="button" data-toggle="dropdown" href="#"><i class="fa fa-bars"></i></a></li>
<ul> <ul>
</div> </div>
@ -240,14 +240,6 @@
</div> </div>
</script> </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="jquery/js/jquery-1.11.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script> <script src="bootstrap/js/bootstrap.min.js"></script>
<script src="jquery/js/jquery-ui-1.10.3.custom.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="d3.v3.min.js"></script>
<script src="red/main.js"></script> <script src="red/main.js"></script>
<script src="red/settings.js"></script> <script src="red/settings.js"></script>
<script src="red/user.js"></script>
<script src="red/comms.js"></script> <script src="red/comms.js"></script>
<script src="red/ui/state.js"></script> <script src="red/ui/state.js"></script>
<script src="red/nodes.js"></script> <script src="red/nodes.js"></script>

View File

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

View File

@ -311,34 +311,46 @@ var RED = (function() {
}); });
if (RED.settings.user) { if (RED.settings.user) {
$("#header .username").html(RED.settings.user.username); RED.menu.init({id:"btn-usermenu",
$("#header .user").show(); options: []
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);
}
})
}
}); });
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(); $("#main-container").show();
$("#btn-deploy").show(); $(".header-toolbar").show();
$("#btn-sidemenu").show();
RED.library.init(); RED.library.init();
RED.palette.init(); RED.palette.init();
@ -350,91 +362,13 @@ var RED = (function() {
loadNodeList(); 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() { $(function() {
if ((window.location.hostname !== "localhost") && (window.location.hostname !== "127.0.0.1")) { if ((window.location.hostname !== "localhost") && (window.location.hostname !== "127.0.0.1")) {
document.title = "Node-RED : "+window.location.hostname; 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 () { RED.settings = (function () {
var loadedSettings = {};
var hasLocalStorage = function () { var hasLocalStorage = function () {
try { try {
return 'localStorage' in window && window['localStorage'] !== null; return 'localStorage' in window && window['localStorage'] !== null;
@ -51,15 +54,20 @@ RED.settings = (function () {
}; };
var setProperties = function(data) { var setProperties = function(data) {
for(var prop in data) { 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)) { if (data.hasOwnProperty(prop)) {
RED.settings[prop] = data[prop]; RED.settings[prop] = data[prop];
} }
} }
loadedSettings = data;
}; };
var init = function (done) { var init = function (done) {
$.ajaxSetup({ $.ajaxSetup({
beforeSend: function(jqXHR,settings) { beforeSend: function(jqXHR,settings) {
// Only attach auth header for requests to relative paths // Only attach auth header for requests to relative paths
@ -72,6 +80,11 @@ RED.settings = (function () {
} }
}); });
load(done);
}
var load = function(done) {
$.ajax({ $.ajax({
headers: { headers: {
"Accept": "application/json" "Accept": "application/json"
@ -81,11 +94,18 @@ RED.settings = (function () {
url: 'settings', url: 'settings',
success: function (data) { success: function (data) {
setProperties(data); setProperties(data);
if (RED.settings.user && RED.settings.user.anonymous) {
RED.settings.remove("auth-tokens");
}
console.log("Node-RED: " + data.version); console.log("Node-RED: " + data.version);
done(null); done();
}, },
error: function(jqXHR,textStatus,errorThrown) { 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 { return {
init: init, init: init,
load: load,
set: set, set: set,
get: get, get: get,
remove: remove remove: remove

View File

@ -140,7 +140,13 @@ RED.menu = (function() {
var button = $("#"+options.id); 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++) { for (var i=0;i<options.options.length;i++) {
var opt = options.options[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 oauth2orize = require("oauth2orize");
var strategies = require("./strategies"); var strategies = require("./strategies");
var tokens = require("./tokens"); var Tokens = require("./tokens");
var Users = require("./users");
var settings = require("../../settings"); var settings = require("../../settings");
passport.use(strategies.bearerStrategy.BearerStrategy); passport.use(strategies.bearerStrategy.BearerStrategy);
passport.use(strategies.clientPasswordStrategy.ClientPasswordStrategy); passport.use(strategies.clientPasswordStrategy.ClientPasswordStrategy);
passport.use(strategies.anonymousStrategy);
var server = oauth2orize.createServer(); var server = oauth2orize.createServer();
server.exchange(oauth2orize.exchange.password(strategies.passwordTokenExchange)); server.exchange(oauth2orize.exchange.password(strategies.passwordTokenExchange));
function init() {
Users.init();
}
function authenticate(req,res,next) { function authenticate(req,res,next) {
if (settings.adminAuth) { if (settings.adminAuth) {
if (/^\/auth\/.*/.test(req.originalUrl)) { if (/^\/auth\/.*/.test(req.originalUrl)) {
next(); next();
} else { } else {
return passport.authenticate('bearer', { session: false })(req,res,next); return passport.authenticate(['bearer','anon'], { session: false })(req,res,next);
} }
} else { } else {
next(); next();
@ -59,18 +65,18 @@ function login(req,res) {
"type":"credentials", "type":"credentials",
"prompts":[{id:"username",type:"text",label:"Username"},{id:"password",type:"password",label:"Password"}] "prompts":[{id:"username",type:"text",label:"Username"},{id:"password",type:"password",label:"Password"}]
} }
res.json(response); res.json(response);
} }
function revoke(req,res) { function revoke(req,res) {
var token = req.body.token; var token = req.body.token;
tokens.revoke(token).then(function() { Tokens.revoke(token).then(function() {
res.send(200); res.send(200);
}); });
} }
module.exports = { module.exports = {
init: init,
authenticate: authenticate, authenticate: authenticate,
ensureClientSecret: ensureClientSecret, ensureClientSecret: ensureClientSecret,
authenticateClient: authenticateClient, 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 BearerStrategy = require('passport-http-bearer').Strategy;
var ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy; var ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy;
var passport = require("passport");
var crypto = require("crypto"); var crypto = require("crypto");
var util = require("util");
var Tokens = require("./tokens"); var Tokens = require("./tokens");
var Users = require("./users"); var Users = require("./users");
var Clients = require("./clients"); var Clients = require("./clients");
@ -29,7 +30,7 @@ var bearerStrategy = function (accessToken, done) {
if (token) { if (token) {
Users.get(token.user).then(function(user) { Users.get(token.user).then(function(user) {
if (user) { if (user) {
done(null,{username:user.username},{scope:token.scope}); done(null,user,{scope:token.scope});
} else { } else {
done(null,false); done(null,false);
} }
@ -53,13 +54,31 @@ var clientPasswordStrategy = function(clientId, clientSecret, done) {
clientPasswordStrategy.ClientPasswordStrategy = new ClientPasswordStrategy(clientPasswordStrategy); clientPasswordStrategy.ClientPasswordStrategy = new ClientPasswordStrategy(clientPasswordStrategy);
var passwordTokenExchange = function(client, username, password, scope, done) { var passwordTokenExchange = function(client, username, password, scope, done) {
Users.get(username,password).then(function(user) { Users.authenticate(username,password).then(function(user) {
if (user) { if (user) {
Tokens.create(username,client.id,scope).then(function(token) { Tokens.create(username,client.id,scope).then(function(token) {
done(null,token); done(null,token);
}); });
} else { } 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);
} }
}); });
} }
@ -67,5 +86,6 @@ var passwordTokenExchange = function(client, username, password, scope, done) {
module.exports = { module.exports = {
bearerStrategy: bearerStrategy, bearerStrategy: bearerStrategy,
clientPasswordStrategy: clientPasswordStrategy, clientPasswordStrategy: clientPasswordStrategy,
passwordTokenExchange: passwordTokenExchange passwordTokenExchange: passwordTokenExchange,
anonymousStrategy: new AnonymousStrategy()
} }

View File

@ -19,24 +19,73 @@ var crypto = require("crypto");
var util = require("util"); var util = require("util");
var settings = require("../../settings"); 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')} //{username:"nick",password:crypto.createHash('md5').update("foo",'utf8').digest('hex')}
var users = {}; var users = {};
var passwords = {}; var passwords = {};
var api = {}; var anonymousUser = null;
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) {
if (settings.adminAuth.type == "credentials") { 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) { if (settings.adminAuth.users) {
if (util.isArray(settings.adminAuth.users)) { var us = settings.adminAuth.users;
for (var i=0;i<settings.adminAuth.users.length;i++) { if (!util.isArray(us)) {
var u = settings.adminAuth.users[i]; us = [us];
}
for (var i=0;i<us.length;i++) {
var u = us[i];
users[u.username] = { users[u.username] = {
"username":u.username "username":u.username,
"permissions":u.permissions
}; };
passwords[u.username] = u.password; passwords[u.username] = u.password;
} }
var api = { }
if (settings.adminAuth.anonymous) {
anonymousUser = {
"anonymous": true,
"permissions":settings.adminAuth.anonymous.permissions
}
}
api = {
get: function(username) { get: function(username) {
return when.resolve(users[username]); return when.resolve(users[username]);
}, },
@ -50,15 +99,20 @@ if (settings.adminAuth) {
} }
return when.resolve(null); return when.resolve(null);
}); });
} },
} anonymous: function() {
} else { return when.resolve(anonymousUser);
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 express = require("express");
var util = require('util'); var util = require('util');
var path = require('path');
var passport = require('passport'); var passport = require('passport');
var ui = require("./ui"); var ui = require("./ui");
@ -25,6 +26,7 @@ var library = require("./library");
var info = require("./info"); var info = require("./info");
var auth = require("./auth"); var auth = require("./auth");
var needsPermission = require("./auth/permissions").needsPermission;
var settings = require("../settings"); var settings = require("../settings");
@ -35,6 +37,7 @@ var errorHandler = function(err,req,res,next) {
function init(adminApp) { function init(adminApp) {
auth.init();
// Editor // Editor
if (!settings.disableEditor) { if (!settings.disableEditor) {
@ -62,28 +65,28 @@ function init(adminApp) {
adminApp.post("/auth/revoke",auth.revoke); adminApp.post("/auth/revoke",auth.revoke);
// Flows // Flows
adminApp.get("/flows",flows.get); adminApp.get("/flows",needsPermission("flows.read"),flows.get);
adminApp.post("/flows",flows.post); adminApp.post("/flows",needsPermission("flows.write"),flows.post);
// Nodes // Nodes
adminApp.get("/nodes",nodes.getAll); adminApp.get("/nodes",needsPermission("nodes.read"),nodes.getAll);
adminApp.post("/nodes",nodes.post); adminApp.post("/nodes",needsPermission("nodes.write"),nodes.post);
adminApp.get("/nodes/:mod",nodes.getModule); adminApp.get("/nodes/:mod",needsPermission("nodes.read"),nodes.getModule);
adminApp.put("/nodes/:mod",nodes.putModule); adminApp.put("/nodes/:mod",needsPermission("nodes.write"),nodes.putModule);
adminApp.delete("/nodes/:mod",nodes.delete); adminApp.delete("/nodes/:mod",needsPermission("nodes.write"),nodes.delete);
adminApp.get("/nodes/:mod/:set",nodes.getSet); adminApp.get("/nodes/:mod/:set",needsPermission("nodes.read"),nodes.getSet);
adminApp.put("/nodes/:mod/:set",nodes.putSet); adminApp.put("/nodes/:mod/:set",needsPermission("nodes.write"),nodes.putSet);
// Library // Library
library.init(adminApp); library.init(adminApp);
adminApp.post(new RegExp("/library/flows\/(.*)"),library.post); adminApp.post(new RegExp("/library/flows\/(.*)"),needsPermission("library.write"),library.post);
adminApp.get("/library/flows",library.getAll); adminApp.get("/library/flows",needsPermission("library.read"),library.getAll);
adminApp.get(new RegExp("/library/flows\/(.*)"),library.get); adminApp.get(new RegExp("/library/flows\/(.*)"),needsPermission("library.read"),library.get);
// Settings // Settings
adminApp.get("/settings",info.settings); adminApp.get("/settings",needsPermission("settings.read"),info.settings);
// Error Handler // Error Handler
adminApp.use(errorHandler); adminApp.use(errorHandler);

View File

@ -14,8 +14,6 @@
* limitations under the License. * limitations under the License.
**/ **/
var tokens = require("./api/auth/tokens");
var ws = require("ws"); var ws = require("ws");
var log = require("./log"); var log = require("./log");
@ -37,9 +35,14 @@ function init(_server,_settings) {
settings = _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) { if (!settings.disableEditor) {
Users.anonymous().then(function(anonymousUser) {
var webSocketKeepAliveTime = settings.webSocketKeepAliveTime || 15000; var webSocketKeepAliveTime = settings.webSocketKeepAliveTime || 15000;
var path = settings.httpAdminRoot || "/"; var path = settings.httpAdminRoot || "/";
path = path + (path.slice(-1) == "/" ? "":"/") + "comms"; path = path + (path.slice(-1) == "/" ? "":"/") + "comms";
@ -49,12 +52,6 @@ function start() {
var pendingAuth = (settings.adminAuth != null); var pendingAuth = (settings.adminAuth != null);
if (!pendingAuth) { if (!pendingAuth) {
activeConnections.push(ws); activeConnections.push(ws);
} else {
pendingConnections.push(ws);
}
ws.on('close',function() {
if (!pendingAuth) {
removeActiveConnection(ws);
} else { } else {
removePendingConnection(ws); removePendingConnection(ws);
} }
@ -67,31 +64,64 @@ function start() {
log.warn("comms received malformed message : "+err.toString()); log.warn("comms received malformed message : "+err.toString());
return; return;
} }
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;
}
if (!pendingAuth) { if (!pendingAuth) {
if (msg.subscribe) { if (msg.subscribe) {
handleRemoteSubscription(ws,msg.subscribe); handleRemoteSubscription(ws,msg.subscribe);
} }
} else { } else {
if (msg.auth) { var completeConnection = function(user) {
tokens.get(msg.auth).then(function(client) { if (!user || !Permissions.hasPermission(user,"status.read")) {
if (!client) {
ws.close(); ws.close();
} else { } else {
pendingAuth = false; pendingAuth = false;
removePendingConnection(ws); removePendingConnection(ws);
activeConnections.push(ws); activeConnections.push(ws);
ws.send(JSON.stringify({auth:"ok"}));
}
}
if (msg.auth) {
Tokens.get(msg.auth).then(function(client) {
if (client) {
Users.get(client.user).then(completeConnection);
} else {
completeConnection(null);
} }
}); });
} else { } else {
ws.close(); completeConnection(anonymousUser);
} }
} }
}); });
ws.on('error', function(err) { ws.on('error', function(err) {
log.warn("comms error : "+err.toString()); 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) { wsServer.on('error', function(err) {
log.warn("comms server error : "+err.toString()); log.warn("comms server error : "+err.toString());
}); });

View File

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

View File

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

View File