Added RBAC to logging page. Removed /check-auth route references.
[osm/UI.git] / skyquake / framework / utils / utils.js
1 /*
2 *
3 * Copyright 2016 RIFT.IO Inc
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18 //Login needs to be refactored. Too many cross dependencies
19 var AuthActions = require('../widgets/login/loginAuthActions.js');
20 var $ = require('jquery');
21 import rw from './rw.js';
22 var API_SERVER = rw.getSearchParams(window.location).api_server;
23 let NODE_PORT = rw.getSearchParams(window.location).api_port || ((window.location.protocol == 'https:') ? 8443 : 8000);
24 var SockJS = require('sockjs-client');
25
26 var Utils = {};
27
28 Utils.DescriptorModelMeta = null;
29 // Utils.DescriptorModelMeta = require('./../../plugins/composer/src/src/libraries/model/DescriptorModelMeta.json');
30
31 var INACTIVITY_TIMEOUT = 600000;
32
33 Utils.getInactivityTimeout = function() {
34 return new Promise(function(resolve, reject) {
35 $.ajax({
36 url: '/inactivity-timeout',
37 type: 'GET',
38 success: function(data) {
39 resolve(data);
40 },
41 error: function(error) {
42 console.log("There was an error getting the inactivity-timeout: ", error);
43 reject(error);
44 }
45 }).fail(function(xhr) {
46 console.log('There was an xhr error getting the inactivity-timeout', xhr);
47 reject(xhr);
48 });
49 });
50 };
51
52 Utils.isMultiplexerLoaded = function() {
53 if (window.multiplexer) {
54 return true;
55 }
56 return false;
57 };
58
59 Utils.setupMultiplexClient = function() {
60 var sockjs_url = '/multiplex';
61
62 var sockjs = new SockJS(sockjs_url);
63
64 var loadChecker = function() {
65 try {
66 window.multiplexer = new WebSocketMultiplex(sockjs);
67 console.log('WebSocketMultiplex loaded');
68 } catch (e) {
69 // caught an error, retry in someTime
70 console.log('WebSocketMultiplex not loaded yet. will try again in 1 second:', e);
71 setTimeout(function() {
72 loadChecker();
73 }, 1000);
74 }
75 }
76 loadChecker();
77 };
78
79 Utils.checkAndResolveSocketRequest = function(data, resolve, reject) {
80 const checker = () => {
81 if (!Utils.isMultiplexerLoaded()) {
82 setTimeout(() => {
83 checker();
84 }, 500);
85 } else {
86 resolve(data.id);
87 }
88 };
89
90 checker();
91 };
92
93 Utils.bootstrapApplication = function() {
94 var self = this;
95 return new Promise(function(resolve, reject) {
96 Promise.all([self.getInactivityTimeout()]).then(function(results) {
97 INACTIVITY_TIMEOUT = results[0]['inactivity-timeout'];
98 resolve();
99 }, function(error) {
100 console.log("Error bootstrapping application ", error);
101 reject();
102 });
103 });
104 };
105
106 Utils.getDescriptorModelMeta = function() {
107 return new Promise(function(resolve, reject) {
108 if (!Utils.DescriptorModelMeta) {
109 $.ajax({
110 url: '/descriptor-model-meta?api_server=' + API_SERVER,
111 type: 'GET',
112 beforeSend: Utils.addAuthorizationStub,
113 success: function(data) {
114 Utils.DescriptorModelMeta = data;
115 Utils.DescriptorModelMetaLoaded = true;
116 resolve(data);
117 },
118 error: function(error) {
119 console.log("There was an error getting the schema: ", error);
120 reject(error);
121 }
122 }).fail(function(xhr) {
123 console.log("There was an error getting the schema: ", xhr);
124 Utils.checkAuthentication(xhr.status);
125 });
126 } else {
127 resolve(Utils.DescriptorModelMeta);
128 }
129 })
130 }
131
132 Utils.addAuthorizationStub = function(xhr) {
133 // NO-OP now that we are dealing with it on the server
134 // var Auth = window.sessionStorage.getItem("auth");
135 // xhr.setRequestHeader('Authorization', 'Basic ' + Auth);
136 };
137
138 Utils.getByteDataWithUnitPrefix = function(number, precision) {
139 var toPrecision = precision || 3;
140 if (number < Math.pow(10, 3)) {
141 return [number, 'B'];
142 } else if (number < Math.pow(10, 6)) {
143 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KB'];
144 } else if (number < Math.pow(10, 9)) {
145 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MB'];
146 } else if (number < Math.pow(10, 12)) {
147 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GB'];
148 } else if (number < Math.pow(10, 15)) {
149 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TB'];
150 } else if (number < Math.pow(10, 18)) {
151 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PB'];
152 } else if (number < Math.pow(10, 21)) {
153 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EB'];
154 } else if (number < Math.pow(10, 24)) {
155 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZB'];
156 } else if (number < Math.pow(10, 27)) {
157 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZB'];
158 } else {
159 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YB'];
160 }
161 }
162
163 Utils.getPacketDataWithUnitPrefix = function(number, precision) {
164 var toPrecision = precision || 3;
165 if (number < Math.pow(10, 3)) {
166 return [number, 'P'];
167 } else if (number < Math.pow(10, 6)) {
168 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KP'];
169 } else if (number < Math.pow(10, 9)) {
170 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MP'];
171 } else if (number < Math.pow(10, 12)) {
172 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GP'];
173 } else if (number < Math.pow(10, 15)) {
174 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TP'];
175 } else if (number < Math.pow(10, 18)) {
176 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PP'];
177 } else if (number < Math.pow(10, 21)) {
178 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EP'];
179 } else if (number < Math.pow(10, 24)) {
180 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZP'];
181 } else if (number < Math.pow(10, 27)) {
182 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZP'];
183 } else {
184 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YP'];
185 }
186 }
187 Utils.loginHash = "#/login";
188
189 Utils.clearAuthentication = function(callback) {
190 var self = this;
191 window.sessionStorage.removeItem("auth");
192 AuthActions.notAuthenticated();
193 window.sessionStorage.setItem("locationRefHash", window.location.hash);
194 $.ajax({
195 url: '//' + window.location.hostname + ':' + window.location.port + '/session?api_server=' + API_SERVER,
196 type: 'DELETE',
197 success: function(data) {
198 console.log('User logged out');
199 },
200 error: function(data) {
201 console.log('Problem logging user out');
202 }
203 });
204
205
206 if (callback) {
207 callback();
208 } else {
209 window.location.replace(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/?api_server=' + API_SERVER);
210 }
211 }
212 Utils.isNotAuthenticated = function(windowLocation, callback) {
213 var self = this;
214 self.detectInactivity();
215 if (!window.sessionStorage.getItem("auth")) {
216 Utils.clearAuthentication();
217 }
218 }
219 Utils.isDetecting = false;
220 Utils.detectInactivity = function(callback, duration) {
221 var self = this;
222 if (!self.isDetecting) {
223 var cb = function() {
224 self.clearAuthentication();
225 if (callback) {
226 callback();
227 }
228 };
229 var isInactive;
230 var timeout = duration || INACTIVITY_TIMEOUT;
231 var setInactive = function() {
232 isInactive = setTimeout(cb, timeout);
233 };
234 var reset = function() {
235 clearTimeout(isInactive);
236 setInactive();
237 }
238 setInactive();
239 window.addEventListener('mousemove', reset);
240 window.addEventListener("keypress", reset);
241 self.isDetecting = true;
242 }
243 }
244 Utils.checkAuthentication = function(statusCode, cb) {
245 var self = this;
246 if (statusCode == 401) {
247 if (cb) {
248 cb();
249 }
250 window.sessionStorage.removeItem("auth")
251 self.isNotAuthenticated(window.location)
252 return true;
253 }
254 return false;
255 }
256
257 Utils.isAuthenticationCached = function() {
258 var self = this;
259 if (window.sessionStorage.getItem("auth")) {
260 return true;
261 }
262 return false;
263 }
264
265 Utils.getHostNameFromURL = function(url) {
266 var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([^?#]*)(\?[^#]*|)(#.*|)$/);
267 return match && match[3];
268 }
269
270 Utils.webSocketProtocol = function() {
271 if (this.wsProto) {
272 return this.wsProto;
273 } else {
274 if (window.location.protocol == 'http:') {
275 this.wsProto = 'ws:'
276 } else {
277 this.wsProto = 'wss:'
278 }
279 }
280 return this.wsProto;
281 }
282
283 Utils.arrayIntersperse = (arr, sep) => {
284 if (arr.length === 0) {
285 return [];
286 }
287
288 return arr.slice(1).reduce((xs, x, i) => {
289 return xs.concat([sep, x]);
290 }, [arr[0]]);
291 }
292
293 Utils.cleanImageDataURI = (imageString, type, id) => {
294 if (/\bbase64\b/g.test(imageString)) {
295 return imageString;
296 } else if (/<\?xml\b/g.test(imageString)) {
297 const imgStr = imageString.substring(imageString.indexOf('<?xml'));
298 return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(imgStr);
299 } else if (/\.(svg|png|gif|jpeg|jpg)$/.test(imageString)) {
300 return '/composer/assets/logos/' + type + '/' + id + '/' + imageString;
301 // return require('../images/logos/' + imageString);
302 }
303 if(type == 'nsd' || type == 'vnfd') {
304 return require('style/img/catalog-'+type+'-default.svg');
305 }
306 return require('style/img/catalog-default.svg');
307 }
308
309 module.exports = Utils;