update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b third try
Signed-off-by: Jeremy Mordkoff <Jeremy.Mordkoff@riftio.com>
Change-Id: Ib11aa03a2eff5a53c808342508a5d7bee7b202b8
diff --git a/skyquake/framework/core/api_utils/auth.js b/skyquake/framework/core/api_utils/auth.js
new file mode 100644
index 0000000..7249ac7
--- /dev/null
+++ b/skyquake/framework/core/api_utils/auth.js
@@ -0,0 +1,145 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * Auth util for use across the api_server.
+ * @module framework/core/api_utils/auth
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ */
+
+var jsonLoader = require('require-json');
+var passport = require('passport');
+var OpenIdConnectStrategy = require('passport-openidconnect').Strategy;
+var BearerStrategy = require('passport-http-bearer').Strategy;
+var OAuth2Strategy = require('passport-oauth2');
+var OAuth2RefreshTokenStrategy = require('passport-oauth2-middleware').Strategy;
+var openidConnectConfig = require('./openidconnect_config.json');
+var _ = require('lodash');
+var constants = require('./constants');
+var utils = require('./utils');
+var request = utils.request;
+var rp = require('request-promise');
+var nodeutil = require('util');
+
+
+var Authorization = function(openidConfig) {
+
+ var self = this;
+
+ self.passport = passport;
+
+ self.openidConnectConfig = openidConnectConfig;
+
+ var refreshStrategy = new OAuth2RefreshTokenStrategy({
+ refreshWindow: constants.REFRESH_WINDOW, // Time in seconds to perform a token refresh before it expires
+ userProperty: 'user', // Active user property name to store OAuth tokens
+ authenticationURL: '/login', // URL to redirect unauthorized users to
+ callbackParameter: 'callback' //URL query parameter name to pass a return URL
+ });
+
+ self.passport.use('main', refreshStrategy);
+
+ var openidConfigPrefix = openidConfig.idpServerProtocol + '://' + openidConfig.idpServerAddress + ':' + openidConfig.idpServerPortNumber;
+
+ self.openidConnectConfig.authorizationURL = openidConfigPrefix + self.openidConnectConfig.authorizationURL;
+ self.openidConnectConfig.tokenURL = openidConfigPrefix + self.openidConnectConfig.tokenURL;
+ self.openidConnectConfig.callbackURL = openidConfig.callbackServerProtocol + '://' + openidConfig.callbackAddress + ':' + openidConfig.callbackPortNumber + self.openidConnectConfig.callbackURL;
+
+ var userInfoURL = openidConfigPrefix + self.openidConnectConfig.userInfoURL;
+
+ function SkyquakeOAuth2Strategy(options, verify) {
+ OAuth2Strategy.call(this, options, verify);
+ }
+ nodeutil.inherits(SkyquakeOAuth2Strategy, OAuth2Strategy);
+
+ SkyquakeOAuth2Strategy.prototype.userProfile = function(access_token, done) {
+
+ var requestHeaders = {
+ 'Authorization': 'Bearer ' + access_token
+ };
+
+ request({
+ url: userInfoURL,
+ type: 'GET',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: constants.REJECT_UNAUTHORIZED
+ }, function(err, response, body) {
+ if (err) {
+ console.log('Error obtaining userinfo: ', err);
+ return done(null, {
+ username: '',
+ subject: ''
+ });
+ } else {
+ if (response.statusCode == constants.HTTP_RESPONSE_CODES.SUCCESS.OK) {
+ try {
+ var data = JSON.parse(response.body);
+ var username = data['preferred_username'];
+ var subject = data['sub'];
+ var domain = data['user_domain'] || 'system';
+ return done(null, {
+ username: username,
+ subject: subject,
+ domain: domain
+ })
+ } catch (ex) {
+ console.log('Error parsing userinfo data');
+ return done(null, {
+ username: '',
+ subject: ''
+ });
+ }
+ }
+ }
+ })
+ };
+
+ var oauthStrategy = new SkyquakeOAuth2Strategy(self.openidConnectConfig,
+ refreshStrategy.getOAuth2StrategyCallback());
+
+ self.passport.use('oauth2', oauthStrategy);
+ refreshStrategy.useOAuth2Strategy(oauthStrategy);
+
+ self.passport.serializeUser(function(user, done) {
+ done(null, user);
+ });
+
+ self.passport.deserializeUser(function(obj, done) {
+ done(null, obj);
+ });
+
+};
+
+Authorization.prototype.configure = function(config) {
+ this.config = config;
+ // Initialize Passport and restore authentication state, if any, from the
+ // session.
+ if (this.config.app) {
+ this.config.app.use(this.passport.initialize());
+ this.config.app.use(this.passport.session());
+ } else {
+ console.log('FATAL error. Bad config passed into authorization module');
+ }
+};
+
+Authorization.prototype.invalidate_token = function(token) {
+
+};
+
+module.exports = Authorization;
diff --git a/skyquake/framework/core/api_utils/constants.js b/skyquake/framework/core/api_utils/constants.js
index 0aac7d2..b27e7da 100644
--- a/skyquake/framework/core/api_utils/constants.js
+++ b/skyquake/framework/core/api_utils/constants.js
@@ -73,11 +73,21 @@
constants.SOCKET_POOL_LENGTH = 20;
constants.SERVER_PORT = process.env.SERVER_PORT || 8000;
constants.SECURE_SERVER_PORT = process.env.SECURE_SERVER_PORT || 8443;
+constants.REJECT_UNAUTHORIZED = false;
-constants.BASE_PACKAGE_UPLOAD_DESTINATION = 'upload/packages/';
+constants.BASE_PACKAGE_UPLOAD_DESTINATION = 'upload';
constants.PACKAGE_MANAGER_SERVER_PORT = 4567;
constants.PACKAGE_FILE_DELETE_DELAY_MILLISECONDS = 3 * 1000 * 60; //5 minutes
constants.PACKAGE_FILE_ONBOARD_TRANSACTION_STATUS_CHECK_DELAY_MILLISECONDS = 2 * 1000; //2 seconds
+constants.REFRESH_WINDOW = 10; //Time in seconds to perform a token refresh before it expires
+constants.LAUNCHPAD_ADDRESS = 'localhost';
+constants.LAUNCHPAD_PORT = 8008;
+constants.IDP_SERVER_PROTOCOL = 'https';
+constants.IDP_PORT_NUMBER = 8009;
+constants.CALLBACK_SERVER_PROTOCOL = 'https';
+constants.CALLBACK_PORT_NUMBER = 8443;
+constants.CALLBACK_ADDRESS = 'localhost';
+constants.END_SESSION_PATH = 'end_session';
module.exports = constants;
\ No newline at end of file
diff --git a/skyquake/framework/core/api_utils/csrf.js b/skyquake/framework/core/api_utils/csrf.js
new file mode 100644
index 0000000..62855f2
--- /dev/null
+++ b/skyquake/framework/core/api_utils/csrf.js
@@ -0,0 +1,67 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * CSRF util for use across the api_server.
+ * @module framework/core/api_utils/csrf
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ */
+
+var constants = require('./constants.js');
+var utils = require('./utils.js');
+
+var target = null;
+
+function configure(config) {
+ target = config.target;
+}
+
+function csrfCheck(req, res, next) {
+ var host = null;
+
+ if (req.headers.origin != 'null') {
+ host = utils.getHostNameFromURL(req.headers.origin);
+ } else if (req.headers.referer) {
+ host = utils.getHostNameFromURL(req.headers.referer);
+ } else {
+ var msg = 'Request did not contain an origin or referer header. Request terminated.';
+ var error = {};
+ error.statusCode = constants.HTTP_RESPONSE_CODES.ERROR.METHOD_NOT_ALLOWED;
+ error.errorMessage = {
+ error: msg
+ }
+ return utils.sendErrorResponse(error, res);
+ }
+
+ if (!host || host != target) {
+ var msg = 'Request did not originate from authorized source (Potential CSRF attempt). Request terminated.';
+ var error = {};
+ error.statusCode = constants.HTTP_RESPONSE_CODES.ERROR.METHOD_NOT_ALLOWED;
+ error.errorMessage = {
+ error: msg
+ }
+ return utils.sendErrorResponse(error, res);
+ } else {
+ return next();
+ }
+}
+
+module.exports = {
+ configure: configure,
+ csrfCheck: csrfCheck
+};
\ No newline at end of file
diff --git a/skyquake/framework/core/api_utils/openidconnect_config.json b/skyquake/framework/core/api_utils/openidconnect_config.json
new file mode 100644
index 0000000..63c4a1d
--- /dev/null
+++ b/skyquake/framework/core/api_utils/openidconnect_config.json
@@ -0,0 +1,9 @@
+{
+ "scope": "openid",
+ "clientID": "cncudWkub3BlbmlkY2xpZW50",
+ "clientSecret": "riftiorocks",
+ "authorizationURL": "/authorization",
+ "tokenURL": "/token",
+ "userInfoURL": "/userinfo",
+ "callbackURL": "/callback"
+}
\ No newline at end of file
diff --git a/skyquake/framework/core/api_utils/sockets.js b/skyquake/framework/core/api_utils/sockets.js
index 5e0b25b..a86f5ed 100644
--- a/skyquake/framework/core/api_utils/sockets.js
+++ b/skyquake/framework/core/api_utils/sockets.js
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -33,6 +33,7 @@
var sockjs = require('sockjs');
var websocket_multiplex = require('websocket-multiplex');
var utils = require('./utils.js');
+var configurationAPI = require('../modules/api/configuration.js');
var Subscriptions = function() {
@@ -182,7 +183,7 @@
if (Type == PollingSocket) {
Socket = new Type(url, req, 1000, req.body);
} else {
- Socket = new Type(url);
+ Socket = new Type(url, ['Bearer', req.session.passport.user.user['access_token']]);
}
console.log('Socket assigned for url', url);
}
@@ -278,12 +279,12 @@
self.isClosed = false;
var requestHeaders = {};
_.extend(requestHeaders, {
- 'Authorization': req.get('Authorization')
+ Cookie: req.get('Cookie')
});
var pollServer = function() {
Request({
- url: url,
+ url: utils.projectContextUrl(req, url),
method: config.method || 'GET',
headers: requestHeaders,
json: config.payload,
@@ -294,7 +295,11 @@
console.log('Error polling: ' + url);
} else {
if (!self.isClosed) {
- self.poll = setTimeout(pollServer, 1000 || interval);
+ if(process.env.DISABLE_POLLING != "TRUE") {
+ self.poll = setTimeout(pollServer, 1000 || interval);
+ } else {
+ console.log('Polling is disabled. Finishing request.')
+ }
var data = response.body;
if (self.onmessage) {
self.onmessage(data);
diff --git a/skyquake/framework/core/api_utils/utils.js b/skyquake/framework/core/api_utils/utils.js
index 5b17279..cdf12fc 100644
--- a/skyquake/framework/core/api_utils/utils.js
+++ b/skyquake/framework/core/api_utils/utils.js
@@ -49,6 +49,41 @@
return api_server + ':' + CONFD_PORT;
};
+var projectContextUrl = function(req, url) {
+ //NOTE: We need to go into the sessionStore because express-session
+ // does not reliably update the session.
+ // See https://github.com/expressjs/session/issues/450
+ var projectId = (req.session &&
+ req.sessionStore &&
+ req.sessionStore.sessions &&
+ req.sessionStore.sessions[req.session.id] &&
+ JSON.parse(req.sessionStore.sessions[req.session.id])['projectId']) ||
+ (null);
+ if (projectId) {
+ projectId = encodeURIComponent(projectId);
+ return url.replace(/(\/api\/operational\/|\/api\/config\/)(.*)/, '$1project/' + projectId + '/$2');
+ }
+ return url;
+}
+
+var addProjectContextToRPCPayload = function(req, url, inputPayload) {
+ //NOTE: We need to go into the sessionStore because express-session
+ // does not reliably update the session.
+ // See https://github.com/expressjs/session/issues/450
+ var projectId = (req.session &&
+ req.sessionStore &&
+ req.sessionStore.sessions &&
+ req.sessionStore.sessions[req.session.id] &&
+ JSON.parse(req.sessionStore.sessions[req.session.id])['projectId']) ||
+ (null);
+ if (projectId) {
+ if (url.indexOf('/api/operations/')) {
+ inputPayload['project-name'] = projectId;
+ }
+ }
+ return inputPayload;
+}
+
var validateResponse = function(callerName, error, response, body, resolve, reject) {
var res = {};
@@ -61,12 +96,12 @@
};
reject(res);
return false;
- } else if (response.statusCode >= 400) {
+ } else if (response.statusCode >= CONSTANTS.HTTP_RESPONSE_CODES.ERROR.BAD_REQUEST) {
console.log('Problem with "', callerName, '": ', response.statusCode, ':', body);
res.statusCode = response.statusCode;
// auth specific
- if (response.statusCode == 401) {
+ if (response.statusCode == CONSTANTS.HTTP_RESPONSE_CODES.ERROR.UNAUTHORIZED) {
res.errorMessage = {
error: 'Authentication needed' + body
};
@@ -81,7 +116,7 @@
reject(res);
return false;
- } else if (response.statusCode == 204) {
+ } else if (response.statusCode == CONSTANTS.HTTP_RESPONSE_CODES.SUCCESS.NO_CONTENT) {
resolve({
statusCode: response.statusCode,
data: {}
@@ -95,7 +130,7 @@
var checkAuthorizationHeader = function(req) {
return new Promise(function(resolve, reject) {
- if (req.get('Authorization') == null) {
+ if (req.session && req.session.authorization == null) {
reject();
} else {
resolve();
@@ -119,12 +154,12 @@
reject(res);
fs.appendFileSync(logFile, 'Request API: ' + response.request.uri.href + ' ; ' + 'Error: ' + error);
return false;
- } else if (response.statusCode >= 400) {
+ } else if (response.statusCode >= CONSTANTS.HTTP_RESPONSE_CODES.ERROR.BAD_REQUEST) {
console.log('Problem with "', callerName, '": ', response.statusCode, ':', body);
res.statusCode = response.statusCode;
// auth specific
- if (response.statusCode == 401) {
+ if (response.statusCode == CONSTANTS.HTTP_RESPONSE_CODES.ERROR.UNAUTHORIZED) {
res.errorMessage = {
error: 'Authentication needed' + body
};
@@ -140,7 +175,7 @@
reject(res);
fs.appendFileSync(logFile, 'Request API: ' + response.request.uri.href + ' ; ' + 'Error Body: ' + body);
return false;
- } else if (response.statusCode == 204) {
+ } else if (response.statusCode == CONSTANTS.HTTP_RESPONSE_CODES.SUCCESS.NO_CONTENT) {
resolve();
fs.appendFileSync(logFile, 'Request API: ' + response.request.uri.href + ' ; ' + 'Response Body: ' + body);
return false;
@@ -162,6 +197,9 @@
* @param {Function} res - a handle to the express response function
*/
var sendErrorResponse = function(error, res) {
+ if (!error.statusCode) {
+ console.error('Status Code has not been set in error object: ', error);
+ }
res.status(error.statusCode);
res.send(error);
}
@@ -197,10 +235,10 @@
}
new Promise(function(resolve, reject) {
request({
- uri: uri,
+ uri: projectContextUrl(req, uri),
method: 'GET',
headers: _.extend({}, CONSTANTS.HTTP_HEADERS.accept[type], {
- 'Authorization': req.get('Authorization'),
+ 'Authorization': req.session && req.session.authorization,
forever: CONSTANTS.FOREVER_ON,
rejectUnauthorized: false,
})
@@ -226,6 +264,31 @@
}
}
+var buildRedirectURL = function(req, globalConfiguration, plugin, extra) {
+ var api_server = req.query['api_server'] || (req.protocol + '://' + globalConfiguration.get().api_server);
+ var download_server = req.query['dev_download_server'] || globalConfiguration.get().dev_download_server;
+ var url = '/';
+ url += plugin;
+ url += '/?api_server=' + api_server;
+ url += download_server ? '&dev_download_server=' + download_server : '';
+ url += extra || '';
+ return url;
+}
+
+var getHostNameFromURL = function(url) {
+ var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([^?#]*)(\?[^#]*|)(#.*|)$/);
+ return match && match[3];
+}
+
+var dataToJsonSansPropNameNamespace = function(s) {
+ var a = JSON.parse(s);
+ var b = JSON.stringify(a);
+ var c = b.replace(/{"[-\w]+:/g, '{"');
+ var d = c.replace(/,"[-\w]+:/g, ',"');
+ var j = JSON.parse(d);
+ return j;
+}
+
module.exports = {
/**
* Ensure confd port is on api_server variable.
@@ -244,5 +307,15 @@
passThroughConstructor: passThroughConstructor,
- getPortForProtocol: getPortForProtocol
+ getPortForProtocol: getPortForProtocol,
+
+ projectContextUrl: projectContextUrl,
+
+ addProjectContextToRPCPayload: addProjectContextToRPCPayload,
+
+ buildRedirectURL: buildRedirectURL,
+
+ getHostNameFromURL: getHostNameFromURL,
+
+ dataToJsonSansPropNameNamespace: dataToJsonSansPropNameNamespace
};
diff --git a/skyquake/framework/core/modules/api/appConfigAPI.js b/skyquake/framework/core/modules/api/appConfigAPI.js
new file mode 100644
index 0000000..ce93bdc
--- /dev/null
+++ b/skyquake/framework/core/modules/api/appConfigAPI.js
@@ -0,0 +1,119 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+// DescriptorModelMeta API (NSD + VNFD)
+
+
+var Schema = {};
+var request = require('request');
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var _ = require('lodash');
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var utils = require('../../api_utils/utils');
+var sessionAPI = require('./sessions.js');
+var configuration = require('./configuration');
+
+var router = require('express').Router();
+
+router.use(bodyParser.json());
+router.use(cors());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+router.get('/app-config', cors(), function (req, res) {
+ getConfig(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+var inactivityTimeout = process.env.UI_TIMEOUT_SECS || 600000;
+
+var versionPromise = null;
+
+var init = function () {
+ versionPromise = new Promise(
+ function (resolve, reject) {
+ sessionAPI.sessionPromise.then(
+ function (session) {
+ request({
+ url: configuration.getBackendURL() + '/api/operational/version',
+ type: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false
+ },
+ function (error, response, body) {
+ var data;
+ if (utils.validateResponse('schema/version.get', error, response, body, resolve, reject)) {
+ try {
+ data = JSON.parse(response.body)['rw-base:version'];
+ resolve(data.version);
+ } catch (e) {
+ return reject({});
+ }
+ } else {
+ console.log(error);
+ }
+ });
+ });
+ });
+}
+
+var getConfig = function (req) {
+ var api_server = req.query['api_server'];
+
+ var requests = [versionPromise];
+
+ return new Promise(function (resolve, reject) {
+ Promise.all(requests).then(
+ function (results) {
+ var data = {
+ version: results[0],
+ 'api-server': configuration.getBackendURL,
+ 'inactivity-timeout': process.env.UI_TIMEOUT_SECS || 600000
+ }
+ resolve({
+ data: data,
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+ });
+ }).catch(
+ function (error) {
+ var response = {};
+ console.log('Problem with config.get', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to get config' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+module.exports = {
+ getRouter: function () {
+ return router;
+ },
+ init: init
+};
\ No newline at end of file
diff --git a/skyquake/framework/core/modules/api/configuration.js b/skyquake/framework/core/modules/api/configuration.js
index 3762643..d1fca27 100644
--- a/skyquake/framework/core/modules/api/configuration.js
+++ b/skyquake/framework/core/modules/api/configuration.js
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,7 +30,11 @@
var _ = require('lodash');
var GLOBAL_CONFIGURATION = {
api_server: 'localhost',
- ssl_enabled: true
+ ssl_enabled: true,
+ api_server_port_number: constants.SECURE_SERVER_PORT,
+ idp_server_address: constants.LAUNCHPAD_ADDRESS,
+ idp_server_protocol: constants.IDP_SERVER_PROTOCOL,
+ idp_server_port_number: constants.IDP_PORT_NUMBER
};
/**
@@ -92,4 +96,18 @@
return GLOBAL_CONFIGURATION;
};
+var backendURL = null;
+configurationAPI.getBackendURL = function () {
+ if (!backendURL) {
+ backendURL = GLOBAL_CONFIGURATION.api_server_protocol + '://' + GLOBAL_CONFIGURATION.api_server + ':' + GLOBAL_CONFIGURATION.api_server_port_number;
+ }
+ return backendURL;
+}
+
+configurationAPI.getBackendAPI = function () {
+ return configurationAPI.getBackendURL() + '/v2/api';
+}
+
+
+
module.exports = configurationAPI;
diff --git a/skyquake/framework/core/modules/api/descriptorModelMetaAPI.js b/skyquake/framework/core/modules/api/descriptorModelMetaAPI.js
index b0223b2..34d30b3 100644
--- a/skyquake/framework/core/modules/api/descriptorModelMetaAPI.js
+++ b/skyquake/framework/core/modules/api/descriptorModelMetaAPI.js
@@ -36,7 +36,7 @@
uri: utils.confdPort(api_server) + '/api/schema/nsd-catalog/nsd',
method: 'GET',
headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
- 'Authorization': req.get('Authorization')
+ 'Authorization': req.session && req.session.authorization
}),
forever: constants.FOREVER_ON,
rejectUnauthorized: false,
@@ -46,7 +46,7 @@
uri: utils.confdPort(api_server) + '/api/schema/vnfd-catalog/vnfd',
method: 'GET',
headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
- 'Authorization': req.get('Authorization')
+ 'Authorization': req.session && req.session.authorization
}),
forever: constants.FOREVER_ON,
rejectUnauthorized: false,
diff --git a/skyquake/framework/core/modules/api/modelAPI.js b/skyquake/framework/core/modules/api/modelAPI.js
new file mode 100644
index 0000000..1f14cb7
--- /dev/null
+++ b/skyquake/framework/core/modules/api/modelAPI.js
@@ -0,0 +1,359 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+// DescriptorModelMeta API (NSD + VNFD)
+
+
+var Schema = {};
+var rp = require('request-promise');
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var _ = require('lodash');
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var utils = require('../../api_utils/utils');
+var configuration = require('./configuration');
+
+var router = require('express').Router();
+
+
+router.use(bodyParser.json());
+router.use(cors());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+router.get('/model', cors(), function (req, res) {
+ get(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+router.patch('/model', cors(), function (req, res) {
+ update(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+router.put('/model', cors(), function (req, res) {
+ add(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+router.delete('/model', cors(), function (req, res) {
+ remove(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+module.exports = {
+ getRouter: function () {
+ return router;
+ },
+ init: function () {}
+};
+
+get = function (req) {
+ var backend = configuration.getBackendAPI();
+ var modelPath = req.query['path'];
+ var requestHeaders = _.extend({}, constants.HTTP_HEADERS.accept.collection, {
+ 'Authorization': req.session && req.session.authorization
+ })
+ return new Promise(function (resolve, reject) {
+ Promise.all([
+ rp({
+ uri: backend + '/config' + modelPath,
+ method: 'GET',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ // }),
+ // rp({
+ // uri: utils.projectContextUrl(req, backend + '/api/operational' + modelPath),
+ // method: 'GET',
+ // headers: requestHeaders,
+ // forever: constants.FOREVER_ON,
+ // rejectUnauthorized: false,
+ // resolveWithFullResponse: true
+ })
+ ]).then(function (results) {
+ var response = {
+ statusCode: results[0].statusCode || 200,
+ data: [null]
+ }
+ if (results[0].body && !results[0].error) {
+ var result = JSON.parse(results[0].body);
+ if (result.collection) {
+ result = result.collection[Object.keys(result.collection)[0]];
+ if (!result.length) {
+ result = null;
+ } else if (result.length === 1) {
+ result = result[0];
+ }
+ }
+ response.data = result;
+ }
+ resolve(response);
+
+ }).catch(function (error) {
+ var res = {};
+ console.log('Problem with model get', error);
+ res.statusCode = error.statusCode || 500;
+ res.errorMessage = {
+ error: 'Failed to get model: ' + error
+ };
+ reject(res);
+ });
+ });
+};
+
+add = function (req) {
+ var backend = configuration.getBackendAPI();
+ var modelPath = req.query['path'];
+ var targetProperty = modelPath.split('/').pop();
+ var newElement = {};
+ var data = {};
+ console.log(req.body);
+ _.forIn(req.body, function (value, key) {
+ if (_.isObject(value)) {
+ if (value.type === 'leaf_empty') {
+ if (value.data) {
+ data[key] = ' ';
+ }
+ } else if (value.type === 'leaf_list') {
+ data[key] = value.data.add;
+ }
+ } else {
+ data[key] = value;
+ }
+ });
+ newElement[targetProperty] = [data];
+ console.log(newElement);
+ var target = backend + '/config' + modelPath;
+ var method = 'POST'
+ var requestHeaders = _.extend({},
+ constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ });
+ return new Promise(function (resolve, reject) {
+ rp({
+ uri: target,
+ method: method,
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ json: newElement,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ }).then(function (results) {
+ var response = {};
+ response.data = {
+ path: modelPath,
+ data: data
+ };
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK;
+ console.log(response);
+ resolve(response);
+ }).catch(function (result) {
+ var response = {};
+ var error = {};
+ if (result.error['rpc-reply']) {
+ error.type = result.error['rpc-reply']['rpc-error']['error-tag'];
+ error.message = result.error['rpc-reply']['rpc-error']['error-message'];
+ error.rpcError = result.error['rpc-reply']['rpc-error']
+ } else {
+ error.type = 'api-error';
+ error.message = 'invalid api call';
+ }
+ console.log('Problem with model update', error);
+ response.statusCode = error.statusCode || 500;
+ response.error = error;
+ reject(response);
+ });
+ });
+};
+
+update = function (req) {
+ var backend = configuration.getBackendAPI();
+ var modelPath = req.query['path'];
+ var requestHeaders = _.extend({},
+ constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ });
+ var base = backend + '/config' + modelPath + '/';
+
+ function getUpdatePromise(name, value) {
+ var data = {};
+ data[name] = value;
+ return new Promise(function (resolve, reject) {
+ rp({
+ uri: base + name,
+ method: value ? 'PATCH' : 'DELETE',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ }).then(function (result) {
+ resolve({
+ element: name,
+ success: true,
+ value: value
+ });
+ }).catch(function (result) {
+ var error = {};
+ if (result.error['rpc-reply']) {
+ error.type = result.error['rpc-reply']['rpc-error']['error-tag'];
+ error.message = result.error['rpc-reply']['rpc-error']['error-message'];
+ error.rpcError = result.error['rpc-reply']['rpc-error']
+ } else {
+ error.type = 'api-error';
+ error.message = 'invalid api call';
+ }
+ resolve({
+ element: name,
+ success: false,
+ error: error,
+ value: value
+ });
+ })
+ })
+ }
+
+ function getDeletePromise(targetProp, item) {
+ if (item) {
+ targetProp = targetProp + '/' + item;
+ }
+ return getUpdatePromise(targetProp, '');
+ }
+
+ var updates = [];
+ _.forIn(req.body, function (value, key) {
+ var data = {};
+ if (_.isObject(value)) {
+ if (value.type === 'leaf_list') {
+ _.forEach(value.data.remove, function (v) {
+ updates.push(getDeletePromise(key))
+ })
+ _.forEach(value.data.add, function (v) {
+ updates.push(getUpdatePromise(key, v))
+ })
+ } else if (value.type === 'leaf_empty') {
+ if (value.data) {
+ updates.push(getUpdatePromise(key, ' '))
+ } else {
+ updates.push(getDeletePromise(key))
+ }
+ }
+ } else {
+ updates.push(getUpdatePromise(key, value))
+ }
+ })
+
+ return new Promise(function (resolve, reject) {
+ Promise.all(updates).then(function (results) {
+ var response = {};
+ var output = {};
+ var hasError = false;
+ _.forEach(results, function (result) {
+ var record = {};
+ if (output[result.element]) {
+ if (_.isArray(output[result.element].value)) {
+ output[result.element].value.push(result.value);
+ } else {
+ output[result.element].value = [output[result.element].value, result.value];
+ }
+ } else {
+ output[result.element] = result;
+ }
+ hasError = hasError || !result.success
+ })
+ response.data = {
+ result: output,
+ hasError: hasError
+ };
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK;
+ console.log(response);
+ resolve(response);
+ }).catch(function (result) {
+ var response = {};
+ var error = {};
+ if (result.error['rpc-reply']) {
+ error.type = result.error['rpc-reply']['rpc-error']['error-tag'];
+ error.message = result.error['rpc-reply']['rpc-error']['error-message'];
+ error.rpcError = result.error['rpc-reply']['rpc-error']
+ } else {
+ error.type = 'api-error';
+ error.message = 'invalid api call';
+ }
+ console.log('Problem with model update', error);
+ response.statusCode = error.statusCode || 500;
+ response.error = error;
+ reject(response);
+ });
+ });
+};
+
+remove = function (req) {
+ var backend = configuration.getBackendAPI();
+ var modelPath = req.query['path'];
+ var target = backend + '/config' + modelPath;
+ var requestHeaders = _.extend({},
+ constants.HTTP_HEADERS.accept.data,
+ constants.HTTP_HEADERS.content_type.data, {
+ 'Authorization': req.session && req.session.authorization
+ })
+ return new Promise(function (resolve, reject) {
+ rp({
+ url: target,
+ method: 'DELETE',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ }).then(function (response) {
+ return resolve({
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
+ data: modelPath
+ });
+ }).catch(function (result) {
+ var response = {};
+ var error = {};
+ if (result.error['rpc-reply']) {
+ error.type = result.error['rpc-reply']['rpc-error']['error-tag'];
+ error.message = result.error['rpc-reply']['rpc-error']['error-message'];
+ error.rpcError = result.error['rpc-reply']['rpc-error']
+ } else {
+ error.type = 'api-error';
+ error.message = 'invalid api call';
+ }
+ console.log('Problem with model update', error);
+ response.statusCode = error.statusCode || 500;
+ response.error = error;
+ reject(response);
+ });
+ })
+}
\ No newline at end of file
diff --git a/skyquake/framework/core/modules/api/projectManagementAPI.js b/skyquake/framework/core/modules/api/projectManagementAPI.js
new file mode 100644
index 0000000..d65e890
--- /dev/null
+++ b/skyquake/framework/core/modules/api/projectManagementAPI.js
@@ -0,0 +1,297 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+// DescriptorModelMeta API (NSD + VNFD)
+
+
+var ProjectManagement = {};
+var Promise = require('bluebird');
+var rp = require('request-promise');
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var _ = require('lodash');
+var API_VERSION = 'v2';
+ProjectManagement.get = function(req, fields) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ // by default just load basic info as this request is expensive
+ fields = fields || ['name', 'description', 'project-config'];
+ var select = fields.length ? '?fields=' + fields.join(';') : '';
+
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: `${utils.confdPort(api_server)}/${API_VERSION}/api/operational/project` + select,
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data']['project'] = JSON.parse(result[0].body)['rw-project:project'];
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with ProjectManagement.get', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to get ProjectManagement' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+ProjectManagement.create = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var data = req.body;
+ data = {
+ "project":[data]
+ }
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/project',
+ method: 'POST',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with ProjectManagement.create', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to create user' + error
+ };
+ reject(response);
+ });
+ });
+};
+ProjectManagement.update = function(req) {
+ //"rw-project:project"
+ var self = this;
+ var api_server = req.query['api_server'];
+ var bodyData = req.body;
+ // oddly enough, if we do not encode this here letting the request below does so incorrectly
+ var projectName = encodeURIComponent(bodyData.name);
+ var descriptionData = {
+ "rw-project:project" : {
+ "name": bodyData.name,
+ "description": bodyData.description
+ }
+ }
+ var updateTasks = [];
+ var baseUrl = utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/project/' + projectName
+ var updateProjectConfig = rp({
+ uri: baseUrl + '/project-config',
+ method: 'PUT',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: {
+ "project-config": bodyData['project-config']
+ },
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ updateTasks.push(updateProjectConfig);
+
+ var updateProjectDescription = rp({
+ uri: baseUrl + '/description',
+ method: 'PATCH',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: {"description": bodyData.description},
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ updateTasks.push(updateProjectDescription)
+ return new Promise(function(resolve, reject) {
+ Promise.all(
+ updateTasks
+ ).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with ProjectManagement.update', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to update project - ' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+ProjectManagement.delete = function(req) {
+ var self = this;
+ var projectname = encodeURIComponent(req.params.projectname);
+ var api_server = req.query["api_server"];
+ var requestHeaders = {};
+ var url = utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/project/' + projectname
+ return new Promise(function(resolve, reject) {
+ _.extend(requestHeaders,
+ constants.HTTP_HEADERS.accept.data,
+ constants.HTTP_HEADERS.content_type.data, {
+ 'Authorization': req.session && req.session.authorization
+ });
+ rp({
+ url: url,
+ method: 'DELETE',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ }, function(error, response, body) {
+ if (utils.validateResponse('ProjectManagement.DELETE', error, response, body, resolve, reject)) {
+ return resolve({
+ statusCode: response.statusCode,
+ data: JSON.stringify(response.body)
+ });
+ };
+ });
+ })
+}
+
+
+ProjectManagement.getPlatform = function(req, userId) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var user = req.params['userId'] || userId;
+ return new Promise(function(resolve, reject) {
+ var url = utils.confdPort(api_server) + '/' + API_VERSION + '/api/operational/rbac-platform-config';
+ if(user) {
+ url = url + '/user/' + encodeURIComponent(user);
+ }
+ Promise.all([
+ rp({
+ uri: url,
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ if(user) {
+ response['data']['platform'] = JSON.parse(result[0].body)['rw-rbac-platform:user'];
+ } else {
+ response['data']['platform'] = JSON.parse(result[0].body)['rw-rbac-platform:rbac-platform-config'];
+ }
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with ProjectManagement.getPlatform', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to get ProjectManagement.getPlatform' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+ProjectManagement.updatePlatform = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var bodyData = req.body;
+ data = bodyData;
+ data.user = JSON.parse(data.user)
+ var updateTasks = [];
+
+ var updatePlatform = rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/rbac-platform-config',
+ method: 'PUT',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: {
+ "rw-rbac-platform:rbac-platform-config": data
+ },
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ updateTasks.push(updatePlatform)
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ updateTasks
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with ProjectManagement.updatePlatform', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to update platform - ' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+
+module.exports = ProjectManagement;
diff --git a/skyquake/framework/core/modules/api/restconf.js b/skyquake/framework/core/modules/api/restconf.js
index 5ba0eb5..03f2721 100644
--- a/skyquake/framework/core/modules/api/restconf.js
+++ b/skyquake/framework/core/modules/api/restconf.js
@@ -45,7 +45,7 @@
url: uri + url + '?deep',
method: 'GET',
headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
- 'Authorization': req.get('Authorization')
+ 'Authorization': req.session && req.session.authorization
}),
forever: constants.FOREVER_ON,
rejectUnauthorized: false,
diff --git a/skyquake/framework/core/modules/api/schemaAPI.js b/skyquake/framework/core/modules/api/schemaAPI.js
new file mode 100644
index 0000000..34c83be
--- /dev/null
+++ b/skyquake/framework/core/modules/api/schemaAPI.js
@@ -0,0 +1,100 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+// DescriptorModelMeta API (NSD + VNFD)
+
+
+var Schema = {};
+var rp = require('request-promise');
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var _ = require('lodash');
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var utils = require('../../api_utils/utils');
+var configuration = require('./configuration');
+
+var router = require('express').Router();
+
+
+router.use(bodyParser.json());
+router.use(cors());
+router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+router.get('/schema', cors(), function (req, res) {
+ getSchema(req).then(function (response) {
+ utils.sendSuccessResponse(response, res);
+ }, function (error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+module.exports = {
+ getRouter: function () {
+ return router;
+ },
+ init: function () {}
+};
+
+getSchema = function (req) {
+ var schemaURI = configuration.getBackendURL() + '/api/schema/';
+ var schemaPaths = req.query['request'];
+ var paths = schemaPaths.split(',');
+
+ function getSchemaRequest(path) {
+ return rp({
+ uri: schemaURI + path,
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.collection, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ }
+
+ var requests = _.map(paths, getSchemaRequest);
+
+ return new Promise(function (resolve, reject) {
+ Promise.all(requests).then(
+ function (results) {
+ var data = {
+ schema: {}
+ }
+ _.forEach(results, function (result, index) {
+ data.schema[paths[index]] = JSON.parse(result.body);
+ });
+ resolve({
+ data: data,
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+ });
+ }).catch(
+ function (error) {
+ var response = {};
+ console.log('Problem with schema.get', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to get schema' + error
+ };
+ reject(response);
+ });
+ });
+};
\ No newline at end of file
diff --git a/skyquake/framework/core/modules/api/sessions.js b/skyquake/framework/core/modules/api/sessions.js
new file mode 100644
index 0000000..f168724
--- /dev/null
+++ b/skyquake/framework/core/modules/api/sessions.js
@@ -0,0 +1,294 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * sessions api module. Provides API functions for sessions
+ * @module framework/core/modules/api/sessions
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ */
+"use strict"
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var request = utils.request;
+var rp = require('request-promise');
+var sessionsAPI = {};
+var _ = require('lodash');
+var base64 = require('base-64');
+var APIVersion = '/v2';
+var configurationAPI = require('./configuration');
+var UserManagement = require('./userManagementAPI.js');
+var URL = require('url');
+
+// Used for determining what page a user should first go to.
+var Application = {
+ order: [
+ "rw-rbac-platform:super-admin",
+ "rw-rbac-platform:platform-admin",
+ "rw-rbac-platform:platform-oper",
+ "rw-project:project-admin",
+ "rw-project:project-oper",
+ "rw-project-mano:lcm-admin",
+ "rw-project-mano:lcm-oper",
+ "rw-project-mano:catalog-admin",
+ "rw-project-mano:catalog-oper",
+ "rw-project-mano:account-admin",
+ "rw-project-mano:account-oper"
+ ],
+ key: {
+ "rw-rbac-platform:super-admin": "user_management",
+ "rw-rbac-platform:platform-admin": "user_management",
+ "rw-rbac-platform:platform-oper": "user_management",
+ "rw-project:project-admin": "project_management",
+ "rw-project:project-oper": "project_management",
+ "rw-project-mano:catalog-admin": "composer",
+ "rw-project-mano:catalog-oper": "composer",
+ "rw-project-mano:lcm-admin": "launchpad",
+ "rw-project-mano:lcm-oper": "launchpad",
+ "rw-project-mano:account-admin": "accounts",
+ "rw-project-mano:account-oper": "accounts"
+ }
+};
+
+function logAndReject(mesg, reject, errCode) {
+ var res = {};
+ res.errorMessage = {
+ error: mesg
+ }
+ res.statusCode = errCode || constants.HTTP_RESPONSE_CODES.ERROR.BAD_REQUEST;
+ console.log(mesg);
+ reject(res);
+}
+
+function logAndRedirectToLogin(mesg, res, req, invalid) {
+ console.log(mesg);
+ if (!invalid) {
+ res.redirect(utils.buildRedirectURL(req, configurationAPI.globalConfiguration, 'login', '&referer=' + encodeURIComponent(req.headers.referer)));
+ }
+ res.end();
+}
+
+function logAndRedirectToEndSession(mesg, res, authorization, url) {
+ console.log(mesg);
+ res.set({
+ 'Authorization': authorization
+ });
+ res.redirect(url);
+ res.end();
+}
+var sessionPromiseResolve = null;
+sessionsAPI.sessionPromise = new Promise(function(resolve, reject) {
+ sessionPromiseResolve = resolve;
+});
+
+sessionsAPI.create = function (req, res) {
+ if (!req.session.passport){
+ logAndRedirectToLogin("lost session", res, req);
+ return new Promise(function (resolve, reject){reject("lost session")});
+ }
+ var api_server = req.query['api_server'] || (req.protocol + '://' + configurationAPI.globalConfiguration.get().api_server);
+ var uri = utils.confdPort(api_server);
+ var username = req.session.passport.user['username'];
+ var authorization_header_string = 'Bearer ' + req.session.passport.user.user.access_token;
+ return new Promise(function (resolve, reject) {
+ req.session.authorization = authorization_header_string;
+ req.session.api_server = api_server;
+ req.session.api_protocal = req.protocol;
+ req.session.loggedIn = true;
+ req.session.userdata = {
+ username: username,
+ };
+ UserManagement.getUserInfo(req, req.session.passport.user.username).then(function (results) {
+ var project_list_for_user = null;
+ if (!req.session.projectId && results.data.project) {
+ project_list_for_user = Object.keys(results.data.project);
+ if (project_list_for_user.length > 0) {
+ req.session.projectId = project_list_for_user.sort() && project_list_for_user[0];
+ }
+ }
+ sessionsAPI.setTopApplication(req);
+ req.session.isLCM = results.data.isLCM;
+
+ req.session['ui-state'] = results.data['ui-state'];
+ var lastActiveProject = req.session['ui-state'] && req.session['ui-state']['last-active-project'];
+ if (lastActiveProject) {
+ if (results.data.project.hasOwnProperty(lastActiveProject)) {
+ req.session.projectId = lastActiveProject;
+ }
+
+ }
+
+ var successMsg = 'User => ' + username + ' successfully logged in.';
+ successMsg += req.session.projectId ? 'Project => ' + req.session.projectId + ' set as default.' : '';
+
+ console.log(successMsg);
+
+ req.session.save(function (err) {
+ if (err) {
+ console.log('Error saving session to store', err);
+ }
+ // no response data, just redirect now that session data is set
+ if (req.session['ui-state'] && req.session['ui-state']['last-active-uri']) {
+ var url = URL.parse(req.session['ui-state']['last-active-uri']);
+ var host = req.headers.host;
+ var path = url.path;
+ var hash = url.hash;
+ var protocol = url.protocol;
+ var newUrl = protocol + '//' + host + path + (hash?hash:'');
+ console.log('Redirecting to: ' + newUrl)
+ res.redirect(newUrl)
+ } else {
+ if(req.session.topApplication) {
+ res.redirect(utils.buildRedirectURL(req, configurationAPI.globalConfiguration, req.session.topApplication));
+ } else {
+ res.redirect(utils.buildRedirectURL(req, configurationAPI.globalConfiguration, 'user_management', '#/user-profile'));
+ }
+ }
+ })
+
+ sessionPromiseResolve(req.session);
+
+ }).catch(function (error) {
+ // Something went wrong - Redirect to /login
+ var errorMsg = 'Error logging in or getting list of projects. Error: ' + error;
+ console.log(errorMsg);
+ logAndRedirectToLogin(errorMsg, res, req);
+ });
+ })
+};
+
+sessionsAPI.addProjectToSession = function (req, res) {
+ return new Promise(function (resolve, reject) {
+ if (req.session && req.session.loggedIn == true) {
+ Promise.all([UserManagement.getProfile(req), UserManagement.updateActiveProject(req)]).then(function () {
+ req.session.projectId = req.params.projectId;
+ req.session.topApplication = null;
+ sessionsAPI.setTopApplication(req, req.query.app);
+ req.session.save(function (err) {
+ if (err) {
+ console.log('Error saving session to store', err);
+ var errorMsg = 'Session does not exist or not logged in';
+ logAndReject(errorMsg, reject, constants.HTTP_RESPONSE_CODES.ERROR.NOT_FOUND);
+ } else {
+ var successMsg = 'Added project ' + req.session.projectId + ' to session ' + req.sessionID;
+ console.log(successMsg);
+ var response = {
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
+ data: JSON.stringify({
+ status: successMsg
+ })
+ }
+ return resolve(response);
+ }
+ // res.redirect('/');
+ });
+
+ })
+
+ }
+ });
+}
+
+sessionsAPI.delete = function (req, res) {
+ var idpServerAddress = configurationAPI.globalConfiguration.get().idp_server_address;
+ var idpServerProtocol = configurationAPI.globalConfiguration.get().idp_server_protocol;
+ var idpServerPortNumber = configurationAPI.globalConfiguration.get().idp_server_port_number;
+ var idpEndSessionPath = constants.END_SESSION_PATH;
+ var url = idpServerProtocol + '://' +
+ idpServerAddress + ':' +
+ idpServerPortNumber + '/' +
+ idpEndSessionPath;
+ var authorization = req.session.authorization;
+ return new Promise(function (resolve, reject) {
+ Promise.all([
+ UserManagement.updateActiveUri(req),
+ new Promise(function (success, failure) {
+ req.session.destroy(function (err) {
+ if (err) {
+ var errorMsg = 'Error deleting session. Error: ' + err;
+ console.log(errorMsg);
+ success({
+ status: 'error',
+ message: errorMsg
+ });
+ }
+
+ var successMsg = 'Success deleting session';
+ console.log(successMsg);
+
+ success({
+ status: 'success',
+ message: successMsg
+ });
+ });
+ })
+ ]).then(function (result) {
+ // assume the session was deleted!
+ var message = 'Session was deleted. Redirecting to end_session';
+ resolve({
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
+ data: {
+ url: url,
+ message: message
+ }
+ });
+
+ }).catch(function (error) {
+ var message = "An error occured while deleting session";
+ resolve({
+ statusCode: constants.HTTP_RESPONSE_CODES.SUCCESS.OK,
+ data: {
+ url: url,
+ message: message
+ }
+ });
+ });
+ });
+}
+
+sessionsAPI.setTopApplication = function (req, suggestedPlugin) {
+ var selectedProject = req.session.projectId;
+ var userProject = selectedProject ? req.session.projectMap[selectedProject] : null;
+ if (userProject) {
+ if (suggestedPlugin) {
+ if (req.session.platformMap['rw-rbac-platform:super-admin']) {
+ topApplication = suggestedPlugin;
+ } else {
+ var roles = _.reduce(Object.keys(Application.key), function (accumulator, role) {
+ if (Application.key[role] === suggestedPlugin) {
+ accumulator.push(role);
+ }
+ return accumulator;
+ }, []);
+ if (_.some(roles, function (role){return userProject.role[role]})) {
+ req.session.topApplication = suggestedPlugin;
+ return;
+ }
+ }
+ }
+ _.some(Application.order, function (role) {
+ if (userProject.role[role] || req.session.platformMap.role[role]) {
+ req.session.topApplication = Application.key[role];
+ return true;
+ }
+ return false;
+ })
+ }
+}
+
+module.exports = sessionsAPI;
diff --git a/skyquake/framework/core/modules/api/userManagementAPI.js b/skyquake/framework/core/modules/api/userManagementAPI.js
new file mode 100644
index 0000000..834df7e
--- /dev/null
+++ b/skyquake/framework/core/modules/api/userManagementAPI.js
@@ -0,0 +1,530 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+// DescriptorModelMeta API (NSD + VNFD)
+
+
+var UserManagement = {};
+var Promise = require('bluebird');
+var rp = require('request-promise');
+var Promise = require('promise');
+var constants = require('../../api_utils/constants');
+var utils = require('../../api_utils/utils');
+var _ = require('lodash');
+var ProjectManagementAPI = require('./projectManagementAPI.js');
+var API_VERSION = 'v2';
+
+UserManagement.get = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+
+ return new Promise(function(resolve, reject) {
+ var userConfig = rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/operational/user-config/user',
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ var userOp = rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/operational/user-state/user',
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ Promise.all([
+ userConfig,
+ userOp
+ ]).then(function(result) {
+ var response = {};
+ var userConfig = [];
+ var userOpData = {};
+ response['data'] = {};
+ if (result[0].body) {
+ userConfig = JSON.parse(result[0].body)['rw-user:user'];
+ }
+ if (result[1].body) {
+ JSON.parse(result[1].body)['rw-user:user'].map(function(u) {
+ userOpData[u['user-domain'] + ',' + u['user-name']] = u;
+ })
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+ response['data']['user'] = userConfig.map(function(u,i) {
+ var mergedData = _.merge(u, userOpData[u['user-domain'] + ',' + u['user-name']]);
+ mergedData.projects = {
+ ids: [],
+ data: {}
+ };
+ var projects = mergedData.projects;
+ mergedData.role && mergedData.role.map(function(r) {
+ if ((r.role != "rw-project:user-self" )&& (r.role != "rw-rbac-platform:user-self")) {
+ var projectId = r.keys.split(';')[0];
+ if (projectId == "") {
+ projectId = "platform"
+ }
+ if (!projects.data[projectId]) {
+ projects.ids.push(projectId);
+ projects.data[projectId] = [];
+ }
+ projects.data[projectId].push(r.role);
+ }
+ })
+ return mergedData;
+ })
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.get', error);
+ response.statusCode = error.statusCode || constants.HTTP_RESPONSE_CODES.ERROR.INTERNAL_SERVER_ERROR;
+ response.errorMessage = {
+ error: 'Failed to get UserManagement' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+
+UserManagement.getProfile = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ return new Promise(function(resolve, reject) {
+ var response = {};
+ try {
+ var userId = req.session.userdata.username
+ response['data'] = {
+ userId: userId,
+ projectId: req.session.projectId,
+ domain: req.session.passport.user.domain
+ };
+ UserManagement.getUserInfo(req, userId).then(function(result) {
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK;
+ response.data.data = result.data
+ resolve(response);
+ }, function(error) {
+ console.log('Error retrieving getUserInfo');
+ response.statusCode = constants.HTTP_RESPONSE_CODES.ERROR.INTERNAL_SERVER_ERROR;
+ reject(response);
+ })
+ } catch (e) {
+ var response = {};
+ console.log('Problem with UserManagement.get', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to get UserManagement' + error
+ };
+ reject(response);
+ }
+ });
+};
+UserManagement.getUserInfo = function(req, userId, domain) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var id = req.params['userId'] || userId;
+ var domain = req.params['domainId'] || domain;
+ var response = {};
+ return new Promise(function(resolve, reject) {
+ if (id) {
+ var getProjects = ProjectManagementAPI.get(req, ['name', 'project-config']);
+ var getPlatformUser = ProjectManagementAPI.getPlatform(req, id);
+ var getUserUiState = UserManagement.getUserUiState(req);
+ Promise.all([
+ getProjects,
+ getPlatformUser,
+ getUserUiState
+ ]).then(function(result) {
+ var userData = {
+ platform: {
+ role: {
+
+ }
+ },
+ //id/key values for each project
+ projectId:[],
+ project: {
+ /**
+ * [projectId] : {
+ * data: [project object],
+ * role: {
+ * [roleId]: true
+ * }
+ * }
+ */
+ }
+ }
+ //Build UI state
+ var uiState = result[2].data && result[2].data['rw-user:user'];
+ userData['ui-state'] = uiState['ui-state'];
+ //Build platform roles
+ var platformRoles = result[1].data.platform && result[1].data.platform.role;
+ platformRoles && platformRoles.map(function(r) {
+ userData.platform.role[r.role] = true
+ });
+ //Build project roles
+ var projects = result[0].data.project;
+ var userProjects = [];
+ projects && projects.map(function(p, i) {
+ userData.project[p.name] = {
+ data: p,
+ role: {}
+ }
+ userData.projectId.push(p.name);
+ if (userData.platform.role['rw-rbac-platform:super-admin']) {
+ userData.project[p.name] = {
+ data: p,
+ role: {
+ "rw-project:project-admin": true,
+ "rw-project:project-oper": true,
+ "rw-project-mano:account-admin": true,
+ "rw-project-mano:account-oper": true,
+ "rw-project-mano:catalog-admin": true,
+ "rw-project-mano:catalog-oper": true,
+ "rw-project-mano:lcm-admin": true,
+ "rw-project-mano:lcm-oper": true
+ }
+ }
+ } else {
+ var users = p['project-config'] && p['project-config'].user;
+ users && users.map(function(u) {
+ if(u['user-name'] == id) {
+ u.role && u.role.map(function(r) {
+ userData.project[p.name].role[r.role] = true;
+ if (r.role === 'rw-project:project-admin') {
+ userData.project[p.name].role["rw-project-mano:account-admin"] = true;
+ userData.project[p.name].role["rw-project-mano:catalog-admin"] = true;
+ userData.project[p.name].role["rw-project-mano:lcm-admin"] = true;
+ userData.isLCM = true;
+ } else if (r.role === 'rw-project:project-oper') {
+ userData.project[p.name].role["rw-project-mano:account-oper"] = true;
+ userData.project[p.name].role["rw-project-mano:catalog-oper"] = true;
+ userData.project[p.name].role["rw-project-mano:lcm-oper"] = true;
+ userData.isLCM = true;
+ }
+ });
+ u["rw-project-mano:mano-role"] && u["rw-project-mano:mano-role"] .map(function(r) {
+ userData.project[p.name].role[r.role] = true;
+ if (r.role.indexOf('rw-project-mano:lcm') > -1) {
+ userData.isLCM = true;
+ }
+ });
+ }
+ })
+ }
+ });
+ response.data = userData;
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK;
+
+ req.session.projectMap = userData.project;
+ req.session.platformMap = userData.platform;
+ resolve(response);
+ })
+ } else {
+ var errorMsg = 'userId not specified in UserManagement.getUserInfo';
+ console.error(errorMsg);
+ response.statusCode = constants.HTTP_RESPONSE_CODES.ERROR.BAD_REQUEST;
+ response.error = errorMsg;
+ reject(response)
+ }
+
+ })
+}
+UserManagement.create = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var data = req.body;
+ data = {
+ "user":[data]
+ }
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/user-config',
+ method: 'POST',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.create', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to create user' + error
+ };
+ reject(response);
+ });
+ });
+};
+UserManagement.update = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var bodyData = req.body;
+ data = {
+ "rw-user:user": bodyData
+ }
+ var updateTasks = [];
+ if(bodyData.hasOwnProperty('old-password')) {
+ var changePW = rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/operations/change-password',
+ method: 'POST',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: {
+ "input": {
+ 'user-name' : bodyData['user-name'],
+ 'user-domain' : bodyData['user-domain'],
+ 'old-password' : bodyData['old-password'],
+ 'new-password' : bodyData['new-password'],
+ 'confirm-password' : bodyData['confirm-password'],
+ }
+ },
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ updateTasks.push(changePW);
+ };
+ var updateUser = rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/user-config/user/' + encodeURIComponent(bodyData['user-name']) + ',' + encodeURIComponent(bodyData['user-domain']),
+ method: 'PUT',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ });
+ updateTasks.push(updateUser)
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ updateTasks
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.passwordChange', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to passwordChange user' + error
+ };
+ reject(response);
+ });
+ });
+};
+
+UserManagement.delete = function(req) {
+ var self = this;
+ var username = req.params.username;
+ var domain = req.params.domain;
+ var api_server = req.query["api_server"];
+ var requestHeaders = {};
+ var url = `${utils.confdPort(api_server)}/${API_VERSION}/api/config/user-config/user/${encodeURIComponent(username)},${encodeURIComponent(domain)}`
+ return new Promise(function(resolve, reject) {
+ _.extend(requestHeaders,
+ constants.HTTP_HEADERS.accept.data,
+ constants.HTTP_HEADERS.content_type.data, {
+ 'Authorization': req.session && req.session.authorization
+ });
+ rp({
+ url: url,
+ method: 'DELETE',
+ headers: requestHeaders,
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ }, function(error, response, body) {
+ if (utils.validateResponse('UserManagement.DELETE', error, response, body, resolve, reject)) {
+ return resolve({
+ statusCode: response.statusCode,
+ data: JSON.stringify(response.body)
+ });
+ };
+ });
+ })
+};
+UserManagement.getUserUiState = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var user = req.session.passport.user;
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/user-config/user/'+encodeURIComponent(user.username) + ',' + encodeURIComponent(user.domain),
+ method: 'GET',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = JSON.parse(result[0].body);
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.getUserUiState', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to create user' + error
+ };
+ reject(response);
+ });
+ });
+};
+UserManagement.updateActiveProject = function(req) {
+ var self = this;
+ var api_server = req.query['api_server'];
+ var user = req.session.passport.user;
+ var data = {
+ "rw-user:user-config": {
+ "user":{
+ "user-name" : user.username,
+ "user-domain": user.domain,
+ "ui-state": {
+ "last-active-project" : req.params.projectId
+ }
+ }
+ }
+ }
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/user-config',
+ method: 'PATCH',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.updateActiveProject', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to create user' + error
+ };
+ reject(response);
+ });
+ });
+};
+UserManagement.updateActiveUri = function(req) {
+ if (!req.session.passport) {
+ console.debug("passport gone before we got the save the active uri");
+ var response = {
+ statusCode: 500,
+ errorMessage: {
+ error: 'Failed to save active uri'
+ }};
+ return Promise.resolve(response);
+ }
+ var self = this;
+ var api_server = req.query['api_server'];
+ var user = req.session.passport.user;
+ var ref = req.headers.referer;
+ var hash = req.query.hash;
+ var data = {
+ "rw-user:user-config": {
+ "user":{
+ "user-name" : user.username,
+ "user-domain": user.domain,
+ "ui-state": {
+ "last-active-uri" : ref + decodeURIComponent(hash)
+ }
+ }
+ }
+ }
+ return new Promise(function(resolve, reject) {
+ Promise.all([
+ rp({
+ uri: utils.confdPort(api_server) + '/' + API_VERSION + '/api/config/user-config',
+ method: 'PATCH',
+ headers: _.extend({}, constants.HTTP_HEADERS.accept.data, {
+ 'Authorization': req.session && req.session.authorization
+ }),
+ forever: constants.FOREVER_ON,
+ json: data,
+ rejectUnauthorized: false,
+ resolveWithFullResponse: true
+ })
+ ]).then(function(result) {
+ var response = {};
+ response['data'] = {};
+ if (result[0].body) {
+ response['data'] = result[0].body;
+ }
+ response.statusCode = constants.HTTP_RESPONSE_CODES.SUCCESS.OK
+
+ resolve(response);
+ }).catch(function(error) {
+ var response = {};
+ console.log('Problem with UserManagement.updateActiveProject', error);
+ response.statusCode = error.statusCode || 500;
+ response.errorMessage = {
+ error: 'Failed to create user' + error
+ };
+ reject(response);
+ });
+ });
+};
+module.exports = UserManagement;
diff --git a/skyquake/framework/core/modules/navigation_manager.js b/skyquake/framework/core/modules/navigation_manager.js
index c85eba6..7d22394 100644
--- a/skyquake/framework/core/modules/navigation_manager.js
+++ b/skyquake/framework/core/modules/navigation_manager.js
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -42,7 +42,6 @@
if (!NAVIGATION[plugin_name]) {
NAVIGATION[plugin_name] = {};
}
-
if (!NAVIGATION[plugin_name].routes) {
NAVIGATION[plugin_name].routes = routes;
} else {
@@ -69,6 +68,20 @@
NAVIGATION[plugin_name].label = label || 'RW.UI Plugin';
}
+function addAllow(plugin_name, allow) {
+ if (!NAVIGATION[plugin_name]) {
+ NAVIGATION[plugin_name] = {};
+ }
+ NAVIGATION[plugin_name].allow = allow || '*';
+}
+
+function addAdminFlag(plugin_name, admin_link) {
+ if (!NAVIGATION[plugin_name]) {
+ NAVIGATION[plugin_name] = {};
+ }
+ NAVIGATION[plugin_name].admin_link = admin_link || false;
+}
+
function getNavigation() {
return NAVIGATION;
}
@@ -82,6 +95,8 @@
addOrder(plugin_name, plugin.order);
addPriority(plugin_name, plugin.priority);
addLabel(plugin_name, plugin.name);
+ addAllow(plugin_name, plugin.allow);
+ addAdminFlag(plugin_name, plugin.admin_link);
}
function init() {
diff --git a/skyquake/framework/core/modules/routes/auth.js b/skyquake/framework/core/modules/routes/auth.js
new file mode 100644
index 0000000..c1df55a
--- /dev/null
+++ b/skyquake/framework/core/modules/routes/auth.js
@@ -0,0 +1,99 @@
+
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * auth routes module. Provides a RESTful API for this
+ * skyquake instance's auth state.
+ * @module framework/core/modules/routes/auth
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ */
+
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var Router = require('express').Router();
+var utils = require('../../api_utils/utils');
+var configurationAPI = require('../api/configuration');
+
+var auth = {};
+
+auth.routes = function(authManager) {
+ console.log('Configuring auth routes');
+ Router.use(bodyParser.json());
+ Router.use(cors());
+ Router.use(bodyParser.urlencoded({
+ extended: true
+ }));
+
+ // Define routes.
+ Router.get('/', function(req, res) {
+ var default_page = null;
+ var api_server = req.query['api_server'] || (req.protocol + '://' + configurationAPI.globalConfiguration.get().api_server);
+ if (req.session && req.session.topApplication) {
+ default_page = utils.buildRedirectURL(req, configurationAPI.globalConfiguration, req.session.topApplication);
+ } else {
+ default_page = utils.buildRedirectURL(req, configurationAPI.globalConfiguration, 'user_management', '#/user-profile');
+ }
+ if (!req.user) {
+ res.redirect('/login');
+ } else {
+ res.redirect(default_page);
+ }
+ });
+
+ Router.get('/login', cors(), function(req, res) {
+ // res.render('login.html');
+ res.redirect('/login/idp');
+ });
+
+ Router.get('/login/idp',
+ authManager.passport.authenticate('oauth2')
+ );
+
+ Router.get('/callback', function(req, res, next) {
+ authManager.passport.authenticate('oauth2', function(err, user, info) {
+ if (err) {
+ // Catch some errors specific to deployments (e.g. IDP unavailable)
+ if (err.oauthError && err.oauthError.code == 'ENOTFOUND') {
+ return res.render('idpconnectfail.ejs', {
+ callback_url: req.url
+ });
+ }
+ return res.redirect('/login');
+ }
+ if (!user) {
+ return res.redirect('/login');
+ }
+ req.logIn(user, function(err) {
+ if (err) {
+ return next(err);
+ }
+ return res.redirect('/session?redirectParams=' + req.url);
+ });
+ })(req, res, next);
+ });
+
+
+ Router.get('/login.html', cors(), function(req, res) {
+ res.render('login.html');
+ });
+}
+
+auth.router = Router;
+
+module.exports = auth;
diff --git a/skyquake/framework/core/modules/routes/configuration.js b/skyquake/framework/core/modules/routes/configuration.js
index b789ff0..93bb88a 100644
--- a/skyquake/framework/core/modules/routes/configuration.js
+++ b/skyquake/framework/core/modules/routes/configuration.js
@@ -56,38 +56,5 @@
});
});
-Router.get('/check-auth', function(req, res) {
- console.log('testing auth')
- var api_server = req.query["api_server"];
- var uri = utils.confdPort(api_server) + '/api/config/';
-
- checkAuth(uri, req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
-});
-
-function checkAuth(uri, req){
- return new Promise(function(resolve, reject) {
- request({
- uri: uri,
- method: 'GET',
- headers: _.extend({}, {
- 'Authorization': req.get('Authorization'),
- forever: CONSTANTS.FOREVER_ON,
- rejectUnauthorized: false,
- })
- }, function(error, response, body) {
- console.log(arguments)
- if( response.statusCode == 401) {
- reject({statusCode: 401, error: response.body});
- } else {
- resolve({statusCode:200, data:response.body})
- }
- });
- });
-}
-
module.exports = Router;
diff --git a/skyquake/framework/core/modules/routes/navigation.js b/skyquake/framework/core/modules/routes/navigation.js
index 82c7ec5..37e86e4 100644
--- a/skyquake/framework/core/modules/routes/navigation.js
+++ b/skyquake/framework/core/modules/routes/navigation.js
@@ -1,6 +1,6 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,6 +30,7 @@
var Router = require('express').Router();
var utils = require('../../api_utils/utils');
var configurationAPI = require('../api/configuration');
+var csrfCheck = require('../../api_utils/csrf').csrfCheck;
Router.use(bodyParser.json());
Router.use(cors());
@@ -37,48 +38,64 @@
extended: true
}));
-Router.get('/', cors(), function(req, res, next) {
- res.redirect('/launchpad/?api_server=' + req.protocol + '://' + configurationAPI.globalConfiguration.get().api_server + '&upload_server=' + req.protocol + '://' + (configurationAPI.globalConfiguration.get().upload_server || req.hostname));
+//Should have a way of adding excluded routes to this via plugin registry, instead of hard coding
+Router.use(/^(?!.*(login\/idp|session|composer\/upload|composer\/update)).*/, function(req, res, next) {
+ var api_server = req.query['api_server'] || (req.protocol + '://' + configurationAPI.globalConfiguration.get().api_server);
+ if (req.session && req.session.loggedIn) {
+ switch (req.method) {
+ case 'POST':
+ case 'PUT':
+ csrfCheck(req, res, next);
+ break;
+ default:
+ next();
+ break;
+ }
+ } else {
+ console.log('Redirect to login.html');
+ res.redirect(utils.buildRedirectURL(req, configurationAPI.globalConfiguration, 'login', '&referer=' + encodeURIComponent(req.headers.referer)));
+ }
});
+
Router.get('/nav', cors(), function(req, res) {
- navAPI.get(req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
+ navAPI.get(req).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
});
Router.get('/nav/:plugin_id', cors(), function(req, res) {
- navAPI.get(req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
+ navAPI.get(req).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
});
Router.post('/nav/:plugin_id', cors(), function(req, res) {
- navAPI.create(req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
+ navAPI.create(req).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
});
Router.put('/nav/:plugin_id/:route_id', cors(), function(req, res) {
- navAPI.update(req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
+ navAPI.update(req).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
});
Router.delete('/nav/:plugin_id/:route_id', cors(), function(req, res) {
- navAPI.delete(req).then(function(data) {
- utils.sendSuccessResponse(data, res);
- }, function(error) {
- utils.sendErrorResponse(error, res);
- });
+ navAPI.delete(req).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
});
diff --git a/skyquake/framework/core/modules/routes/projectManagement.js b/skyquake/framework/core/modules/routes/projectManagement.js
new file mode 100644
index 0000000..c106f30
--- /dev/null
+++ b/skyquake/framework/core/modules/routes/projectManagement.js
@@ -0,0 +1,85 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * inactivity routes module. Provides a RESTful API for this
+ * skyquake instance's inactivity state.
+ * @module framework/core/modules/routes/inactivity
+ * @author Laurence Maultsby <laurence.maultsby@riftio.com>
+ */
+
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var Router = require('express').Router();
+var utils = require('../../api_utils/utils');
+var ProjectManagementAPI = require('../api/projectManagementAPI.js');
+
+Router.use(bodyParser.json());
+Router.use(cors());
+Router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+Router.get('/project', cors(), function(req, res) {
+ ProjectManagementAPI.get(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.post('/project', cors(), function(req, res) {
+ ProjectManagementAPI.create(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.put('/project', cors(), function(req, res) {
+ ProjectManagementAPI.update(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.delete('/project/:projectname', cors(), function(req, res) {
+ ProjectManagementAPI.delete(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+Router.put('/platform', cors(), function(req, res) {
+ ProjectManagementAPI.updatePlatform(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+Router.get('/platform', cors(), function(req, res) {
+ ProjectManagementAPI.getPlatform(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+module.exports = Router;
+
+
+
diff --git a/skyquake/framework/core/modules/routes/sessions.js b/skyquake/framework/core/modules/routes/sessions.js
new file mode 100644
index 0000000..f84ca11
--- /dev/null
+++ b/skyquake/framework/core/modules/routes/sessions.js
@@ -0,0 +1,74 @@
+
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * Node sessions routes module.
+ * Provides a RESTful API to manage sessions.
+ * @module framework/core/modules/routes/sessions
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ */
+
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var sessionsAPI = require('../api/sessions');
+var Router = require('express').Router();
+var utils = require('../../api_utils/utils');
+var CONSTANTS = require('../../api_utils/constants.js');
+var request = require('request');
+var _ = require('lodash');
+
+var sessions = {};
+
+sessions.routes = function(sessionsConfig) {
+ Router.use(bodyParser.json());
+ Router.use(cors());
+ Router.use(bodyParser.urlencoded({
+ extended: true
+ }));
+
+ // Overloaded get method to handle OpenIDConnect redirect to establish a session.
+ Router.get('/session*', cors(), /*sessionsConfig.authManager.passport.authenticate('main', {
+ noredirect: false
+ }), */function(req, res) {
+ req.query['api_server'] = sessionsConfig.api_server_protocol + '://' + sessionsConfig.api_server;
+ sessionsAPI.create(req, res).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ });
+ });
+
+ // For project switcher UI
+ Router.put('/session/:projectId', cors(), function(req, res) {
+ sessionsAPI.addProjectToSession(req, res).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+ });
+
+ Router.delete('/session', cors(), function(req, res) {
+ sessionsAPI.delete(req, res).then(function(data) {
+ utils.sendSuccessResponse(data, res);
+ });
+ });
+}
+
+sessions.router = Router;
+
+
+module.exports = sessions;
diff --git a/skyquake/framework/core/modules/routes/userManagement.js b/skyquake/framework/core/modules/routes/userManagement.js
new file mode 100644
index 0000000..22a2d74
--- /dev/null
+++ b/skyquake/framework/core/modules/routes/userManagement.js
@@ -0,0 +1,85 @@
+
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+/**
+ * inactivity routes module. Provides a RESTful API for this
+ * skyquake instance's inactivity state.
+ * @module framework/core/modules/routes/inactivity
+ * @author Laurence Maultsby <laurence.maultsby@riftio.com>
+ */
+
+var cors = require('cors');
+var bodyParser = require('body-parser');
+var Router = require('express').Router();
+var utils = require('../../api_utils/utils');
+var UserManagementAPI = require('../api/userManagementAPI.js');
+
+Router.use(bodyParser.json());
+Router.use(cors());
+Router.use(bodyParser.urlencoded({
+ extended: true
+}));
+
+Router.get('/user', cors(), function(req, res) {
+ UserManagementAPI.get(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.get('/user-profile', cors(), function(req, res) {
+ UserManagementAPI.getProfile(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.get('/user-data/:userId/:domain?', cors(), function(req, res) {
+ UserManagementAPI.getUserInfo(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.post('/user', cors(), function(req, res) {
+ UserManagementAPI.create(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.put('/user', cors(), function(req, res) {
+ UserManagementAPI.update(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+Router.delete('/user/:username/:domain', cors(), function(req, res) {
+ UserManagementAPI.delete(req).then(function(response) {
+ utils.sendSuccessResponse(response, res);
+ }, function(error) {
+ utils.sendErrorResponse(error, res);
+ });
+});
+
+module.exports = Router;
+
+
+
diff --git a/skyquake/framework/core/views/home.ejs b/skyquake/framework/core/views/home.ejs
new file mode 100644
index 0000000..2cb2f80
--- /dev/null
+++ b/skyquake/framework/core/views/home.ejs
@@ -0,0 +1,5 @@
+<% if (!user) { %>
+ <p>Welcome! Please <a href="/login">log in</a>.</p>
+<% } else { %>
+ <p>Hello, <%= user.username %>. View your <a href="<%= default_page %>">default page</a>. TODO: Update link to dashboard</p>
+<% } %>
\ No newline at end of file
diff --git a/skyquake/framework/core/views/idpconnectfail.ejs b/skyquake/framework/core/views/idpconnectfail.ejs
new file mode 100644
index 0000000..7847b3d
--- /dev/null
+++ b/skyquake/framework/core/views/idpconnectfail.ejs
@@ -0,0 +1,43 @@
+<style type="text/css">
+
+html {
+ background: #f1f1f1;
+}
+
+body {
+ background: #f1f1f1;
+}
+#idpfail {
+ display: flex;
+ flex-direction: column;
+ text-align: center;
+ align-items: center;
+}
+#idpfail .message {
+ display: flex;
+ margin-bottom: 20px;
+ font-size: 1.625rem;
+ font-weight: 400;
+ text-decoration: none;
+ text-transform: uppercase;
+ font-family: roboto-thin, Helvetica, Arial, sans-serif;
+ color: #CD5C5C;
+}
+#retrylink {
+ margin-top:40px;
+ font-family: roboto-thin, Helvetica, Arial, sans-serif;
+}
+
+
+</style>
+<div id="idpfail">
+ <p class="message">
+ We are having trouble connecting to the Identity Provider.
+ </p>
+ <p class="message">
+ Please check that it is running and reachable.
+ </p>
+ <p id="retrylink">
+ Once you have resolved the connectivity issues, <a href="<%= callback_url %>">please click here to retry.</a>
+ </p>
+</div>
\ No newline at end of file
diff --git a/skyquake/framework/plugin-index.html b/skyquake/framework/plugin-index.html
new file mode 100644
index 0000000..b704a3c
--- /dev/null
+++ b/skyquake/framework/plugin-index.html
@@ -0,0 +1,13 @@
+<style>
+ html {
+ display: none;
+ }
+</style>
+<script>
+ if (self == top) {
+ document.documentElement.style.display = 'block';
+ } else {
+ top.location = self.location;
+ }
+</script>
+<div id="app"></div>
\ No newline at end of file
diff --git a/skyquake/framework/source/SourceCache.js b/skyquake/framework/source/SourceCache.js
new file mode 100644
index 0000000..ded3c9d
--- /dev/null
+++ b/skyquake/framework/source/SourceCache.js
@@ -0,0 +1,96 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import appConfiguration from '../utils/appConfiguration'
+
+let versionKeyPrefix = null;
+
+const localCache = new class {
+ get(key) {
+ let valueAsString = localStorage.getItem(key);
+ return valueAsString ? JSON.parse(valueAsString) : undefined;
+ }
+ set(key, val) {
+ localStorage.setItem(key, typeof val === 'string' ? val : JSON.stringify(val));
+ }
+}();
+
+let objCache = new Map();
+
+const storeCache = new class {
+ get(key) {
+ if (objCache[key]) {
+ objCache[key].timerId && clearTimeout(objCache[key].timerId)
+ objCache[key].timerId = setTimeout((key) => delete objCache[key], 2000)
+ return objCache[key].value;
+ }
+ const obj = localCache.get(key);
+ if (obj) {
+ objCache[key] = {
+ value: obj,
+ timerId: setTimeout((key) => delete objCache[key], 2000)
+ }
+ return obj;
+ }
+ }
+ set(key, obj) {
+ setTimeout(localCache.set, 100, key, obj);
+ objCache[key] = {
+ value: obj,
+ timerId: setTimeout((key) => delete objCache[key], 2000)
+ }
+ }
+ init(version) {
+ versionKeyPrefix = 's-v-' + version;
+ const currentStoreVersion = localStorage.getItem('store-version');
+ if (currentStoreVersion !== version) {
+ let removeItems = [];
+ for (let i = 0; i < localStorage.length; ++i) {
+ let key = localStorage.key(i);
+ if (key.startsWith('s-v-')) {
+ removeItems.push(key);
+ }
+ }
+ removeItems.forEach((key) => localStorage.removeItem(key));
+ localStorage.setItem('store-version', version);
+ }
+ }
+}();
+
+class StoreCache {
+ constructor(name) {
+ this.name = 's-v-' + name;
+ }
+ get(key) {
+ return storeCache.get(this.name + key);
+ }
+ set(key, obj) {
+ storeCache.set(this.name + key, obj);
+ }
+ init() {
+ return versionKeyPrefix ? Promise.resolve() : new Promise(
+ (resolve, reject) => {
+ appConfiguration.get().then((config) => {
+ storeCache.init(config.version);
+ resolve();
+ })
+ }
+ )
+ }
+}
+
+module.exports = StoreCache;
\ No newline at end of file
diff --git a/skyquake/framework/source/model/index.js b/skyquake/framework/source/model/index.js
new file mode 100644
index 0000000..019ada0
--- /dev/null
+++ b/skyquake/framework/source/model/index.js
@@ -0,0 +1,7 @@
+import modelActions from './modelActions'
+import modelSource from './modelSource'
+
+export {
+ modelSource,
+ modelActions
+}
\ No newline at end of file
diff --git a/skyquake/framework/source/model/modelActions.js b/skyquake/framework/source/model/modelActions.js
new file mode 100644
index 0000000..41dbc00
--- /dev/null
+++ b/skyquake/framework/source/model/modelActions.js
@@ -0,0 +1,31 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import Alt from 'widgets/skyquake_container/skyquakeAltInstance';
+
+class Actions {
+
+ constructor() {
+ this.generateActions(
+ 'loadModel',
+ 'processRequestSuccess',
+ 'processRequestInitiated',
+ 'processRequestFailure');
+ }
+}
+
+export default Alt.createActions(Actions);
diff --git a/skyquake/framework/source/model/modelSource.js b/skyquake/framework/source/model/modelSource.js
new file mode 100644
index 0000000..3779aa5
--- /dev/null
+++ b/skyquake/framework/source/model/modelSource.js
@@ -0,0 +1,128 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import rw from 'utils/rw'
+import modelActions from './modelActions'
+import Utils from 'utils/utils'
+import $ from 'jquery';
+
+const source = {
+ loadModel: function () {
+ return {
+ remote: function (state, path) {
+ return new Promise(function (resolve, reject) {
+ $.ajax({
+ url: '/model?path=' + path,
+ type: 'GET',
+ success: function (result) {
+ resolve(result);
+ },
+ error: function (xhr, errorType, errorMessage) {
+ console.log("There was an error updating the model: ", errorType, errorMessage, xhr);
+ reject({response: xhr.responseJSON, errorType, errorMessage});
+ }
+ });
+ })
+ },
+ success: modelActions.processRequestSuccess,
+ loading: modelActions.processRequestInitiated,
+ error: modelActions.processRequestFailure
+ }
+ },
+ updateModel: function () {
+ return {
+ remote: function (state, path, data) {
+ const url = path.reduce((url, node) => {
+ url += node[0] !== '[' ? '/' : '';
+ return url + node
+ }, `/model?path=/${state.path}`);
+ return new Promise(function (resolve, reject) {
+ $.ajax({
+ url: url,
+ type: 'PATCH',
+ data: data,
+ success: function (result) {
+ resolve(result);
+ },
+ error: function (xhr, errorType, errorMessage) {
+ console.log("There was an error updating the model: ", errorType, errorMessage, xhr);
+ reject({response: xhr.responseJSON, errorType, errorMessage});
+ }
+ });
+ })
+ },
+ success: modelActions.processRequestSuccess,
+ loading: modelActions.processRequestInitiated,
+ error: modelActions.processRequestFailure
+ }
+ },
+ createModel: function () {
+ return {
+ remote: function (state, path, data) {
+ const url = path.reduce((url, node) => {
+ url += node[0] !== '[' ? '/' : '';
+ return url + node
+ }, `/model?path=/${state.path}`);
+ return new Promise(function (resolve, reject) {
+ $.ajax({
+ url: url,
+ type: 'PUT',
+ data: data,
+ success: function (result) {
+ resolve(result);
+ },
+ error: function (xhr, errorType, errorMessage) {
+ console.log("There was an error updating the model: ", errorType, errorMessage, xhr);
+ reject({response: xhr.responseJSON, errorType, errorMessage});
+ }
+ });
+ })
+ },
+ success: modelActions.processRequestSuccess,
+ loading: modelActions.processRequestInitiated,
+ error: modelActions.processRequestFailure
+ }
+ },
+
+ deleteModel: function () {
+ return {
+ remote: function (state, path) {
+ const url = path.reduce((url, node) => {
+ url += node[0] !== '[' ? '/' : '';
+ return url + node
+ }, `/model?path=/${state.path}`);
+ return new Promise(function (resolve, reject) {
+ $.ajax({
+ url: url,
+ type: 'DELETE',
+ success: function (result) {
+ resolve(result);
+ },
+ error: function (xhr, errorType, errorMessage) {
+ console.log("There was an error updating the model: ", errorType, errorMessage, xhr);
+ reject({response: xhr.responseJSON, errorType, errorMessage});
+ }
+ });
+ })
+ },
+ success: modelActions.processRequestSuccess,
+ loading: modelActions.processRequestInitiated,
+ error: modelActions.processRequestFailure
+ }
+ }
+}
+module.exports = source;
\ No newline at end of file
diff --git a/skyquake/framework/source/schema/index.js b/skyquake/framework/source/schema/index.js
new file mode 100644
index 0000000..95b152e
--- /dev/null
+++ b/skyquake/framework/source/schema/index.js
@@ -0,0 +1,7 @@
+import schemaActions from './schemaActions'
+import schemaSource from './schemaSource'
+
+export {
+ schemaSource,
+ schemaActions
+}
\ No newline at end of file
diff --git a/skyquake/framework/source/schema/schemaActions.js b/skyquake/framework/source/schema/schemaActions.js
new file mode 100644
index 0000000..7e36cca
--- /dev/null
+++ b/skyquake/framework/source/schema/schemaActions.js
@@ -0,0 +1,31 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import Alt from 'widgets/skyquake_container/skyquakeAltInstance';
+
+class Actions {
+
+ constructor() {
+ this.generateActions(
+ 'loadSchema',
+ 'loadSchemaSuccess',
+ 'loadSchemaLoading',
+ 'loadSchemaFail');
+ }
+}
+
+export default Alt.createActions(Actions);
diff --git a/skyquake/framework/source/schema/schemaSource.js b/skyquake/framework/source/schema/schemaSource.js
new file mode 100644
index 0000000..2c7bd5b
--- /dev/null
+++ b/skyquake/framework/source/schema/schemaSource.js
@@ -0,0 +1,95 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import rw from 'utils/rw'
+import schemaActions from './schemaActions'
+import Utils from 'utils/utils'
+import $ from 'jquery';
+import StoreCache from '../SourceCache'
+
+const storeCache = new StoreCache('schema');
+storeCache.init(); // get the ball rolling
+
+function getCachedSchema(request) {
+ const cachedSchema = {};
+ const requestSchema = [];
+ request.forEach((path) => {
+ let schema = storeCache.get(path);
+ if (schema) {
+ cachedSchema[path] = schema
+ } else {
+ requestSchema.push(path);
+ }
+ });
+ return {
+ cachedSchema,
+ requestSchema
+ };
+}
+
+const schemaSource = {
+ loadSchema: function () {
+ return {
+ local: function (state, request) {
+ request = Array.isArray(request) ? request : [request];
+ const results = getCachedSchema(request);
+ if (!results.requestSchema.length) {
+ return(Promise.resolve(results.cachedSchema));
+ }
+ },
+
+ remote: function (state, request) {
+ return new Promise(function (resolve, reject) {
+ storeCache.init().then(() => {
+ request = Array.isArray(request) ? request : [request];
+ const results = getCachedSchema(request);
+ if (!results.requestSchema.length) {
+ resolve({
+ schema: results.cachedSchema
+ });
+ } else {
+ $.ajax({
+ url: '/schema?request=' + results.requestSchema.join(','),
+ type: 'GET',
+ success: function ({
+ schema
+ }) {
+ for (let path in schema) {
+ storeCache.set(path, schema[path]);
+ }
+ resolve(getCachedSchema(request).cachedSchema);
+ },
+ error: function (error) {
+ console.log("There was an error getting the schema: ", error);
+ reject(error);
+ }
+ }).fail(function (xhr) {
+ console.log("There was an error getting the schema: ", xhr);
+ Utils.checkAuthentication(xhr.status);
+ reject("There was an error getting the schema.")
+ });
+ }
+ })
+ })
+ },
+ success: schemaActions.loadSchemaSuccess,
+ loading: schemaActions.loadSchemaLoading,
+ error: schemaActions.loadSchemaFail
+ }
+ },
+}
+export default schemaSource;
\ No newline at end of file
diff --git a/skyquake/framework/style/_colors.scss b/skyquake/framework/style/_colors.scss
index 9378984..a01c293 100644
--- a/skyquake/framework/style/_colors.scss
+++ b/skyquake/framework/style/_colors.scss
@@ -1,6 +1,6 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -31,7 +31,7 @@
$error-red:#FF5F5F;
-//PC
+/*PC*/
$black: #000;
$gray-lightest: #f1f1f1;
@@ -42,9 +42,9 @@
$gray-darker: #666;
$gray-darkest: #333;
$white: #FFF;
-//
-// Brand Colors
-//
+/**/
+/* Brand Colors*/
+/**/
$brand-blue-light: #30baef;
$brand-blue: #00acee;
$brand-blue-dark: #147ca3;
@@ -66,11 +66,12 @@
$neutral-light-4: hsl(360, 100%, 50%);
$neutral-light-5: hsl(360, 100%, 50%);
-$neutral-dark-1: hsl(360, 100%, 50%);
-$neutral-dark-2: hsl(360, 100%, 50%);
-$neutral-dark-3: hsl(360, 100%, 50%);
-$neutral-dark-4: hsl(360, 100%, 50%);
-$neutral-dark-5: hsl(360, 100%, 50%);
+$neutral-dark-0: hsl(0, 0%, 80.7%);
+$neutral-dark-1: hsl(0, 0%, 63.7%);
+$neutral-dark-2: hsl(0, 0%, 56.7%);
+$neutral-dark-3: hsl(0, 0%, 49.7%);
+$neutral-dark-4: hsl(0, 0%, 42.7%);
+$neutral-dark-5: hsl(0, 0%, 35.7%);
$netral-black: hsl(0, 100%, 0%);
diff --git a/skyquake/framework/style/core.css b/skyquake/framework/style/core.css
index 01b728b..e9d5de9 100644
--- a/skyquake/framework/style/core.css
+++ b/skyquake/framework/style/core.css
@@ -16,8 +16,6 @@
*
*/
/*@import "./vendor/css-reset-2.0/css-reset.css";*/
-@import "../../node_modules/reset-css/reset.css";
-
.has-drop-shadow {
box-shadow: 2px 2px rgba(0, 0, 0, .15)
}
@@ -2023,7 +2021,7 @@
margin-top: 150px;
margin-bottom: 20px;
background-size: 154px 102px;
- /*background-image: url(./img/header-logo.png)*/
+ /*background-image: url(./img/header-logo.png)*/
background-image: url(./img/svg/osm-logo_color_rgb.svg);
}
.login-cntnr .riftio {
diff --git a/skyquake/framework/style/img/osm_header.png b/skyquake/framework/style/img/osm_header.png
index 53a9500..c67dca3 100644
--- a/skyquake/framework/style/img/osm_header.png
+++ b/skyquake/framework/style/img/osm_header.png
Binary files differ
diff --git a/skyquake/framework/style/img/osm_header_253x50.png b/skyquake/framework/style/img/osm_header_253x50.png
index 1005431..3055122 100644
--- a/skyquake/framework/style/img/osm_header_253x50.png
+++ b/skyquake/framework/style/img/osm_header_253x50.png
Binary files differ
diff --git a/skyquake/framework/style/img/osm_header_506x100.png b/skyquake/framework/style/img/osm_header_506x100.png
index 7ece845..4b7a344 100644
--- a/skyquake/framework/style/img/osm_header_506x100.png
+++ b/skyquake/framework/style/img/osm_header_506x100.png
Binary files differ
diff --git a/skyquake/framework/utils/appConfiguration.js b/skyquake/framework/utils/appConfiguration.js
new file mode 100644
index 0000000..2882309
--- /dev/null
+++ b/skyquake/framework/utils/appConfiguration.js
@@ -0,0 +1,42 @@
+/*
+ *
+ * Copyright 2017 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import $ from 'jquery';
+
+const configPromise = new Promise((resolve, reject) => {
+ $.ajax({
+ url: '/app-config',
+ type: 'GET',
+ success: function (data) {
+ if (data.version.endsWith('.1')){
+ data.version = '' + Date.now();
+ }
+ resolve(data);
+ },
+ error: function (error) {
+ console.log("There was an error getting config: ", error);
+ reject(error);
+ }
+ }).fail(function (xhr) {
+ console.log('There was an xhr error getting the config', xhr);
+ reject(xhr);
+ });
+});
+
+module.exports = {
+ get: () => configPromise
+};
\ No newline at end of file
diff --git a/skyquake/framework/utils/roleConstants.js b/skyquake/framework/utils/roleConstants.js
new file mode 100644
index 0000000..5ac4e64
--- /dev/null
+++ b/skyquake/framework/utils/roleConstants.js
@@ -0,0 +1,31 @@
+var c = {};
+
+c.PLATFORM = {
+ OPER: "rw-rbac-platform:platform-oper",
+ ADMIN: "rw-rbac-platform:platform-admin",
+ SUPER: "rw-rbac-platform:super-admin"
+}
+
+c.PROJECT = {
+ TYPE: {
+ "rw-project-mano:catalog-oper": "rw-project-mano",
+ "rw-project-mano:catalog-admin": "rw-project-mano",
+ "rw-project-mano:lcm-oper": "rw-project-mano",
+ "rw-project-mano:lcm-admin": "rw-project-mano",
+ "rw-project-mano:account-oper": "rw-project-mano",
+ "rw-project-mano:account-admin": "rw-project-mano",
+ "rw-project:project-oper": "rw-project",
+ "rw-project:project-admin": "rw-project"
+ },
+ CATALOG_OPER: "rw-project-mano:catalog-oper",
+ CATALOG_ADMIN: "rw-project-mano:catalog-admin",
+ LCM_OPER: "rw-project-mano:lcm-oper",
+ LCM_ADMIN: "rw-project-mano:lcm-admin",
+ ACCOUNT_OPER: "rw-project-mano:account-oper",
+ ACCOUNT_ADMIN: "rw-project-mano:account-admin",
+ PROJECT_OPER: "rw-project:project-oper",
+ PROJECT_ADMIN: "rw-project:project-admin"
+
+}
+
+module.exports = c;
diff --git a/skyquake/framework/utils/utils.js b/skyquake/framework/utils/utils.js
index 7b93fd5..88ef939 100644
--- a/skyquake/framework/utils/utils.js
+++ b/skyquake/framework/utils/utils.js
@@ -15,13 +15,14 @@
* limitations under the License.
*
*/
-//Login needs to be refactored. Too many cross dependencies
-var AuthActions = require('../widgets/login/loginAuthActions.js');
-var $ = require('jquery');
-import rw from './rw.js';
+import AuthActions from '../widgets/login/loginAuthActions';
+import $ from 'jquery';
+import rw from './rw';
+import appConfiguration from './appConfiguration'
+import SockJS from 'sockjs-client';
+
var API_SERVER = rw.getSearchParams(window.location).api_server;
let NODE_PORT = rw.getSearchParams(window.location).api_port || ((window.location.protocol == 'https:') ? 8443 : 8000);
-var SockJS = require('sockjs-client');
var Utils = {};
@@ -29,25 +30,6 @@
var INACTIVITY_TIMEOUT = 600000;
-Utils.getInactivityTimeout = function() {
- return new Promise(function(resolve, reject) {
- $.ajax({
- url: '/inactivity-timeout',
- type: 'GET',
- success: function(data) {
- resolve(data);
- },
- error: function(error) {
- console.log("There was an error getting the inactivity-timeout: ", error);
- reject(error);
- }
- }).fail(function(xhr) {
- console.log('There was an xhr error getting the inactivity-timeout', xhr);
- reject(xhr);
- });
- });
-};
-
Utils.isMultiplexerLoaded = function() {
if (window.multiplexer) {
return true;
@@ -75,14 +57,19 @@
loadChecker();
};
-Utils.checkAndResolveSocketRequest = function(data, resolve, reject) {
+Utils.checkAndResolveSocketRequest = function(data, resolve, reject, successCallback) {
const checker = () => {
if (!Utils.isMultiplexerLoaded()) {
setTimeout(() => {
checker();
}, 500);
} else {
- resolve(data.id);
+ if (!successCallback) {
+ resolve(data.id);
+ } else {
+ //resolve handled in callback
+ successCallback(data.id)
+ }
}
};
@@ -90,9 +77,8 @@
};
Utils.bootstrapApplication = function() {
- var self = this;
- return new Promise(function(resolve, reject) {
- Promise.all([self.getInactivityTimeout()]).then(function(results) {
+ return new Promise((resolve, reject) => {
+ Promise.all([appConfiguration.get()]).then(function(results) {
INACTIVITY_TIMEOUT = results[0]['inactivity-timeout'];
resolve();
}, function(error) {
@@ -129,8 +115,9 @@
}
Utils.addAuthorizationStub = function(xhr) {
- var Auth = window.sessionStorage.getItem("auth");
- xhr.setRequestHeader('Authorization', 'Basic ' + Auth);
+ // NO-OP now that we are dealing with it on the server
+ // var Auth = window.sessionStorage.getItem("auth");
+ // xhr.setRequestHeader('Authorization', 'Basic ' + Auth);
};
Utils.getByteDataWithUnitPrefix = function(number, precision) {
@@ -183,36 +170,30 @@
}
}
Utils.loginHash = "#/login";
-Utils.setAuthentication = function(username, password, cb) {
- var self = this;
- var AuthBase64 = btoa(username + ":" + password);
- window.sessionStorage.setItem("auth", AuthBase64);
- self.detectInactivity();
- $.ajax({
- url: '//' + window.location.hostname + ':' + window.location.port + '/check-auth?api_server=' + API_SERVER,
- type: 'GET',
- beforeSend: Utils.addAuthorizationStub,
- success: function(data) {
- //console.log("LoggingSource.getLoggingConfig success call. data=", data);
- if (cb) {
- cb();
- };
- },
- error: function(data) {
- Utils.clearAuthentication();
- }
- });
-}
-Utils.clearAuthentication = function(callback) {
+
+Utils.clearAuthentication = function() {
var self = this;
window.sessionStorage.removeItem("auth");
AuthActions.notAuthenticated();
window.sessionStorage.setItem("locationRefHash", window.location.hash);
- if (callback) {
- callback();
- } else {
- window.location.hash = Utils.loginHash;
- }
+ var reloadURL = '';
+ $.ajax({
+ url: '//' + window.location.hostname + ':' + window.location.port + '/session?api_server=' + API_SERVER + '&hash=' + encodeURIComponent(window.location.hash),
+ type: 'DELETE',
+ success: function(data) {
+ console.log('User logged out');
+ reloadURL = data['url'] + '?post_logout_redirect_uri=' +
+ window.location.protocol + '//' +
+ window.location.hostname + ':' +
+ window.location.port +
+ '/?api_server=' + API_SERVER;
+
+ window.location.replace(reloadURL);
+ },
+ error: function(data) {
+ console.log('Problem logging user out');
+ }
+ });
}
Utils.isNotAuthenticated = function(windowLocation, callback) {
var self = this;
@@ -322,4 +303,24 @@
return displayMsg
}
+Utils.rpcError = (rpcResult) => {
+ try {
+ let info = JSON.parse(rpcResult);
+ let rpcError = info.body || info.errorMessage.body || info.errorMessage.error;
+ if (rpcError) {
+ if (typeof rpcError === 'string') {
+ const index = rpcError.indexOf('{');
+ if (index >= 0) {
+ return JSON.parse(rpcError.substr(index));
+ }
+ } else {
+ return rpcError;
+ }
+ }
+ } catch (e) {
+ }
+ console.log('invalid rpc error: ', rpcResult);
+ return null;
+}
+
module.exports = Utils;
diff --git a/skyquake/framework/widgets/button/button.scss b/skyquake/framework/widgets/button/button.scss
index c972e14..043a769 100644
--- a/skyquake/framework/widgets/button/button.scss
+++ b/skyquake/framework/widgets/button/button.scss
@@ -1,6 +1,6 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -62,15 +62,18 @@
############################################################################ */
.SqButton {
- align-items: center;
+ -ms-flex-align: center;
+ align-items: center;
border-style: solid;
border-radius: 3px;
border-width: 0px;
cursor: pointer;
+ display: -ms-inline-flexbox;
display: inline-flex;
font-size: 1rem;
height: 50px;
- justify-content: center;
+ -ms-flex-pack: center;
+ justify-content: center;
margin: 0 10px;
outline: none;
padding: 0 15px;
@@ -107,8 +110,9 @@
/* Focus */
&:focus {
- // box-shadow: $focus-shadow;
- border: 1px solid red;
+ /* box-shadow: $focus-shadow;*/
+ border: 1px solid;
+ border-color: darken($normalHoverBackground, 10%);
}
/* SIZES
@@ -256,11 +260,14 @@
fill: $primaryForeground;
}
}
-
-
}
-
+.sqButtonGroup {
+ display: -ms-flexbox;
+ display: flex;
+ -ms-flex-pack: center;
+ justify-content: center;
+}
diff --git a/skyquake/framework/widgets/button/sq-button.jsx b/skyquake/framework/widgets/button/sq-button.jsx
index ae93128..8d0ec77 100644
--- a/skyquake/framework/widgets/button/sq-button.jsx
+++ b/skyquake/framework/widgets/button/sq-button.jsx
@@ -36,17 +36,35 @@
Class += " is-disabled";
}
return (
- <div style={{display: 'flex'}}>
+ <div style={{display: 'flex'}} onClick={this.props.onClick}>
<div className={Class} tabIndex="0">
- {svgHTML}
- <div className="SqButton-content">{label}</div>
+ {svgHTML}
+ <div className="SqButton-content">{label}</div>
</div>
+ </div>
+ )
+ }
+}
+
+export class ButtonGroup extends React.Component {
+ render() {
+ let className = "sqButtonGroup";
+ if (this.props.className) {
+ className = `${className} ${this.props.className}`
+ }
+ return (
+ <div className={className} style={this.props.style}>
+ {this.props.children}
</div>
)
}
}
+
SqButton.defaultProps = {
+ onClick: function(e) {
+ console.log('Clicked')
+ },
icon: false,
primary: false,
disabled: false,
diff --git a/skyquake/framework/widgets/components.js b/skyquake/framework/widgets/components.js
index f38719a..461a783 100644
--- a/skyquake/framework/widgets/components.js
+++ b/skyquake/framework/widgets/components.js
@@ -26,355 +26,7 @@
// Histogram: Histogram,
Multicomponent: require('./multicomponent/multicomponent.js'),
Mixins: require('./mixins/ButtonEventListener.js'),
- // Gauge: require('./gauge/gauge.js'),
+// Gauge: require('./gauge/gauge.js'),
Bullet: require('./bullet/bullet.js')
};
-// require('../../assets/js/n3-line-chart.js');
-// var Gauge = require('../../assets/js/gauge-modified.js');
-// var bulletController = function($scope, $element) {
-// this.$element = $element;
-// this.vertical = false;
-// this.value = 0;
-// this.min = 0;
-// this.max = 100;
-// //this.range = this.max - this.min;
-// //this.percent = (this.value - this.min) / this.range;
-// this.displayValue = this.value;
-// this.isPercent = (this.units == '')? true:false;
-// this.bulletColor = "#6BB814";
-// this.fontsize = 28;
-// this.radius = 4;
-// this.containerMarginX = 0;
-// this.containerMarginY = 0;
-// this.textMarginX = 5;
-// this.textMarginY = 42;
-// this.bulletMargin = 0;
-// this.width = 512;
-// this.height = 64;
-// this.markerX = -100; // puts it off screen unless set
-// var self = this;
-// if (this.isPercent) {
-// this.displayValue + "%";
-// }
-// $scope.$watch(
-// function() {
-// return self.value;
-// },
-// function() {
-// self.valueChanged();
-// }
-// );
-
-// }
-
-// bulletController.prototype = {
-
-// valueChanged: function() {
-// var range = this.max - this.min;
-// var normalizedValue = (this.value - this.min) / range;
-// if (this.isPercent) {
-// this.displayValue = String(Math.round(normalizedValue * 100)) + "%";
-// } else {
-// this.displayValue = this.value;
-// }
-// // All versions of IE as of Jan 2015 does not support inline CSS transforms on SVG
-// if (platform.name == 'IE') {
-// this.bulletWidth = Math.round(100 * normalizedValue) + '%';
-// } else {
-// this.bulletWidth = this.width - (2 * this.containerMarginX);
-// var transform = 'scaleX(' + normalizedValue + ')';
-// var bullet = $(this.$element).find('.bullet2');
-// bullet.css('transform', transform);
-// bullet.css('-webkit-transform', transform);
-// }
-// },
-
-// markerChanged: function() {
-// var range = this.max - this.min;
-// var w = this.width - (2 * this.containerMarginX);
-// this.markerX = this.containerMarginX + ((this.marker - this.min) / range ) * w;
-// this.markerY1 = 7;
-// this.markerY2 = this.width - 7;
-// }
-// }
-
-// angular.module('components', ['n3-line-chart'])
-// .directive('rwBullet', function() {
-// return {
-// restrict : 'E',
-// templateUrl: 'modules/views/rw.bullet.tmpl.html',
-// bindToController: true,
-// controllerAs: 'bullet',
-// controller: bulletController,
-// replace: true,
-// scope: {
-// min : '@?',
-// max : '@?',
-// value : '@',
-// marker: '@?',
-// units: '@?',
-// bulletColor: '@?',
-// label: '@?'
-// }
-// };
-// })
-// .directive('rwSlider', function() {
-// var controller = function($scope, $element, $timeout) {
-// // Q: is there a way to force attributes to be ints?
-// $scope.min = $scope.min || "0";
-// $scope.max = $scope.max || "100";
-// $scope.step = $scope.step || "1";
-// $scope.height = $scope.height || "30";
-// $scope.orientation = $scope.orientation || 'horizontal';
-// $scope.tooltipInvert = $scope.tooltipInvert || false;
-// $scope.percent = $scope.percent || false;
-// $scope.kvalue = $scope.kvalue || false;
-// $scope.direction = $scope.direction || "ltr";
-// $($element).noUiSlider({
-// start: parseInt($scope.value),
-// step: parseInt($scope.step),
-// orientation: $scope.orientation,
-// range: {
-// min: parseInt($scope.min),
-// max: parseInt($scope.max)
-// },
-// direction: $scope.direction
-// });
-// //$(".no-Ui-target").Link('upper').to('-inline-<div class="tooltip"></div>')
-// var onSlide = function(e, value) {
-// $timeout(function(){
-// $scope.value = value;
-// })
-
-// };
-// $($element).on({
-// change: onSlide,
-// slide: onSlide,
-// set: $scope.onSet({value: $scope.value})
-// });
-// var val = String(Math.round($scope.value));
-// if ($scope.percent) {
-// val += "%"
-// } else if ($scope.kvalue) {
-// val += "k"
-// }
-// $($element).height($scope.height);
-// if ($scope.tooltipInvert) {
-// $($element).find('.noUi-handle').append("<div class='tooltip' style='position:relative;right:20px'>" + val + "</div>");
-// } else {
-// $($element).find('.noUi-handle').append("<div class='tooltip' style='position:relative;left:-20px'>" + val + "</div>");
-// }
-// $scope.$watch('value', function(value) {
-// var val = String(Math.round($scope.value));
-// if ($scope.percent) {
-// val += "%"
-// } else if($scope.kvalue) {
-// val += "k"
-// }
-// $($element).val(value);
-// $($element).find('.tooltip').html(val);
-// if ($scope.tooltipInvert) {
-// $($element).find('.tooltip').css('right', $($element).find('.tooltip').innerWidth() * -1);
-// } else {
-// $($element).find('.tooltip').css('left', $($element).find('.tooltip').innerWidth() * -1);
-// }
-// });
-// };
-
-// return {
-// restrict : 'E',
-// template: '<div></div>',
-// controller : controller,
-// replace: true,
-// scope: {
-// min : '@',
-// max : '@',
-// width: '@',
-// height: '@',
-// step : '@',
-// orientation : '@',
-// tooltipInvert: '@',
-// percent: '@',
-// kvalue: '@?',
-// onSet:'&?',
-// direction: '@?',
-// value:'=?'
-// }
-// };
-// })
-// .directive('rwGauge', function() {
-// return {
-// restrict: 'AE',
-// template: '<canvas class="rwgauge" style="width:100%;height:100%;max-width:{{width}}px;max-height:240px;"></canvas>',
-// replace: true,
-// scope: {
-// min: '@?',
-// max: '@?',
-// size: '@?',
-// color: '@?',
-// value: '@?',
-// resize: '@?',
-// isAggregate: '@?',
-// units: '@?',
-// valueFormat: '=?',
-// width: '@?'
-// },
-// bindToController: true,
-// controllerAs: 'gauge',
-// controller: function($scope, $element) {
-// var self = this;
-// this.gauge = null;
-// this.min = this.min || 0;
-// this.max = this.max || 100;
-// this.nSteps = 14;
-// this.size = this.size || 300;
-// this.units = this.units || '';
-// $scope.width = this.width || 240;
-// this.color = this.color || 'hsla(212, 57%, 50%, 1)';
-// if (!this.valueFormat) {
-// if (this.max > 1000 || this.value) {
-// self.valueFormat = {
-// "int": 1,
-// "dec": 0
-// };
-// } else {
-// self.valueFormat = {
-// "int": 1,
-// "dec": 2
-// };
-// }
-// }
-// this.isAggregate = this.isAggregate || false;
-// this.resize = this.resize || false;
-// if (this.format == 'percent') {
-// self.valueFormat = {
-// "int": 3,
-// "dec": 0
-// };
-// }
-// $scope.$watch(function() {
-// return self.max;
-// }, function(n, o) {
-// if(n !== o) {
-// renderGauge();
-// }
-// });
-// $scope.$watch(function() {
-// return self.valueFormat;
-// }, function(n, o) {
-// if(n != 0) {
-// renderGauge();
-// }
-// });
-// $scope.$watch(function() {
-// return self.value;
-// }, function() {
-// if (self.gauge) {
-// // w/o rounding gauge will unexplainably thrash round.
-// self.valueFormat = determineValueFormat(self.value);
-// self.gauge.setValue(Math.ceil(self.value * 100) / 100);
-// //self.gauge.setValue(Math.round(self.value));
-// }
-// });
-// angular.element($element).ready(function() {
-// console.log('rendering')
-// renderGauge();
-// })
-// window.testme = renderGauge;
-// function determineValueFormat(value) {
-
-// if (value > 999 || self.units == "%") {
-// return {
-// "int": 1,
-// "dec": 0
-// }
-// }
-
-// return {
-// "int": 1,
-// "dec": 2
-// }
-// }
-// function renderGauge(calcWidth) {
-// if (self.max == self.min) {
-// self.max = 14;
-// }
-// var range = self.max - self.min;
-// var step = Math.round(range / self.nSteps);
-// var majorTicks = [];
-// for (var i = 0; i <= self.nSteps; i++) {
-// majorTicks.push(self.min + (i * step));
-// };
-// var redLine = self.min + (range * 0.9);
-// var config = {
-// isAggregate: self.isAggregate,
-// renderTo: angular.element($element)[0],
-// width: calcWidth || self.size,
-// height: calcWidth || self.size,
-// glow: false,
-// units: self.units,
-// title: false,
-// minValue: self.min,
-// maxValue: self.max,
-// majorTicks: majorTicks,
-// valueFormat: determineValueFormat(self.value),
-// minorTicks: 0,
-// strokeTicks: false,
-// highlights: [],
-// colors: {
-// plate: 'rgba(0,0,0,0)',
-// majorTicks: 'rgba(15, 123, 182, .84)',
-// minorTicks: '#ccc',
-// title: 'rgba(50,50,50,100)',
-// units: 'rgba(50,50,50,100)',
-// numbers: '#fff',
-// needle: {
-// start: 'rgba(255, 255, 255, 1)',
-// end: 'rgba(255, 255, 255, 1)'
-// }
-// }
-// };
-// var min = config.minValue;
-// var max = config.maxValue;
-// var N = 1000;
-// var increment = (max - min) / N;
-// for (i = 0; i < N; i++) {
-// var temp_color = 'rgb(0, 172, 238)';
-// if (i > 0.5714 * N && i <= 0.6428 * N) {
-// temp_color = 'rgb(0,157,217)';
-// } else if (i >= 0.6428 * N && i < 0.7142 * N) {
-// temp_color = 'rgb(0,142,196)';
-// } else if (i >= 0.7142 * N && i < 0.7857 * N) {
-// temp_color = 'rgb(0,126,175)';
-// } else if (i >= 0.7857 * N && i < 0.8571 * N) {
-// temp_color = 'rgb(0,122,154)';
-// } else if (i >= 0.8571 * N && i < 0.9285 * N) {
-// temp_color = 'rgb(0,96,133)';
-// } else if (i >= 0.9285 * N) {
-// temp_color = 'rgb(0,80,112)';
-// }
-// config.highlights.push({
-// from: i * increment,
-// to: increment * (i + 2),
-// color: temp_color
-// })
-// }
-// var updateSize = _.debounce(function() {
-// config.maxValue = self.max;
-// var clientWidth = self.parentNode.parentNode.clientWidth / 2;
-// var calcWidth = (300 > clientWidth) ? clientWidth : 300;
-// self.gauge.config.width = self.gauge.config.height = calcWidth;
-// self.renderGauge(calcWidth);
-// }, 500);
-// if (self.resize) $(window).resize(updateSize)
-// if (self.gauge) {
-// self.gauge.updateConfig(config);
-// } else {
-// self.gauge = new Gauge(config);
-// self.gauge.draw();
-// }
-// };
-// },
-// }
-// });
diff --git a/skyquake/framework/widgets/form_controls/formControls.jsx b/skyquake/framework/widgets/form_controls/formControls.jsx
new file mode 100644
index 0000000..e50fb7e
--- /dev/null
+++ b/skyquake/framework/widgets/form_controls/formControls.jsx
@@ -0,0 +1,113 @@
+import './formControls.jsx';
+
+import React from 'react'
+import SelectOption from 'widgets/form_controls/selectOption.jsx';
+import imgAdd from '../../../node_modules/open-iconic/svg/plus.svg'
+import imgRemove from '../../../node_modules/open-iconic/svg/trash.svg'
+import TextInput from 'widgets/form_controls/textInput.jsx';
+import Input from 'widgets/form_controls/input.jsx';
+
+export class FormSection extends React.Component {
+ render() {
+ let className = 'FormSection ' + this.props.className;
+ let html = (
+ <div
+ style={this.props.style}
+ className={className}
+ >
+ <div className="FormSection-title">
+ {this.props.title}
+ </div>
+ <div className="FormSection-body">
+ {this.props.children}
+ </div>
+ </div>
+ );
+ return html;
+ }
+}
+
+FormSection.defaultProps = {
+ className: ''
+}
+
+/**
+ * AddItemFn:
+ */
+export class InputCollection extends React.Component {
+ constructor(props) {
+ super(props);
+ this.collection = props.collection;
+ }
+ buildTextInput(onChange, v, i) {
+ return (
+ <Input
+ readonly={this.props.readonly}
+ style={{flex: '1 1'}}
+ key={i}
+ value={v}
+ onChange= {onChange.bind(null, i)}
+ />
+ )
+ }
+ buildSelectOption(initial, options, onChange, v, i) {
+ return (
+ <SelectOption
+ readonly={this.props.readonly}
+ key={`${i}-${v.replace(' ', '_')}`}
+ intial={initial}
+ defaultValue={v}
+ options={options}
+ onChange={onChange.bind(null, i)}
+ />
+ );
+ }
+ showInput() {
+
+ }
+ render() {
+ const props = this.props;
+ let inputType;
+ let className = "InputCollection";
+ if (props.className) {
+ className = `${className} ${props.className}`;
+ }
+ if (props.type == 'select') {
+ inputType = this.buildSelectOption.bind(this, props.initial, props.options, props.onChange);
+ } else {
+ inputType = this.buildTextInput.bind(this, props.onChange)
+ }
+ let html = (
+ <div className="InputCollection-wrapper">
+ {props.collection.map((v,i) => {
+ return (
+ <div key={i} className={className} >
+ {inputType(v, i)}
+ {
+ props.readonly ? null : <span onClick={props.RemoveItemFn.bind(null, i)} className="removeInput"><img src={imgRemove} />Remove</span>}
+ </div>
+ )
+ })}
+ { props.readonly ? null : <span onClick={props.AddItemFn} className="addInput"><img src={imgAdd} />Add</span>}
+ </div>
+ );
+ return html;
+ }
+}
+
+InputCollection.defaultProps = {
+ input: Input,
+ collection: [],
+ onChange: function(i, e) {
+ console.log(`
+ Updating with: ${e.target.value}
+ At index of: ${i}
+ `)
+ },
+ AddItemFn: function(e) {
+ console.log(`Adding a new item to collection`)
+ },
+ RemoveItemFn: function(i, e) {
+ console.log(`Removing item from collection at index of: ${i}`)
+ }
+}
diff --git a/skyquake/framework/widgets/form_controls/formControls.scss b/skyquake/framework/widgets/form_controls/formControls.scss
index 4a88435..ad95add 100644
--- a/skyquake/framework/widgets/form_controls/formControls.scss
+++ b/skyquake/framework/widgets/form_controls/formControls.scss
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,7 +15,7 @@
* limitations under the License.
*
*/
-@import 'style/_colors.scss';
+@import '../../style/_colors.scss';
.sqTextInput {
display: -ms-flexbox;
@@ -32,9 +32,9 @@
color:$darker-gray;
text-transform:uppercase;
}
- input, .readonly, textarea {
+ input, textarea {
height: 35px;
- box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.39), 0 -1px 1px #ffffff, 0 1px 0 #ffffff;
+ /* box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.39), 0 -1px 1px #ffffff, 0 1px 0 #ffffff;*/
font-size: 1rem;
display: block;
background: white !important;
@@ -49,6 +49,7 @@
.readonly {
line-height: 35px;
box-shadow:none;
+ background:none !important;
}
textarea {
-ms-flex-align: stretch;
@@ -57,4 +58,107 @@
border:0px;
height: 100%;
}
+ &.checkbox {
+ -ms-flex-direction:row;
+ flex-direction:row;
+ -ms-flex-align:center;
+ align-items:center;
+ margin-bottom:0;
+ >span {
+ -ms-flex-order: 1;
+ order: 1;
+ padding-left:1rem;
+ }
+ >input {
+ -ms-flex-order: 0;
+ order: 0;
+
+ box-shadow:none;
+ height:25px;
+ }
+ }
+ .invalid {
+ color: red;
+ font-weight:strong;
+ }
+ input:invalid {
+ border: 2px solid red;
+ &:after {
+ content: 'Invalid Value'
+ }
+ }
+}
+
+.sqCheckBox {
+ display:-ms-flexbox;
+ display:flex;
+ label {
+ display:-ms-flexbox;
+ display:flex;
+ -ms-flex-align: center;
+ align-items: center;
+ input {
+ box-shadow: none;
+ height: auto;
+ margin: 0 0.25rem;
+ }
+ }
+}
+
+.FormSection {
+ &-title {
+ color: #000;
+ background: lightgray;
+ padding: 0.5rem;
+ border-top: 1px solid #f1f1f1;
+ border-bottom: 1px solid #f1f1f1;
+ }
+ &-body {
+ padding: 0.5rem 0.75rem;
+ }
+ label {
+ -ms-flex: 1 0;
+ flex: 1 0;
+ }
+ /* label {*/
+ /* display: -ms-flexbox;*/
+ /* display: flex;*/
+ /* -ms-flex-direction: column;*/
+ /* flex-direction: column;*/
+ /* width: 100%;*/
+ /* margin: 0.5rem 0;*/
+ /* -ms-flex-align: start;*/
+ /* align-items: flex-start;*/
+ /* -ms-flex-pack: start;*/
+ /* justify-content: flex-start;*/
+ /* }*/
+ select {
+ font-size: 1rem;
+ min-width: 75%;
+ height: 35px;
+ }
+}
+
+
+
+
+.InputCollection {
+ display:-ms-flexbox;
+ display:flex;
+ -ms-flex-wrap: nowrap;
+ flex-wrap: nowrap;
+ -ms-flex-align: center;
+ align-items: center;
+ button {
+ padding: 0.25rem;
+ height: 1.5rem;
+ font-size: 0.75rem;
+ }
+ select {
+ min-width: 100%;
+ }
+ margin-bottom:0.5rem;
+ &-wrapper {
+
+ }
}
diff --git a/skyquake/framework/widgets/form_controls/input.jsx b/skyquake/framework/widgets/form_controls/input.jsx
new file mode 100644
index 0000000..ca31c13
--- /dev/null
+++ b/skyquake/framework/widgets/form_controls/input.jsx
@@ -0,0 +1,134 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+import './formControls.scss';
+import SelectOption from 'widgets/form_controls/selectOption.jsx';
+import CheckSVG from '../../../node_modules/open-iconic/svg/check.svg'
+import React, {Component} from 'react';
+
+export default class Input extends Component {
+ render() {
+ let {label, value, defaultValue, ...props} = this.props;
+ let inputProperties = {
+ value: value
+ }
+ let isRequired;
+ let inputType;
+ let tester = null;
+ let className = `sqTextInput ${props.className}`;
+
+ if(this.props.required) {
+ isRequired = <span className="required">*</span>
+ }
+ if (defaultValue) {
+ inputProperties.defaultValue = defaultValue;
+ }
+ if (props.pattern) {
+ inputProperties.pattern = props.pattern;
+ tester = new RegExp(props.pattern);
+ }
+ if(props.hasOwnProperty('type') && (props.type.toLowerCase() == 'checkbox')) {
+ inputProperties.checked = props.checked;
+ className = `${className} checkbox`;
+ }
+ if (value == undefined) {
+ value = defaultValue;
+ }
+ switch(props.type) {
+ case 'textarea':
+ inputType = <textarea key={props.key} {...inputProperties} value={value} onChange={props.onChange} />
+ break;
+ case 'select':
+ inputType = <SelectOption
+ key={props.key}
+ initial={props.initial}
+ defaultValue={defaultValue}
+ options={props.options}
+ onChange={props.onChange}
+ />
+ break;
+ case 'radiogroup':
+ inputType = buildRadioButtons(this.props);
+ break;
+ default:
+ inputType = <input key={props.key} type={props.type} {...inputProperties} onChange={props.onChange} placeholder={props.placeholder}/>;
+ }
+ let displayedValue;
+ if(value === null) {
+ displayedValue = null;
+ } else {
+ displayedValue = value.toString();
+ }
+ if( props.readonly && props.type == "checkbox" && props.checked ) {
+ displayedValue = <img src={CheckSVG} />
+ }
+
+ if( props.readonly && props.type == "radiogroup" && props.readonlydisplay ) {
+ displayedValue = props.readonlydisplay
+ }
+
+ let html = (
+ <label className={className} style={props.style}>
+ <span> { label } {isRequired}</span>
+ {
+ !props.readonly ? inputType : <div className="readonly">{displayedValue}</div>
+ }
+ {
+ !props.readonly && tester && value && !tester.test(value) ? <span className="invalid">The Value you entered is invalid</span> : null
+ }
+ </label>
+ );
+ return html;
+ }
+}
+
+
+function buildRadioButtons(props) {
+ let className = 'sqCheckBox';
+ return(
+ <div className={className}>
+ {
+ props.options.map((o,i) => {
+ let label = o.label || o;
+ let value = o.value || o;
+ return (
+ <label key={i}>
+ {label}
+ <input type="radio" checked={props.value == value} value={value} onChange={props.onChange} />
+ </label>
+ )
+ })
+ }
+ </div>
+
+ )
+}
+
+Input.defaultProps = {
+ onChange: function(e) {
+ console.log(e.target.value, e);
+ console.dir(e.target);
+ },
+ label: '',
+ defaultValue: null,
+ type: 'text',
+ readonly: false,
+ style:{},
+ className: ''
+
+}
+
diff --git a/skyquake/framework/widgets/form_controls/selectOption.jsx b/skyquake/framework/widgets/form_controls/selectOption.jsx
index 41a8b13..067d1d5 100644
--- a/skyquake/framework/widgets/form_controls/selectOption.jsx
+++ b/skyquake/framework/widgets/form_controls/selectOption.jsx
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,32 +28,65 @@
render() {
let html;
let defaultValue = this.props.defaultValue;
- let options = this.props.options.map(function(op, i) {
- let value = JSON.stringify(op.value);
- return <option key={i} value={JSON.stringify(op.value)}>{op.label}</option>
- });
+ let options = this.props.options && this.props.options.map(function(op, i) {
+ let value;
+ let label;
+ if(typeof(op) == 'object') {
+ value = JSON.stringify(op.value);
+ label = op.label;
+ } else {
+ value = op;
+ label = op;
+ }
+
+ return <option key={i} value={JSON.stringify(value)}>{label}</option>
+ }) || [];
if (this.props.initial) {
options.unshift(<option key='blank' value={JSON.stringify(this.props.defaultValue)}></option>);
}
html = (
- <label>
- {this.props.label}
- <select className={this.props.className} onChange={this.handleOnChange} defaultValue={JSON.stringify(defaultValue)} >
- {
- options
- }
- </select>
+ <label key={this.props.key} className={this.props.className}>
+ <span>{this.props.label}</span>
+ {
+ this.props.readonly ? defaultValue
+ : (
+ <select
+ className={this.props.className}
+ onChange={this.handleOnChange}
+ value={JSON.stringify(this.props.value)}
+ defaultValue={JSON.stringify(defaultValue)}>
+ {
+ options
+ }
+ </select>
+ )
+ }
</label>
);
return html;
}
}
SelectOption.defaultProps = {
+ /**
+ * [options description]
+ * @type {Array} - Expects items to contain objects with the properties 'label' and 'value' which are both string types. Hint: JSON.stringify()
+ */
options: [],
onChange: function(e) {
+ console.log(e.target.value)
console.dir(e)
},
- defaultValue: false,
+ readonly: false,
+ /**
+ * Selected or default value
+​
+ * @type {[type]}
+ */
+ defaultValue: null,
+ /**
+ * True if first entry in dropdown should be blank
+ * @type {Boolean}
+ */
initial: false,
label: null
}
diff --git a/skyquake/framework/widgets/form_controls/textInput.jsx b/skyquake/framework/widgets/form_controls/textInput.jsx
index 03dfa9c..000dcf7 100644
--- a/skyquake/framework/widgets/form_controls/textInput.jsx
+++ b/skyquake/framework/widgets/form_controls/textInput.jsx
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,58 +18,12 @@
import './formControls.scss';
import React, {Component} from 'react';
-
-export default class TextInput extends Component {
- render() {
- let {label, onChange, value, defaultValue, ...props} = this.props;
- let inputProperties = {
- value: value,
- onChange: onChange
- }
- let isRequired;
- let inputType;
- if(this.props.required) {
- isRequired = <span className="required">*</span>
- }
- if (defaultValue) {
- inputProperties.defaultValue = defaultValue;
- }
- if (props.pattern) {
- inputProperties.pattern = props.pattern;
- }
- if (value == undefined) {
- value = defaultValue;
- }
- switch(props.type) {
- case 'textarea':
- inputType = <textarea {...inputProperties} value={value}/>
-
- break;
- default:
- inputType = <input type={props.type} {...inputProperties} placeholder={props.placeholder}/>;
- }
- let html = (
- <label className={"sqTextInput " + props.className} style={props.style}>
- <span> { label } {isRequired}</span>
- {
- !props.readonly ? inputType : <div className="readonly">{value}</div>
- }
-
- </label>
- );
- return html;
+import Input from './input.jsx';
+class TextInput extends Input {
+ constructor(props) {
+ super(props);
+ console.warn('TextInput is deprecated. Use Input component instead')
}
}
-
-TextInput.defaultProps = {
- onChange: function(e) {
- console.log(e.target.value);
- },
- label: '',
- defaultValue: undefined,
- type: 'text',
- readonly: false,
- style:{}
-
-}
+export default TextInput;
diff --git a/skyquake/framework/widgets/header/header.scss b/skyquake/framework/widgets/header/header.scss
index 5e1e717..6a2e56c 100644
--- a/skyquake/framework/widgets/header/header.scss
+++ b/skyquake/framework/widgets/header/header.scss
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,14 +17,20 @@
*/
header.header-app-component {
- padding: 20px 0px;
+ padding: 10px 0px;
+ display:-ms-flexbox;
display:flex;
- flex-direction:column;
+ -ms-flex-direction:column;
+ flex-direction:column;
.header-app-main {
+ display:-ms-flexbox;
display:flex;
- flex-direction:row;
- justify-content:space-between;
- align-items:center;
+ -ms-flex-direction:row;
+ flex-direction:row;
+ -ms-flex-pack:justify;
+ justify-content:space-between;
+ -ms-flex-align:center;
+ align-items:center;
}
h1 {
/*background: url('../../style/img/header-logo.png') no-repeat;*/
@@ -39,15 +45,19 @@
font-size: 1.625rem;
font-weight: 400;
position:relative;
- flex: 1 0 auto;
+ -ms-flex: 1 0 auto;
+ flex: 1 0 auto;
}
ul {
+ display:-ms-flexbox;
display:flex;
}
li {
+ display:-ms-flexbox;
display:flex;
- flex:1 1 auto;
+ -ms-flex:1 1 auto;
+ flex:1 1 auto;
border-right:1px solid #e5e5e5;
padding: 0 1rem;
&:last-child {
@@ -55,12 +65,13 @@
}
a {
cursor:pointer;
- // padding: 0.125rem;
- // border-bottom:1px solid black;
+ /* padding: 0.125rem;*/
+ /* border-bottom:1px solid black;*/
text-decoration:underline;
}
}
.header-app-nav {
+ display:-ms-flexbox;
display:flex;
margin-left: 0.25rem;
a,span {
@@ -81,8 +92,11 @@
}
}
nav {
+ display:-ms-flexbox;
display:flex;
- flex:0 1 auto;
- align-items:center;
+ -ms-flex:0 1 auto;
+ flex:0 1 auto;
+ -ms-flex-align:center;
+ align-items:center;
}
}
diff --git a/skyquake/framework/widgets/operational-status/launchpadOperationalStatus.jsx b/skyquake/framework/widgets/operational-status/launchpadOperationalStatus.jsx
index ba77a79..0e12b6e 100644
--- a/skyquake/framework/widgets/operational-status/launchpadOperationalStatus.jsx
+++ b/skyquake/framework/widgets/operational-status/launchpadOperationalStatus.jsx
@@ -1,6 +1,6 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -101,7 +101,7 @@
}
render() {
if(!this.props.hasFailed) {
- return (<span className='throttledMessageText'>{this.state.displayMessage}</span>)
+ return (<span className='throttledMessageText' style={{margin:'1rem'}}>{this.state.displayMessage}</span>)
} else {
return (<span> </span>)
}
diff --git a/skyquake/framework/widgets/panel/panel.jsx b/skyquake/framework/widgets/panel/panel.jsx
index 4ef7c89..03877b0 100644
--- a/skyquake/framework/widgets/panel/panel.jsx
+++ b/skyquake/framework/widgets/panel/panel.jsx
@@ -18,6 +18,7 @@
import React, {Component} from 'react';
import 'style/core.css';
import './panel.scss';
+import circleXImage from '../../../node_modules/open-iconic/svg/circle-x.svg';
export class Panel extends Component {
constructor(props) {
super(props)
@@ -28,8 +29,15 @@
let classRoot = className ? ' ' + className : ' ';
let hasCorners = this.props['no-corners'];
let titleTag = title ? <header className="skyquakePanel-title">{title}</header> : '';
+ let closeButton = (
+ <a onClick={self.props.hasCloseButton}
+ className={"close-btn"}>
+ <img src={circleXImage} title="Close card" />
+ </a>
+ );
return (
<section className={'skyquakePanel' + classRoot} style={props.style}>
+ { self.props.hasCloseButton ? closeButton : null}
{ !hasCorners ? <i className="corner-accent top left"></i> : null }
{ !hasCorners ? <i className="corner-accent top right"></i> : null }
{titleTag}
@@ -51,13 +59,23 @@
export class PanelWrapper extends Component {
render() {
+ let wrapperClass = 'skyquakePanelWrapper';
+ let {className, column, style, ...props} = this.props;
+ if(className) {
+ wrapperClass = `${wrapperClass} ${className}`
+ }
+ if(column) {
+ style.flexDirection = 'column';
+ }
return (
- <div className={'skyquakePanelWrapper ' + this.props.className} style={this.props.style}>
+ <div className={wrapperClass} style={style} {...props}>
{this.props.children}
</div>)
}
}
-
+PanelWrapper.defaultProps = {
+ style: {}
+}
export default Panel;
diff --git a/skyquake/framework/widgets/panel/panel.scss b/skyquake/framework/widgets/panel/panel.scss
index 2a31b1c..75dc8ac 100644
--- a/skyquake/framework/widgets/panel/panel.scss
+++ b/skyquake/framework/widgets/panel/panel.scss
@@ -53,9 +53,22 @@
width:100%;
height:100%;
}
+ .close-btn {
+ cursor:pointer;
+ position: absolute;
+ right: -0.5rem;
+ top: -0.5rem;
+ img {
+ width: 1rem;
+ }
+ }
}
.skyquakePanelWrapper.column {
+ -ms-flex-direction:column;
+ flex-direction:column;
+ display:-ms-flexbox;
+ display:flex;
.skyquakePanel-wrapper {
height:auto;
}
diff --git a/skyquake/framework/widgets/skyquake_container/eventCenter.jsx b/skyquake/framework/widgets/skyquake_container/eventCenter.jsx
index 7df4e3e..471efd1 100644
--- a/skyquake/framework/widgets/skyquake_container/eventCenter.jsx
+++ b/skyquake/framework/widgets/skyquake_container/eventCenter.jsx
@@ -16,12 +16,12 @@
*
*/
- /**
- * EventCenter module to display a list of events from the system
- * @module framework/widgets/skyquake_container/EventCenter
- * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
- *
- */
+/**
+ * EventCenter module to display a list of events from the system
+ * @module framework/widgets/skyquake_container/EventCenter
+ * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
+ *
+ */
import React from 'react';
import { Link } from 'react-router';
@@ -31,6 +31,8 @@
import _isEqual from 'lodash/isEqual';
import _merge from 'lodash/merge';
import _indexOf from 'lodash/indexOf';
+import _isArray from 'lodash/isArray';
+import _sortBy from 'lodash/sortBy';
import '../../../node_modules/react-treeview/react-treeview.css';
import './eventCenter.scss';
@@ -44,7 +46,6 @@
componentWillReceiveProps(props) {
let stateObject = {};
- let notificationList = sessionStorage.getItem('notificationList');
let latestNotification = sessionStorage.getItem('latestNotification');
if (props.newNotificationEvent && props.newNotificationMsg) {
@@ -67,21 +68,16 @@
stateObject.newNotificationEvent = false;
stateObject.newNotificationMsg = null;
}
+ stateObject.notifications = props.notifications;
- if (notificationList) {
- stateObject.notifications = _merge(notificationList, props.notifications);
- } else {
- stateObject.notifications = props.notifications;
- }
- sessionStorage.setItem('notifications', JSON.stringify(stateObject.notifications));
this.setState(stateObject);
}
newNotificationReset = () => {
- this.setState({
- newNotificationEvent: false
- });
- }
+ this.setState({
+ newNotificationEvent: false
+ });
+ }
onClickToggleOpenClose(event) {
this.props.onToggle();
@@ -92,13 +88,13 @@
constructTree(details) {
let markup = [];
for (let key in details) {
- if (typeof(details[key]) == "object") {
- let html = (
- <TreeView key={key} nodeLabel={key}>
- {this.constructTree(details[key])}
- </TreeView>
- );
- markup.push(html);
+ if (typeof (details[key]) == "object") {
+ let html = (
+ <TreeView key={key} nodeLabel={key}>
+ {this.constructTree(details[key])}
+ </TreeView>
+ );
+ markup.push(html);
} else {
markup.push((<div key={key} className="info">{key} = {details[key].toString()}</div>));
}
@@ -142,40 +138,42 @@
);
}
- this.state.notifications && this.state.notifications.map((notification, notifIndex) => {
- let notificationFields = {};
+ this.state.notifications &&
+ _isArray(this.state.notifications) &&
+ this.state.notifications.map((notification, notifIndex) => {
+ let notificationFields = {};
- notificationFields = this.getNotificationFields(notification);
+ notificationFields = this.getNotificationFields(notification);
- displayNotifications.push(
- <tr key={notifIndex} className='notificationItem'>
- <td className='source column'> {notificationFields.source} </td>
- <td className='timestamp column'> {notificationFields.eventTime} </td>
- <td className='event column'> {notificationFields.eventKey} </td>
- <td className='details column'>
- <TreeView key={notifIndex + '-detail'} nodeLabel='Event Details'>
- {this.constructTree(notificationFields.details)}
- </TreeView>
- </td>
- </tr>
- );
- });
+ displayNotifications.push(
+ <tr key={notifIndex} className='notificationItem'>
+ <td className='source column'> {notificationFields.source} </td>
+ <td className='timestamp column'> {notificationFields.eventTime} </td>
+ <td className='event column'> {notificationFields.eventKey} </td>
+ <td className='details column'>
+ <TreeView key={notifIndex + '-detail'} nodeLabel='Event Details'>
+ {this.constructTree(notificationFields.details)}
+ </TreeView>
+ </td>
+ </tr>
+ );
+ });
let openedClassName = this.state.isOpen ? 'open' : 'closed';
html = (
<div className={'eventCenter ' + openedClassName}>
- <div className='notification'>
- <Crouton
- id={Date.now()}
- message={this.getNotificationFields(this.state.newNotificationMsg).eventKey +
- ' notification received. Check Event Center for more details.'}
- type={'info'}
- hidden={!(this.state.newNotificationEvent && this.state.newNotificationMsg)}
- onDismiss={this.newNotificationReset}
- timeout={this.props.dismissTimeout}
- />
- </div>
+ <div className='notification'>
+ <Crouton
+ id={Date.now()}
+ message={this.getNotificationFields(this.state.newNotificationMsg).eventKey +
+ ' notification received. Check Event Center for more details.'}
+ type={'info'}
+ hidden={!(this.state.newNotificationEvent && this.state.newNotificationMsg)}
+ onDismiss={this.newNotificationReset}
+ timeout={this.props.dismissTimeout}
+ />
+ </div>
<h1 className='title' data-open-close-icon={this.state.isOpen ? 'open' : 'closed'}
onClick={this.onClickToggleOpenClose.bind(this)}>
EVENT CENTER
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeApp.scss b/skyquake/framework/widgets/skyquake_container/skyquakeApp.scss
index 2869560..b6f688f 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeApp.scss
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeApp.scss
@@ -7,15 +7,18 @@
.crouton {
span {
- white-space: pre;
+ /* white-space: pre;*/
}
}
.skyquakeApp {
display: -ms-flexbox;
+ display: -webkit-box;
display: flex;
-ms-flex-direction: column;
- flex-direction: column;
+ -webkit-box-orient: vertical;
+ -webkit-box-direction: normal;
+ flex-direction: column;
height: 100%;
background: $gray-lightest;
h1 {
@@ -28,6 +31,7 @@
}
.skyquakeNav {
display: -ms-flexbox;
+ display: -webkit-box;
display: flex;
color:white;
background:black;
@@ -36,11 +40,14 @@
font-size:0.75rem;
.secondaryNav {
-ms-flex: 1 1 auto;
- flex: 1 1 auto;
+ -webkit-box-flex: 1;
+ flex: 1 1 auto;
display: -ms-flexbox;
+ display: -webkit-box;
display: flex;
-ms-flex-pack: end;
- justify-content: flex-end;
+ -webkit-box-pack: end;
+ justify-content: flex-end;
}
.app {
position:relative;
@@ -48,9 +55,11 @@
font-size:0.75rem;
border-right: 1px solid black;
display: -ms-flexbox;
+ display: -webkit-box;
display: flex;
-ms-flex-align: center;
- align-items: center;
+ -webkit-box-align: center;
+ align-items: center;
.oi {
padding-right: 0.5rem;
}
@@ -60,6 +69,11 @@
display:none;
z-index:2;
width: 100%;
+ &.project {
+ a {
+ text-transform:none;
+ }
+ }
}
&:first-child{
h2 {
@@ -102,12 +116,13 @@
&:before {
content: '';
height:1.85rem;
- width:5.5rem;
- /*margin:0 1rem;*/
- /*padding:0 0.125rem;*/
+ width:2.5rem;
+ margin:auto 1rem;
+ padding:0 0.125rem;
+ /* background: url('../../style/img/header-logo.png') no-repeat center center white;*/
/*background: url('../../style/img/svg/riftio_logo_white.svg') no-repeat center center;*/
background: url('../../style/img/svg/osm-logo_color_rgb_white_text.svg') no-repeat center center;
- background-size: contain;
+ background-size:contain;
}
}
.skyquakeContainerWrapper {
@@ -127,7 +142,8 @@
text-align:left;
position:relative;
-ms-flex: 1 0 auto;
- flex: 1 0 auto;
+ -webkit-box-flex: 1;
+ flex: 1 0 auto;
}
}
.corner-accent {
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeComponent.jsx b/skyquake/framework/widgets/skyquake_container/skyquakeComponent.jsx
index 893a4c1..cd489ac 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeComponent.jsx
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeComponent.jsx
@@ -7,7 +7,7 @@
this.actions = context.flux.actions.global;
}
render(props) {
- return <Component {...this.props} router={this.router} actions={this.actions} flux={this.context.flux} />
+ return <Component {...this.props} router={this.router} actions={this.actions} flux={this.context.flux}/>
}
}
SkyquakeComponent.contextTypes = {
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeContainer.jsx b/skyquake/framework/widgets/skyquake_container/skyquakeContainer.jsx
index d83c836..5c4c97e 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeContainer.jsx
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeContainer.jsx
@@ -18,17 +18,23 @@
import React from 'react';
import AltContainer from 'alt-container';
import Alt from './skyquakeAltInstance.js';
-import SkyquakeNav from './skyquakeNav.jsx';
+ import _cloneDeep from 'lodash/cloneDeep';
+import SkyquakeNav from '../skyquake_nav/skyquakeNav.jsx';
import EventCenter from './eventCenter.jsx';
import SkyquakeContainerActions from './skyquakeContainerActions.js'
import SkyquakeContainerStore from './skyquakeContainerStore.js';
// import Breadcrumbs from 'react-breadcrumbs';
import Utils from 'utils/utils.js';
import Crouton from 'react-crouton';
+import SkyquakeNotification from '../skyquake_notification/skyquakeNotification.jsx';
import ScreenLoader from 'widgets/screen-loader/screenLoader.jsx';
+import {SkyquakeRBAC, isRBACValid} from 'widgets/skyquake_rbac/skyquakeRBAC.jsx';
+import ROLES from 'utils/roleConstants.js';
import './skyquakeApp.scss';
// import 'style/reset.css';
import 'style/core.css';
+const PROJECT_ROLES = ROLES.PROJECT;
+const PLATFORM = ROLES.PLATFORM;
export default class skyquakeContainer extends React.Component {
constructor(props) {
super(props);
@@ -39,13 +45,21 @@
this.state.eventCenterIsOpen = false;
this.state.currentPlugin = SkyquakeContainerStore.currentPlugin;
}
-
+ getChildContext() {
+ return {
+ userProfile: this.state.user
+ };
+ }
+ getUserProfile() {
+ return this.state.user;
+ }
componentWillMount() {
let self = this;
Utils.bootstrapApplication().then(function() {
SkyquakeContainerStore.listen(self.listener);
SkyquakeContainerStore.getNav();
+ SkyquakeContainerStore.getUserProfile();
SkyquakeContainerStore.getEventStreams();
});
@@ -82,12 +96,14 @@
}
render() {
- const {displayNotification, notificationMessage, displayScreenLoader, notificationType, ...state} = this.state;
+ const {displayNotification, notificationData, displayScreenLoader,...state} = this.state;
+ const User = this.state.user || {};
+ const rbacValid = isRBACValid(User, [PLATFORM.SUPER, PLATFORM.ADMIN, PLATFORM.OPER]);
var html;
-
+ let nav = _cloneDeep(this.state.nav);
if (this.matchesLoginUrl()) {
html = (
- <AltContainer>
+ <AltContainer flux={Alt}>
<div className="skyquakeApp">
{this.props.children}
</div>
@@ -100,29 +116,33 @@
html = (
<AltContainer flux={Alt}>
<div className="skyquakeApp wrap">
- <Crouton
- id={Date.now()}
- message={notificationMessage}
- type={notificationType}
- hidden={!(displayNotification && notificationMessage)}
+ <SkyquakeNotification
+ data={this.state.notificationData}
+ visible={displayNotification}
onDismiss={SkyquakeContainerActions.hideNotification}
- timeout= {5000}
/>
<ScreenLoader show={displayScreenLoader}/>
- <SkyquakeNav nav={this.state.nav}
+ <SkyquakeNav nav={nav}
currentPlugin={this.state.currentPlugin}
- store={SkyquakeContainerStore} />
+ currentUser={this.state.user.userId}
+ currentProject={this.state.user.projectId}
+ store={SkyquakeContainerStore}
+ projects={this.state.projects} />
<div className="titleBar">
- <h1>{this.state.currentPlugin + tag}</h1>
+ <h1>{(this.state.nav.name ? this.state.nav.name.replace('_', ' ').replace('-', ' ') : this.state.currentPlugin && this.state.currentPlugin.replace('_', ' ').replace('-', ' ')) + tag}</h1>
</div>
<div className={"application " + routeName}>
{this.props.children}
</div>
- <EventCenter className="eventCenter"
- notifications={this.state.notifications}
- newNotificationEvent={this.state.newNotificationEvent}
- newNotificationMsg={this.state.newNotificationMsg}
- onToggle={this.onToggle} />
+ {
+ rbacValid ?
+ <EventCenter className="eventCenter"
+ notifications={this.state.notifications}
+ newNotificationEvent={this.state.newNotificationEvent}
+ newNotificationMsg={this.state.newNotificationMsg}
+ onToggle={this.onToggle} />
+ : null
+ }
</div>
</AltContainer>
);
@@ -130,6 +150,9 @@
return html;
}
}
+skyquakeContainer.childContextTypes = {
+ userProfile: React.PropTypes.object
+};
skyquakeContainer.contextTypes = {
router: React.PropTypes.object
};
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeContainerActions.js b/skyquake/framework/widgets/skyquake_container/skyquakeContainerActions.js
index 773978b..1124658 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeContainerActions.js
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeContainerActions.js
@@ -1,5 +1,5 @@
/*
- *
+ *
* Copyright 2016 RIFT.IO Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,9 +25,13 @@
'getEventStreamsSuccess',
'getEventStreamsError',
//Notifications
+ 'handleServerReportedError',
'showNotification',
'hideNotification',
//Screen Loader
'showScreenLoader',
- 'hideScreenLoader'
+ 'hideScreenLoader',
+ 'openProjectSocketSuccess',
+ 'getUserProfileSuccess',
+ 'selectActiveProjectSuccess'
);
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeContainerSource.js b/skyquake/framework/widgets/skyquake_container/skyquakeContainerSource.js
index da7080f..f02e7ba 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeContainerSource.js
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeContainerSource.js
@@ -79,7 +79,7 @@
remote: function(state, location, streamSource) {
return new Promise((resolve, reject) => {
$.ajax({
- url: '//' + window.location.hostname + ':' + window.location.port + '/socket-polling?api_server=' + API_SERVER,
+ url: '//' + window.location.hostname + ':' + window.location.port + '/socket-polling',
type: 'POST',
beforeSend: Utils.addAuthorizationStub,
data: {
@@ -114,6 +114,79 @@
success: SkyquakeContainerActions.openNotificationsSocketSuccess,
error: SkyquakeContainerActions.openNotificationsSocketError
}
+ },
+ openProjectSocket() {
+ return {
+ remote: function(state) {
+ return new Promise(function(resolve, reject) {
+ //If socket connection already exists, eat the request.
+ if(state.socket) {
+ return resolve(false);
+ }
+ $.ajax({
+ url: '/socket-polling',
+ type: 'POST',
+ beforeSend: Utils.addAuthorizationStub,
+ data: {
+ url: '/project?api_server=' + API_SERVER
+ },
+ success: function(data, textStatus, jqXHR) {
+ Utils.checkAndResolveSocketRequest(data, resolve, reject);
+ }
+ })
+ .fail(function(xhr){
+ //Authentication and the handling of fail states should be wrapped up into a connection class.
+ Utils.checkAuthentication(xhr.status);
+ });;
+ });
+ },
+ success: SkyquakeContainerActions.openProjectSocketSuccess
+ }
+ },
+
+ getUserProfile() {
+ return {
+ remote: function(state, recordID) {
+ return new Promise(function(resolve, reject) {
+ $.ajax({
+ url: '/user-profile?api_server=' + API_SERVER,
+ type: 'GET',
+ beforeSend: Utils.addAuthorizationStub,
+ success: function(data) {
+ resolve(data);
+ }
+ }).fail(function(xhr) {
+ //Authentication and the handling of fail states should be wrapped up into a connection class.
+ Utils.checkAuthentication(xhr.status);
+ });;
+ });
+ },
+ loading: Alt.actions.global.showScreenLoader,
+ success: SkyquakeContainerActions.getUserProfileSuccess
+ }
+ },
+
+ selectActiveProject() {
+ return {
+ remote: function(state, projectId) {
+ const {currentPlugin} = state;
+ const encodedProjectId = encodeURIComponent(projectId);
+ return new Promise(function(resolve, reject) {
+ $.ajax({
+ url: `/session/${encodedProjectId}?api_server=${API_SERVER}&app=${currentPlugin}`,
+ type: 'PUT',
+ beforeSend: Utils.addAuthorizationStub,
+ success: function(data) {
+ resolve(projectId);
+ }
+ }).fail(function(xhr) {
+ //Authentication and the handling of fail states should be wrapped up into a connection class.
+ Utils.checkAuthentication(xhr.status);
+ });;
+ });
+ },
+ success: SkyquakeContainerActions.selectActiveProjectSuccess
+ }
}
}
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeContainerStore.js b/skyquake/framework/widgets/skyquake_container/skyquakeContainerStore.js
index 56ebdda..e9ba78e 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeContainerStore.js
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeContainerStore.js
@@ -20,19 +20,25 @@
import Alt from './skyquakeAltInstance.js';
import SkyquakeContainerSource from './skyquakeContainerSource.js';
import SkyquakeContainerActions from './skyquakeContainerActions';
+let Utils = require('utils/utils.js');
import _indexOf from 'lodash/indexOf';
+import _isEqual from 'lodash/isEqual';
//Temporary, until api server is on same port as webserver
import rw from 'utils/rw.js';
var API_SERVER = rw.getSearchParams(window.location).api_server;
-var UPLOAD_SERVER = rw.getSearchParams(window.location).upload_server;
+const MAX_STORED_EVENTS = 20;
class SkyquakeContainerStore {
constructor() {
this.currentPlugin = getCurrentPlugin();
this.nav = {};
- this.notifications = [];
+ let notificationList = null;
+ try {notificationList = JSON.parse(sessionStorage.getItem('notifications'));} catch (e) {}
+ this.notifications = notificationList || [];
this.socket = null;
+ this.projects = null;
+ this.user = {};
//Notification defaults
this.notificationMessage = '';
this.displayNotification = false;
@@ -96,6 +102,9 @@
ws.onmessage = (socket) => {
try {
var data = JSON.parse(socket.data);
+ if(data.hasOwnProperty('map')) {
+ data = [];
+ }
if (!data.notification) {
console.warn('No notification in the received payload: ', data);
} else {
@@ -105,12 +114,14 @@
// newly appreared event.
// Add to the notifications list and setState
self.notifications.unshift(data.notification);
+ (self.notifications.length > MAX_STORED_EVENTS) && self.notifications.pop();
self.setState({
newNotificationEvent: true,
newNotificationMsg: data.notification,
notifications: self.notifications,
isLoading: false
});
+ sessionStorage.setItem('notifications', JSON.stringify(self.notifications));
}
}
} catch(e) {
@@ -137,6 +148,7 @@
console.log('Found streams: ', streams);
let self = this;
+ streams &&
streams['ietf-restconf-monitoring:streams'] &&
streams['ietf-restconf-monitoring:streams']['stream'] &&
streams['ietf-restconf-monitoring:streams']['stream'].map((stream) => {
@@ -162,23 +174,53 @@
})
}
+ openProjectSocketSuccess = (connection) => {
+ var self = this;
+ var ws = window.multiplexer.channel(connection);
+ if (!connection) return;
+ self.setState({
+ socket: ws.ws,
+ channelId: connection
+ });
+ ws.onmessage = function(socket) {
+ try {
+ var data = JSON.parse(socket.data);
+ Utils.checkAuthentication(data.statusCode, function() {
+ self.closeSocket();
+ });
+ if (!data.project || !_isEqual(data.project, self.projects)) {
+ let user = self.user;
+ user.projects = data.project;
+ self.setState({
+ user: user,
+ projects: data.project || {}
+ });
+ }
+ } catch(e) {
+ console.log('HIT an exception in openProjectSocketSuccess', e);
+ }
+ };
+ }
+ getUserProfileSuccess = (user) => {
+ this.alt.actions.global.hideScreenLoader.defer();
+ this.setState({user})
+ }
+ selectActiveProjectSuccess = (projectId) => {
+ let user = this.user;
+ user.projectId = projectId;
+ this.setState({user});
+ window.location.href = window.location.origin;
+ }
//Notifications
- showNotification = (data) => {
- let state = {
- displayNotification: true,
- notificationMessage: data,
- notificationType: 'error',
- displayScreenLoader: false
- }
- if(typeof(data) == 'string') {
-
- } else {
- state.notificationMessage = data.msg;
- if(data.type) {
- state.notificationType = data.type;
- }
- }
- this.setState(state);
+ handleServerReportedError = (result) => {
+ this.hideScreenLoader();
+ this.alt.actions.global.showNotification.defer(result);
+ }
+ showNotification = (notificationData) => {
+ this.setState({
+ notificationData,
+ displayNotification: true
+ })
}
hideNotification = () => {
this.setState({
@@ -211,7 +253,7 @@
if (k != currentPlugin) {
nav[k].routes.map(function(route, i) {
if (API_SERVER) {
- route.route = '/' + k + '/index.html?api_server=' + API_SERVER + '&upload_server=' + UPLOAD_SERVER + '#' + route.route;
+ route.route = '/' + k + '/index.html?api_server=' + API_SERVER + '#' + route.route;
} else {
route.route = '/' + k + '/#' + route.route;
}
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeNav.jsx b/skyquake/framework/widgets/skyquake_container/skyquakeNav.jsx
deleted file mode 100644
index 8814a18..0000000
--- a/skyquake/framework/widgets/skyquake_container/skyquakeNav.jsx
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- *
- * Copyright 2016 RIFT.IO Inc
- *
- * 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.
- *
- */
-
-import React from 'react';
-import { Link } from 'react-router';
-import Utils from 'utils/utils.js';
-import Crouton from 'react-crouton';
-import 'style/common.scss';
-
-//Temporary, until api server is on same port as webserver
-import rw from 'utils/rw.js';
-
-var API_SERVER = rw.getSearchParams(window.location).api_server;
-var UPLOAD_SERVER = rw.getSearchParams(window.location).upload_server;
-
-//
-// Internal classes/functions
-//
-
-class LogoutAppMenuItem extends React.Component {
- handleLogout() {
- Utils.clearAuthentication();
- }
- render() {
- return (
- <div className="app">
- <h2>
- <a onClick={this.handleLogout}>
- Logout
- </a>
- </h2>
- </div>
- );
- }
-}
-
-
-//
-// Exported classes and functions
-//
-
-//
-/**
- * Skyquake Nav Component. Provides navigation functionality between all plugins
- */
-export default class skyquakeNav extends React.Component {
- constructor(props) {
- super(props);
- this.state = {};
- this.state.validateErrorEvent = 0;
- this.state.validateErrorMsg = '';
- }
- validateError = (msg) => {
- this.setState({
- validateErrorEvent: true,
- validateErrorMsg: msg
- });
- }
- validateReset = () => {
- this.setState({
- validateErrorEvent: false
- });
- }
- returnCrouton = () => {
- return <Crouton
- id={Date.now()}
- message={this.state.validateErrorMsg}
- type={"error"}
- hidden={!(this.state.validateErrorEvent && this.state.validateErrorMsg)}
- onDismiss={this.validateReset}
- />;
- }
- render() {
- let html;
- html = (
- <div>
- {this.returnCrouton()}
- <nav className="skyquakeNav">
- {buildNav.call(this, this.props.nav, this.props.currentPlugin)}
- </nav>
-
- </div>
- )
- return html;
- }
-}
-skyquakeNav.defaultProps = {
- nav: {}
-}
-/**
- * Returns a React Component
- * @param {object} link Information about the nav link
- * @param {string} link.route Hash route that the SPA should resolve
- * @param {string} link.name Link name to be displayed
- * @param {number} index index of current array item
- * @return {object} component A React LI Component
- */
-//This should be extended to also make use of internal/external links and determine if the link should refer to an outside plugin or itself.
-export function buildNavListItem (k, link, index) {
- let html = false;
- if (link.type == 'external') {
- this.hasSubNav[k] = true;
- html = (
- <li key={index}>
- {returnLinkItem(link)}
- </li>
- );
- }
- return html;
-}
-
-/**
- * Builds a link to a React Router route or a new plugin route.
- * @param {object} link Routing information from nav object.
- * @return {object} component returns a react component that links to a new route.
- */
-export function returnLinkItem(link) {
- let ref;
- let route = link.route;
- if(link.isExternal) {
- ref = (
- <a href={route}>{link.label}</a>
- )
- } else {
- if(link.path && link.path.replace(' ', '') != '') {
- route = link.path;
- }
- if(link.query) {
- let query = {};
- query[link.query] = '';
- route = {
- pathname: route,
- query: query
- }
- }
- ref = (
- <Link to={route}>
- {link.label}
- </Link>
- )
- }
- return ref;
-}
-
-/**
- * Constructs nav for each plugin, along with available subnavs
- * @param {array} nav List returned from /nav endpoint.
- * @return {array} List of constructed nav element for each plugin
- */
-export function buildNav(nav, currentPlugin) {
- let navList = [];
- let navListHTML = [];
- let secondaryNav = [];
- let self = this;
- self.hasSubNav = {};
- let secondaryNavHTML = (
- <div className="secondaryNav" key="secondaryNav">
- {secondaryNav}
- <LogoutAppMenuItem />
- </div>
- )
- for (let k in nav) {
- if (nav.hasOwnProperty(k)) {
- self.hasSubNav[k] = false;
- let header = null;
- let navClass = "app";
- let routes = nav[k].routes;
- let navItem = {};
- //Primary plugin title and link to dashboard.
- let route;
- let NavList;
- if (API_SERVER) {
- route = routes[0].isExternal ? '/' + k + '/index.html?api_server=' + API_SERVER + '' + '&upload_server=' + UPLOAD_SERVER + '' : '';
- } else {
- route = routes[0].isExternal ? '/' + k + '/' : '';
- }
- let dashboardLink = returnLinkItem({
- isExternal: routes[0].isExternal,
- pluginName: nav[k].pluginName,
- label: nav[k].label || k,
- route: route
- });
- if (nav[k].pluginName == currentPlugin) {
- navClass += " active";
- }
- NavList = nav[k].routes.map(buildNavListItem.bind(self, k));
- navItem.priority = nav[k].priority;
- navItem.order = nav[k].order;
- navItem.html = (
- <div key={k} className={navClass}>
- <h2>{dashboardLink} {self.hasSubNav[k] ? <span className="oi" data-glyph="caret-bottom"></span> : ''}</h2>
- <ul className="menu">
- {
- NavList
- }
- </ul>
- </div>
- );
- navList.push(navItem)
- }
- }
- //Sorts nav items by order and returns only the markup
- navListHTML = navList.sort((a,b) => a.order - b.order).map(function(n) {
- if((n.priority < 2)){
- return n.html;
- } else {
- secondaryNav.push(n.html);
- }
- });
- navListHTML.push(secondaryNavHTML);
- return navListHTML;
-}
diff --git a/skyquake/framework/widgets/skyquake_container/skyquakeRouter.jsx b/skyquake/framework/widgets/skyquake_container/skyquakeRouter.jsx
index fc3231d..7d8daa5 100644
--- a/skyquake/framework/widgets/skyquake_container/skyquakeRouter.jsx
+++ b/skyquake/framework/widgets/skyquake_container/skyquakeRouter.jsx
@@ -22,10 +22,24 @@
from 'react-router';
import SkyquakeContainer from 'widgets/skyquake_container/skyquakeContainer.jsx';
+/**
+ * This is the Skyquake App wrapper that all plugins use to be a Skyquake plugin. This
+ * is not a react component although it does return a react component that will be the
+ * app.
+ * This function will also set the title into the <head>
+ *
+ * @export
+ * @param {any} config
+ * @param {any} context
+ * @returns a react component to be rendered manually.
+ */
export default function(config, context) {
let routes = [];
let index = null;
let components = null;
+
+ document.title = config.name || "OpenMANO";
+
if (config && config.routes) {
routes = buildRoutes(config.routes)
function buildRoutes(routes) {
@@ -83,7 +97,6 @@
},
childRoutes: routes
}
-
return((
<Router history={hashHistory} routes={rootRoute}>
</Router>
diff --git a/skyquake/framework/widgets/skyquake_nav/skyquakeNav.jsx b/skyquake/framework/widgets/skyquake_nav/skyquakeNav.jsx
new file mode 100644
index 0000000..7986d5e
--- /dev/null
+++ b/skyquake/framework/widgets/skyquake_nav/skyquakeNav.jsx
@@ -0,0 +1,377 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+import React from 'react';
+import { Link } from 'react-router';
+import Utils from 'utils/utils.js';
+import Crouton from 'react-crouton';
+import 'style/common.scss';
+
+import './skyquakeNav.scss';
+import SelectOption from '../form_controls/selectOption.jsx';
+import { FormSection } from '../form_controls/formControls.jsx';
+import { isRBACValid, SkyquakeRBAC } from 'widgets/skyquake_rbac/skyquakeRBAC.jsx';
+
+//Temporary, until api server is on same port as webserver
+import rw from 'utils/rw.js';
+
+var API_SERVER = rw.getSearchParams(window.location).api_server;
+var DOWNLOAD_SERVER = rw.getSearchParams(window.location).dev_download_server;
+
+//
+// Internal classes/functions
+//
+
+class SelectProject extends React.Component {
+ constructor(props) {
+ super(props);
+ }
+ selectProject(e) {
+ let value = JSON.parse(e.currentTarget.value);
+ // console.log('selected project', value)
+ }
+ render() {
+ let props = this.props;
+ let hasProjects = props.projects;
+ let userAssignedProjects = hasProjects && (props.projects.length > 0)
+ return (
+ <div className="app">
+ <h2>
+ <a style={{textTransform:'none'}}>
+ {
+ hasProjects ?
+ (userAssignedProjects ? 'PROJECT: ' + props.currentProject : 'No Projects Assigned')
+ : 'Projects Loading...'
+ }
+ </a>
+ {
+ userAssignedProjects ? <span className="oi" data-glyph="caret-bottom"></span> : null
+ }
+ </h2>
+ {
+ userAssignedProjects ?
+ <ul className="project menu">
+ {
+ props.projects.map(function (p, k) {
+ return <li key={k} onClick={props.onSelectProject.bind(null, p.name)}><a>{p.name}</a></li>
+ })
+ }
+ </ul>
+ : null
+ }
+ </div>
+ )
+ }
+}
+
+/*
+
+ <SelectOption
+ options={projects}
+ value={currentValue}
+ defaultValue={currentValue}
+ onChange={props.onSelectProject}
+ className="projectSelect" />
+
+ */
+
+
+class UserNav extends React.Component {
+ constructor(props) {
+ super(props);
+ }
+ handleLogout() {
+ Utils.clearAuthentication();
+ }
+ selectProject(e) {
+ let value = JSON.parse(e.currentTarget.value)
+ // console.log('selected project', value)
+ }
+ render() {
+ let props = this.props;
+ let userProfileLink = null;
+ this.props.nav['user_management'] && this.props.nav['user_management'].routes.map((r) => {
+ if (r.unique) {
+ userProfileLink = r;
+ }
+ })
+ return !userProfileLink ? null : (
+ <div className="app">
+ <h2 className="username">
+ USERNAME: {returnLinkItem(userProfileLink, props.currentUser)}
+ <span className="oi" data-glyph="caret-bottom"></span>
+ </h2>
+ <ul className="menu">
+ <li>
+ {returnLinkItem(userProfileLink, "My Profile")}
+ </li>
+ <li>
+ <a onClick={this.handleLogout}>
+ Logout
+ </a>
+ </li>
+ </ul>
+ </div>
+ )
+ }
+}
+
+UserNav.defaultProps = {
+ projects: [
+
+ ]
+}
+
+//
+// Exported classes and functions
+//
+
+//
+/**
+ * Skyquake Nav Component. Provides navigation functionality between all plugins
+ */
+export default class skyquakeNav extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {};
+ this.state.validateErrorEvent = 0;
+ this.state.validateErrorMsg = '';
+ }
+ componentDidMount() {
+ this.props.store.openProjectSocket();
+ }
+ validateError = (msg) => {
+ this.setState({
+ validateErrorEvent: true,
+ validateErrorMsg: msg
+ });
+ }
+ validateReset = () => {
+ this.setState({
+ validateErrorEvent: false
+ });
+ }
+ returnCrouton = () => {
+ return <Crouton
+ id={Date.now()}
+ message={this.state.validateErrorMsg}
+ type={"error"}
+ hidden={!(this.state.validateErrorEvent && this.state.validateErrorMsg)}
+ onDismiss={this.validateReset}
+ />;
+ }
+ render() {
+ let html;
+ html = (
+ <div>
+ {this.returnCrouton()}
+ <nav className="skyquakeNav">
+ {buildNav.call(this, this.props.nav, this.props.currentPlugin, this.props)}
+ </nav>
+
+ </div>
+ )
+ return html;
+ }
+}
+skyquakeNav.defaultProps = {
+ nav: {}
+}
+skyquakeNav.contextTypes = {
+ userProfile: React.PropTypes.object
+};
+/**
+ * Returns a React Component
+ * @param {object} link Information about the nav link
+ * @param {string} link.route Hash route that the SPA should resolve
+ * @param {string} link.name Link name to be displayed
+ * @param {number} index index of current array item
+ * @return {object} component A React LI Component
+ */
+//This should be extended to also make use of internal/external links and determine if the link should refer to an outside plugin or itself.
+export function buildNavListItem(k, link, index) {
+ let html = false;
+ if (link.type == 'external') {
+ this.hasSubNav[k] = true;
+ html = (
+ <li key={index}>
+ {returnLinkItem(link)}
+ </li>
+ );
+ }
+ return html;
+}
+
+/**
+ * Builds a link to a React Router route or a new plugin route.
+ * @param {object} link Routing information from nav object.
+ * @return {object} component returns a react component that links to a new route.
+ */
+export function returnLinkItem(link, label) {
+ let ref;
+ let route = link.route;
+ if (link.isExternal) {
+ ref = (
+ <a href={route}>{label || link.label}</a>
+ )
+ } else {
+ if (link.path && link.path.replace(' ', '') != '') {
+ route = link.path;
+ }
+ if (link.query) {
+ let query = {};
+ query[link.query] = '';
+ route = {
+ pathname: route,
+ query: query
+ }
+ }
+ ref = (
+ <Link to={route}>
+ {label || link.label}
+ </Link>
+ )
+ }
+ return ref;
+}
+
+
+
+
+/**
+ * Constructs nav for each plugin, along with available subnavs
+ * @param {array} nav List returned from /nav endpoint.
+ * @return {array} List of constructed nav element for each plugin
+ */
+export function buildNav(navData, currentPlugin, props) {
+ let navList = [];
+ let navListHTML = [];
+ let secondaryNav = [];
+ let adminNav = [];
+ //For monitoring when admin panel is active
+ let adminNavList = [];
+ let self = this;
+ const User = this.context.userProfile;
+ //The way the nav is sorting needs to be refactored.
+ let navArray = navData && Object.keys(navData).sort((a, b) => navData[a].order - navData[b].order)
+ self.hasSubNav = {};
+ for (let i = 0; i < navArray.length; i++) {
+ let k = navArray[i];
+ if (navData.hasOwnProperty(k)) {
+ self.hasSubNav[k] = false;
+ let header = null;
+ let navClass = "app";
+ let routes = navData[k].routes;
+ let navItem = {};
+ //Primary plugin title and link to dashboard.
+ let route;
+ let NavList;
+ if (API_SERVER) {
+ route = routes[0].isExternal ?
+ '/' + k + '/index.html?api_server=' + API_SERVER + '' + (DOWNLOAD_SERVER ? '&dev_download_server=' + DOWNLOAD_SERVER : '')
+ : '';
+ } else {
+ route = routes[0].isExternal ? '/' + k + '/' : '';
+ }
+ if(navData[k].route) {
+ route = route + navData[k].route;
+ }
+ let dashboardLink = returnLinkItem({
+ isExternal: routes[0].isExternal,
+ pluginName: navData[k].pluginName,
+ label: navData[k].label || k,
+ route: route
+ });
+ let shouldAllow = navData[k].allow || ['*'];
+ if (navData[k].pluginName == currentPlugin) {
+ navClass += " active";
+ }
+ NavList = navData[k].routes.filter((r) => {
+ const User = self.context.userProfile;
+ const shouldAllow = r.allow || ['*'];
+ return isRBACValid(User, shouldAllow);
+ }).map(buildNavListItem.bind(self, k));
+ navItem.priority = navData[k].priority;
+ navItem.order = navData[k].order;
+ if (navData[k].admin_link) {
+ if (isRBACValid(User, shouldAllow)) {
+ adminNavList.push(navData[k].pluginName);
+ adminNav.push((
+ <li key={navData[k].pluginName}>
+ {dashboardLink}
+ </li>
+ ))
+ }
+ } else {
+ if (isRBACValid(User, shouldAllow)) {
+ navItem.html = (
+ <div key={k} className={navClass}>
+ <h2>{dashboardLink} {self.hasSubNav[k] ? <span className="oi" data-glyph="caret-bottom"></span> : ''}</h2>
+ <ul className="menu">
+ {NavList}
+ </ul>
+ </div>
+ );
+ }
+ navList.push(navItem)
+ }
+
+ }
+ }
+
+ //Sorts nav items by order and returns only the markup
+ navListHTML = navList.map(function (n) {
+ if ((n.priority < 2)) {
+ return n.html;
+ } else {
+ secondaryNav.push(n.html);
+ }
+ });
+ if (adminNav.length) {
+ navListHTML.push(
+ <div key="Adminstration" className={"app " + (adminNavList.indexOf(currentPlugin) > -1 ? 'active' : '')}>
+ <h2>
+ <a>
+ ADMINISTRATION
+ </a>
+ <span className="oi" data-glyph="caret-bottom"></span>
+ </h2>
+ <ul className="menu">
+ {
+ adminNav
+ }
+ </ul>
+ </div>
+ );
+ }
+ let secondaryNavHTML = (
+ <div className="secondaryNav" key="secondaryNav">
+ {secondaryNav}
+ <SelectProject
+ onSelectProject={props.store.selectActiveProject}
+ projects={props.projects}
+ currentProject={props.currentProject} />
+ <UserNav
+ currentUser={props.currentUser}
+ nav={navData} />
+ </div>
+ )
+ // console.log("app admin " + (adminNavList.indexOf(currentPlugin) > -1 ? 'active' : ''))
+ navListHTML.push(secondaryNavHTML);
+ return navListHTML;
+}
diff --git a/skyquake/framework/widgets/skyquake_nav/skyquakeNav.scss b/skyquake/framework/widgets/skyquake_nav/skyquakeNav.scss
new file mode 100644
index 0000000..8a312ff
--- /dev/null
+++ b/skyquake/framework/widgets/skyquake_nav/skyquakeNav.scss
@@ -0,0 +1,127 @@
+@import '../../style/_colors.scss';
+.active {
+ background-color: $brand-blue!important;
+ border-color: $brand-blue!important;
+ color: #fff!important
+ }
+ .skyquakeNav {
+ display: -ms-flexbox;
+ display: -webkit-box;
+ display: flex;
+ color:white;
+ background:black;
+ position:relative;
+ z-index: 10;
+ font-size:0.75rem;
+ padding-right:1rem;
+ .secondaryNav {
+ -ms-flex: 1 1 auto;
+ -webkit-box-flex: 1;
+ flex: 1 1 auto;
+ display: -ms-flexbox;
+ display: -webkit-box;
+ display: flex;
+ -ms-flex-pack: end;
+ -webkit-box-pack: end;
+ justify-content: flex-end;
+
+ .username a{
+ text-transform: none;
+ }
+ }
+ .app {
+ display: -ms-flexbox;
+ display: block;
+ position:relative;
+ margin: auto 0.5rem;
+ h2 {
+ font-size:0.75rem;
+ border-right: 1px solid black;
+ display: -ms-flexbox;
+ display: -webkit-box;
+ display: flex;
+ -ms-flex-pack: start;
+ -ms-flex-pack: start;
+ -webkit-box-pack: start;
+ justify-content: flex-start;
+ -ms-flex-align: center;
+ -webkit-box-align: center;
+ align-items: center;
+ .oi {
+ padding-right: 0.5rem;
+ }
+ }
+ .menu {
+ position:absolute;
+ display:none;
+ z-index:2;
+ width: 100%;
+ li {
+ text-align:left;
+ }
+ }
+ &:first-child{
+ h2 {
+ border-left: 1px solid black;
+ }
+ }
+ &:hover {
+ a {
+ color:$brand-blue-light;
+ cursor:pointer;
+ }
+ .menu {
+ display:block;
+ background:black;
+ a {
+ color:white;
+ }
+ li:hover {
+ a {
+ color:$brand-blue-light;
+ }
+ }
+ }
+ }
+ &.active {
+ color:white;
+ background:black;
+ a {
+ color:white;
+ }
+ }
+ }
+ a{
+ display:block;
+ padding:0.5rem 1rem;
+ text-decoration:none;
+ text-transform:uppercase;
+ text-align:left;
+ color:white;
+ }
+ &:before {
+ content: '';
+ min-width: 5.5rem;
+ margin: 0.125rem 1rem;
+ /*background: url('../../style/img/svg/riftio_logo_white.svg') no-repeat center center;*/
+ background: url('../../style/img/svg/osm-logo_color_rgb_white_text.svg') no-repeat center center;
+ background-size: contain;
+ }
+ .userSection {
+ display:-ms-flexbox;
+ display:-webkit-box;
+ display:flex;
+ -ms-flex-align:center;
+ -webkit-box-align:center;
+ align-items:center;
+ padding-left: 1rem;
+ text-transform:uppercase;
+ text-align: left;
+ .projectSelect {
+ padding: 0 0.5rem;
+ font-size: 1rem;
+ /* min-width: 75%;*/
+ height: 25px;
+ }
+ }
+ }
diff --git a/skyquake/framework/widgets/skyquake_notification/netConfErrors.js b/skyquake/framework/widgets/skyquake_notification/netConfErrors.js
new file mode 100644
index 0000000..cde7b5d
--- /dev/null
+++ b/skyquake/framework/widgets/skyquake_notification/netConfErrors.js
@@ -0,0 +1,58 @@
+const NETCONF_ERRORS = {
+ 'in-use' : {
+ description: 'The request requires a resource that already is in use.'
+ },
+ 'invalid-value' : {
+ description: 'The request specifies an unacceptable value for one or more parameters.'
+ },
+ 'too-big' : {
+ description: 'The request or response (that would be generated) is too large for the implementation to handle.'
+ },
+ 'missing-attribute' : {
+ description: 'An expected attribute is missing.'
+ },
+ 'bad-attribute' : {
+ description: 'An attribute value is not correct; e.g., wrong type, out of range, pattern mismatch.'
+ },
+ 'unknown-attribute' : {
+ description: 'An unexpected attribute is present.'
+ },
+ 'missing-element' : {
+ description: 'An expected element is missing.'
+ },
+ 'bad-element' : {
+ description: 'An element value is not correct; e.g., wrong type, out of range, pattern mismatch.'
+ },
+ 'unknown-element' : {
+ description: 'An unexpected element is present.'
+ },
+ 'unknown-namespace' : {
+ description: 'An unexpected namespace is present.'
+ },
+ 'access-denied' : {
+ description: 'Access to the requested protocol operation or data model is denied because authorization failed.'
+ },
+ 'lock-denied' : {
+ description: 'Access to the requested lock is denied because the lock is currently held by another entity.'
+ },
+ 'resource-denied' : {
+ description: 'Request could not be completed because of insufficient resources.'
+ },
+ 'rollback-failed' : {
+ description: 'Request to roll back some configuration change (via rollback-on-error or <discard-changes> operations) was not completed for some reason.'
+ },
+ 'data-exists' : {
+ description: 'Request could not be completed because the relevant data model content already exists. For example, a "create" operation was attempted on data that already exists.'
+ },
+ 'data-missing' : {
+ description: 'Request could not be completed because the relevant data model content does not exist. For example, a "delete" operation was attempted on data that does not exist.'
+ },
+ 'operation-not-supported' : {
+ description: 'Request could not be completed because the requested operation is not supported by this implementation.'
+ },
+ 'operation-failed' : {
+ description: 'Request could not be completed because the requested operation failed for some reason not covered by any other error condition.'
+ }
+}
+
+export default NETCONF_ERRORS;
diff --git a/skyquake/framework/widgets/skyquake_notification/skyquakeNotification.jsx b/skyquake/framework/widgets/skyquake_notification/skyquakeNotification.jsx
new file mode 100644
index 0000000..c8ce157
--- /dev/null
+++ b/skyquake/framework/widgets/skyquake_notification/skyquakeNotification.jsx
@@ -0,0 +1,89 @@
+import React from 'react';
+import Crouton from 'react-crouton';
+import NETCONF_ERRORS from './netConfErrors.js';
+
+class SkyquakeNotification extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {};
+ this.state.displayNotification = props.visible;
+ this.state.notificationMessage = '';
+ this.state.notificationType = 'error';
+ }
+ componentWillReceiveProps(props) {
+ if(props.visible) {
+ this.processMessage(props.data);
+ } else {
+ this.setState({displayNotification: props.visible});
+ }
+ }
+ buildNetconfError(data) {
+ let error = data;
+ try {
+ let info = JSON.parse(data);
+ let rpcError = info.body || info.errorMessage.body || info.errorMessage.error;
+ if (rpcError && typeof rpcError === 'string') {
+ const index = rpcError.indexOf('{');
+ if (index >= 0) {
+ rpcError = JSON.parse(rpcError.substr(index));
+ } else {
+ return rpcError;
+ }
+ }
+ if (!rpcError) {
+ return error;
+ }
+ info = rpcError["rpc-reply"]["rpc-error"];
+ let errorTag = info['error-tag']
+ error = `
+ ${NETCONF_ERRORS[errorTag] && NETCONF_ERRORS[errorTag].description || 'Unknown NETCONF Error'}
+ PATH: ${info['error-path']}
+ INFO: ${JSON.stringify(info['error-info'])}
+ `
+ } catch (e) {
+ console.log('Unexpected string sent to buildNetconfError: ', e);
+ }
+ return error;
+ }
+ processMessage(data) {
+ let state = {
+ displayNotification: true,
+ notificationMessage: data,
+ notificationType: 'error',
+ displayScreenLoader: false
+ }
+ if(typeof(data) == 'string') {
+ //netconf errors will be json strings
+ state.notificationMessage = this.buildNetconfError(data);
+ } else {
+ let message = data.msg || '';
+ if(data.type) {
+ state.notificationType = data.type;
+ }
+ if(data.rpcError){
+ message += " " + this.buildNetconfError(data.rpcError);
+ }
+ state.notificationMessage = message;
+ }
+ console.log('NOTIFICATION: ', state.notificationMessage)
+ this.setState(state);
+ }
+ render() {
+ const {displayNotification, notificationMessage, notificationType, ...state} = this.state;
+ return (
+ <Crouton
+ id={Date.now()}
+ message={notificationMessage}
+ type={notificationType}
+ hidden={!(displayNotification && notificationMessage)}
+ onDismiss={this.props.onDismiss}
+ timeout={10000}
+ />
+ )
+ }
+}
+SkyquakeNotification.defaultProps = {
+ data: {},
+ onDismiss: function(){}
+}
+export default SkyquakeNotification;
diff --git a/skyquake/framework/widgets/skyquake_rbac/skyquakeRBAC.jsx b/skyquake/framework/widgets/skyquake_rbac/skyquakeRBAC.jsx
new file mode 100644
index 0000000..9097b4e
--- /dev/null
+++ b/skyquake/framework/widgets/skyquake_rbac/skyquakeRBAC.jsx
@@ -0,0 +1,119 @@
+/*
+ *
+ * Copyright 2016 RIFT.IO Inc
+ *
+ * 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.
+ *
+ */
+
+
+import React from 'react';
+import ROLES from 'utils/roleConstants.js';
+const PLATFORM = ROLES.PLATFORM;
+
+export function isRBACValid(User, allow, Project){
+ const UserData = User && User.data;
+ if(UserData) {
+ const PlatformRole = UserData.platform.role;
+ const isPlatformSuper = PlatformRole[PLATFORM.SUPER];
+ const isPlatformAdmin = PlatformRole[PLATFORM.ADMIN];
+ const isPlatformOper = PlatformRole[PLATFORM.OPER];
+ const hasRoleAccess = checkForRoleAccess(UserData.project[Project || User.projectId], PlatformRole, allow)//false//(this.props.roles.indexOf(userProfile.projectRole) > -1)
+ if (isPlatformSuper) {
+ return true;
+ } else {
+ if (hasRoleAccess) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+export default class SkyquakeRBAC extends React.Component {
+ constructor(props, context) {
+ super(props);
+ }
+ render() {
+ const User = this.context.userProfile;
+ const UserData = User.data;
+ const Project = this.props.project;
+ let HTML = null;
+ // If user object has platform property then it has been populated by the back end.
+ if(isRBACValid(User, this.props.allow, Project)) {
+ HTML = this.props.children;
+ }
+ return (<div className={this.props.className} style={this.props.style}>{HTML}</div>)
+ }
+}
+SkyquakeRBAC.defaultProps = {
+ allow: [],
+ project: false
+}
+SkyquakeRBAC.contextTypes = {
+ userProfile: React.PropTypes.object
+}
+
+function checkForRoleAccess(project, PlatformRole, allow) {
+ if (allow.indexOf('*') > -1) return true;
+ for (let i = 0; i<allow.length; i++) {
+ if((project && project.role[allow[i]])|| PlatformRole[allow[i]]) {
+ return true
+ }
+ }
+ return false;
+ }
+
+
+
+// export default function(Component) {
+// class SkyquakeRBAC extends React.Component {
+// constructor(props, context) {
+// super(props);
+// }
+// render(props) {
+// console.log(this.context.userProfile)
+// const User = this.context.userProfile.data;
+// // If user object has platform property then it has been populated by the back end.
+// if(User) {
+// const PlatformRole = User.platform.role;
+// const HTML = <Component {...this.props} router={this.router} actions={this.actions} flux={this.context.flux}/>;
+// const isPlatformSuper = PlatformRole[PLATFORM.SUPER];
+// const isPlatformAdmin = PlatformRole[PLATFORM.ADMIN];
+// const isPlatformOper = PlatformRole[PLATFORM.OPER];
+// const hasRoleAccess = false//(this.props.roles.indexOf(userProfile.projectRole) > -1)
+// if (isPlatformSuper || isPlatformOper || isPlatformAdmin) {
+// return HTML
+// } else {
+// if (hasRoleAccess) {
+// return HTML
+// } else {
+// return null;
+// }
+// }
+// }
+// else {
+// return null;
+
+// }
+// }
+// }
+// SkyquakeRBAC.defaultProps = {
+
+// }
+// SkyquakeRBAC.contextTypes = {
+// userProfile: React.PropTypes.object,
+// allowedRoles: []
+// };
+// return SkyquakeRBAC;
+// }