Debian Codegraph @

lemonldap-ng-manager/site/htdocs/static/js/viewer.js

raw symbols SCIP
1 (function () {
2 'use strict';
3
4 /*
5 LemonLDAP::NG Viewer client
6
7 This is the main app file. Other are:
8 - struct.json and js/confTree.js that contains the full tree
9 - translate.json that contains the keywords translation
10
11 This file contains:
12 - the AngularJS controller
13 */
14 var llapp;
15 llapp = angular.module('llngViewer', ['ui.tree', 'ui.bootstrap', 'llApp', 'ngCookies']);
16
17 /*
18 Main AngularJS controller
19 */
20 llapp.controller('TreeCtrl', ['$scope', '$http', '$location', '$q', '$uibModal', '$translator', '$cookies', '$htmlParams', '$timeout', function ($scope, $http, $location, $q, $uibModal, $translator, $cookies, $htmlParams, $timeout) {
21 var _download, _stoggle, c, id, pathEvent, readError, setHelp;
22 $scope.links = window.links;
23 $scope.menu = $htmlParams.menu;
24 $scope.menulinks = window.menulinks;
25 $scope.staticPrefix = window.staticPrefix;
26 $scope.formPrefix = window.formPrefix;
27 $scope.availableLanguages = window.availableLanguages;
28 $scope.waiting = true;
29 $scope.showM = false;
30 $scope.showT = false;
31 $scope.form = 'homeViewer';
32 $scope.currentCfg = {};
33 $scope.clipboardAvailable = Boolean(navigator.clipboard);
34 $scope.viewPrefix = window.viewPrefix;
35 $scope.allowDiff = window.allowDiff;
36 $scope.message = {};
37 $scope.result = '';
38 // Import translations functions
39 $scope.translateTitle = function (node) {
40 return $translator.translateField(node, 'title');
41 };
42 $scope.translateP = $translator.translateP;
43 $scope.translate = $translator.translate;
44 // HELP DISPLAY
45 $scope.helpUrl = 'start.html#configuration';
46 $scope.setShowHelp = function (val) {
47 var d;
48 if (val == null) {
49 val = !$scope.showH;
50 }
51 $scope.showH = val;
52 d = new Date(Date.now());
53 d.setFullYear(d.getFullYear() + 1);
54 return $cookies.put('showhelp', val ? 'true' : 'false', {
55 "expires": d
56 });
57 };
58 $scope.showH = $cookies.get('showhelp') === 'false' ? false : true;
59 if ($scope.showH == null) {
60 $scope.setShowHelp(true);
61 }
62 // INTERCEPT AJAX ERRORS
63 readError = function (response) {
64 var e, j;
65 e = response.status;
66 j = response.statusLine;
67 $scope.waiting = false;
68 if (e === 403) {
69 $scope.message = {
70 title: 'forbidden',
71 message: '',
72 items: []
73 };
74 } else if (e === 401) {
75 console.debug('Authentication needed');
76 $scope.message = {
77 title: 'authenticationNeeded',
78 message: '__waitOrF5__',
79 items: []
80 };
81 } else if (e === 400) {
82 $scope.message = {
83 title: 'badRequest',
84 message: j,
85 items: []
86 };
87 } else if (e > 0) {
88 $scope.message = {
89 title: 'badRequest',
90 message: j,
91 items: []
92 };
93 } else {
94 $scope.message = {
95 title: 'networkProblem',
96 message: '',
97 items: []
98 };
99 }
100 return $scope.showModal('message.html');
101 };
102 // Modal launcher
103 $scope.showModal = function (tpl, init) {
104 var d, modalInstance;
105 modalInstance = $uibModal.open({
106 templateUrl: tpl,
107 controller: 'ModalInstanceCtrl',
108 size: 'lg',
109 resolve: {
110 elem: function () {
111 return function (s) {
112 return $scope[s];
113 };
114 },
115 set: function () {
116 return function (f, s) {
117 return $scope[f] = s;
118 };
119 },
120 init: function () {
121 return init;
122 }
123 }
124 });
125 d = $q.defer();
126 modalInstance.result.then(function (msgok) {
127 $scope.message = {
128 title: '',
129 message: '',
130 items: []
131 };
132 return d.resolve(msgok);
133 }, function (msgnok) {
134 $scope.message = {
135 title: '',
136 message: '',
137 items: []
138 };
139 return d.reject(msgnok);
140 });
141 return d.promise;
142 };
143 // FORM DISPLAY FUNCTIONS
144
145 // Function called when a menu item is selected. It launch function stored in
146 // "action" or "title"
147 $scope.menuClick = function (button) {
148 if (button.popup) {
149 window.open(button.popup);
150 } else {
151 if (!button.action) {
152 button.action = button.title;
153 }
154 switch (typeof button.action) {
155 case 'function':
156 button.action($scope.currentNode, $scope);
157 break;
158 case 'string':
159 $scope[button.action]();
160 break;
161 default:
162 console.warn('Unknown action type', typeof button.action);
163 }
164 }
165 return $scope.showM = false;
166 };
167 // Display main form
168 $scope.home = function () {
169 $scope.form = 'homeViewer';
170 return $scope.showM = false;
171 };
172 // Download raw conf
173 $scope.downloadConf = function () {
174 return window.open($scope.viewPrefix + $scope.currentCfg.cfgNum + '?full=1');
175 };
176 // NODES MANAGEMENT
177 id = 1;
178 $scope._findContainer = function () {
179 return $scope._findScopeContainer().$modelValue;
180 };
181 $scope._findScopeContainer = function () {
182 var cs;
183 cs = $scope.currentScope;
184 while (!cs.$modelValue.type.match(/Container$/)) {
185 cs = cs.$parentNodeScope;
186 }
187 return cs;
188 };
189 $scope._findScopeByKey = function (k) {
190 var cs;
191 cs = $scope.currentScope;
192 while (!(cs.$modelValue.title === k)) {
193 cs = cs.$parentNodeScope;
194 }
195 return cs;
196 };
197 $scope.down = function () {
198 var i, ind, l, len, n, p, ref, tmp;
199 id = $scope.currentNode.id;
200 p = $scope.currentScope.$parentNodeScope.$modelValue;
201 ind = p.nodes.length;
202 ref = p.nodes;
203 for (i = l = 0, len = ref.length; l < len; i = ++l) {
204 n = ref[i];
205 if (n.id === id) {
206 ind = i;
207 }
208 }
209 if (ind < p.nodes.length - 1) {
210 tmp = p.nodes[ind];
211 p.nodes[ind] = p.nodes[ind + 1];
212 p.nodes[ind + 1] = tmp;
213 }
214 return ind;
215 };
216 $scope.up = function () {
217 var i, ind, l, len, n, p, ref, tmp;
218 id = $scope.currentNode.id;
219 p = $scope.currentScope.$parentNodeScope.$modelValue;
220 ind = -1;
221 ref = p.nodes;
222 for (i = l = 0, len = ref.length; l < len; i = ++l) {
223 n = ref[i];
224 if (n.id === id) {
225 ind = i;
226 }
227 }
228 if (ind > 0) {
229 tmp = p.nodes[ind];
230 p.nodes[ind] = p.nodes[ind - 1];
231 p.nodes[ind - 1] = tmp;
232 }
233 return ind;
234 };
235 // test if value is in select
236 $scope.inSelect = function (value) {
237 var l, len, n, ref;
238 ref = $scope.currentNode.select;
239 for (l = 0, len = ref.length; l < len; l++) {
240 n = ref[l];
241 if (n.k === value) {
242 return true;
243 }
244 }
245 return false;
246 };
247 // This is for rule form: title = comment if defined, else title = re
248 $scope.changeRuleTitle = function (node) {
249 return node.title = node.comment.length > 0 ? node.comment : node.re;
250 };
251 // Node opening
252
253 // authParams mechanism: show used auth modules only (launched by stoggle)
254 $scope.filters = {};
255 $scope.execFilters = function (scope) {
256 var filter, func, ref;
257 scope = scope ? scope : $scope;
258 ref = $scope.filters;
259 for (filter in ref) {
260 func = ref[filter];
261 if ($scope.filters.hasOwnProperty(filter)) {
262 return window.filterFunctions[filter](scope, $q, func);
263 }
264 }
265 return false;
266 };
267 // To avoid binding all the tree, nodes are pushed in DOM only when opened
268 $scope.stoggle = function (scope) {
269 var node;
270 node = scope.$modelValue;
271 _stoggle(node);
272 return scope.toggle();
273 };
274 _stoggle = function (node) {
275 var a, l, len, len1, len2, m, n, o, ref, ref1, ref2;
276 ref = ['nodes', 'nodes_cond'];
277 for (l = 0, len = ref.length; l < len; l++) {
278 n = ref[l];
279 if (node[`_${n}`]) {
280 node[n] = [];
281 ref1 = node[`_${n}`];
282 for (m = 0, len1 = ref1.length; m < len1; m++) {
283 a = ref1[m];
284 node[n].push(a);
285 }
286 delete node[`_${n}`];
287 }
288 }
289 // Call execFilter for authParams
290 if (node._nodes_filter) {
291 if (node.nodes) {
292 ref2 = node.nodes;
293 for (o = 0, len2 = ref2.length; o < len2; o++) {
294 n = ref2[o];
295 n.onChange = $scope.execFilters;
296 }
297 }
298 $scope.filters[node._nodes_filter] = node;
299 return $scope.execFilters();
300 }
301 };
302 // Simple toggle management
303 $scope.toggle = function (scope) {
304 return scope.toggle();
305 };
306 // cnodes management: hash keys/values are loaded when parent node is opened
307 $scope.download = function (scope) {
308 var node;
309 node = scope.$modelValue;
310 return _download(node);
311 };
312 _download = function (node) {
313 var d, uri;
314 d = $q.defer();
315 d.notify('Trying to get datas');
316 $scope.waiting = true;
317 console.debug(`Trying to get key ${node.cnodes}`);
318 uri = encodeURI(node.cnodes);
319 $http.get(`${window.viewPrefix}${$scope.currentCfg.cfgNum}/${uri}`).then(function (response) {
320 var a, data, l, len;
321 data = response.data;
322 // Manage datas errors
323 if (!data) {
324 d.reject('Empty response from server');
325 } else if (data.error) {
326 if (data.error.match(/setDefault$/)) {
327 if (node['default']) {
328 node.nodes = node['default'].slice(0);
329 } else {
330 node.nodes = [];
331 }
332 delete node.cnodes;
333 d.resolve('Set data to default value');
334 } else {
335 d.reject(`Server return an error: ${data.error}`);
336 }
337 } else {
338 // Store datas
339 delete node.cnodes;
340 if (!node.type) {
341 node.type = 'keyTextContainer';
342 }
343 node.nodes = [];
344 // TODO: try/catch
345 for (l = 0, len = data.length; l < len; l++) {
346 a = data[l];
347 if (a.template) {
348 a._nodes = templates(a.template, a.title);
349 }
350 node.nodes.push(a);
351 }
352 d.resolve('OK');
353 }
354 return $scope.waiting = false;
355 }, function (response) {
356 readError(response);
357 return d.reject('');
358 });
359 return d.promise;
360 };
361 $scope.openCnode = function (scope) {
362 return $scope.download(scope).then(function () {
363 return scope.toggle();
364 });
365 };
366 $scope.copyPath = function () {
367 var text = $scope.breadCrumb.join(" ยป ");
368 navigator.clipboard.writeText(text).then(function () {
369 $scope.$apply(function () {
370 $scope.copySuccess = true;
371 $timeout(function () {
372 $scope.copySuccess = false;
373 }, 400);
374 });
375 });
376 };
377 setHelp = function (scope) {
378 while (!scope.$modelValue.help && scope.$parentNodeScope) {
379 scope = scope.$parentNodeScope;
380 }
381 return $scope.helpUrl = scope.$modelValue.help || 'start.html#configuration';
382 };
383 // Form management
384
385 // `currentNode` contains the last select node
386
387 // method `diplayForm()`:
388 // - set the `form` property to the name of the form to download
389 // (`text` by default or `home` for node without `type` property)
390 // - launch getKeys to set `node.data`
391 // - hide tree when in XS size
392
393 $scope.getTrPath = function (scope) {
394 var path = [];
395 var trpath = [];
396 var current = scope;
397 var safetycount = 0;
398 while (current && current.$modelValue && safetycount < 100) {
399 safetycount = safetycount + 1;
400 if (current.$modelValue.title && current.$modelValue.title != path[0]) {
401 trpath.unshift(scope.translate(current.$modelValue.title));
402 path.unshift(current.$modelValue.title);
403 }
404 current = current.$parent;
405 }
406 return trpath;
407 };
408 $scope.displayForm = function (scope) {
409 var f, l, len, n, node, ref;
410 node = scope.$modelValue;
411 if (node.cnodes) {
412 $scope.download(scope);
413 }
414 if (node._nodes) {
415 $scope.stoggle(scope);
416 }
417 $scope.currentNode = node;
418 $scope.currentScope = scope;
419 f = node.type ? node.type : 'text';
420 if (node.nodes || node._nodes || node.cnodes) {
421 $scope.form = f !== 'text' ? f : 'mini';
422 } else {
423 $scope.form = f;
424 // Get datas
425 $scope.getKey(node);
426 }
427 if (node.type && node.type === 'simpleInputContainer') {
428 ref = node.nodes;
429 for (l = 0, len = ref.length; l < len; l++) {
430 n = ref[l];
431 $scope.getKey(n);
432 }
433 }
434 $scope.showT = false;
435 $scope.breadCrumb = $scope.getTrPath(scope);
436 return setHelp(scope);
437 };
438 $scope.keyWritable = function (scope) {
439 var node;
440 node = scope.$modelValue;
441 // regexp-assemble of:
442 // authChoice
443 // cmbModule
444 // keyText
445 // menuApp
446 // menuCat
447 // rule
448 // samlAttribute
449 // samlIDPMetaDataNode
450 // samlSPMetaDataNode
451 // sfExtra
452 // virtualHost
453 if (node.type && node.type.match(/^(?:s(?:aml(?:(?:ID|S)PMetaDataNod|Attribut)e|fExtra)|(?:(?:cmbMod|r)ul|authChoic)e|(?:virtualHos|keyTex)t|menu(?:App|Cat))$/)) {
454 return true;
455 } else {
456 return false;
457 }
458 };
459 // method `getKey()`:
460 // - return a promise with the data:
461 // - from node when set
462 // - after downloading else
463
464 $scope.getKey = function (node) {
465 var d, i, l, len, n, ref, tmp, uri;
466 d = $q.defer();
467 if (!node.data) {
468 $scope.waiting = true;
469 if (node.get && typeof node.get === 'object') {
470 node.data = [];
471 tmp = [];
472 ref = node.get;
473 for (i = l = 0, len = ref.length; l < len; i = ++l) {
474 n = ref[i];
475 node.data[i] = {
476 title: n.split("/").pop(),
477 get: n,
478 id: n
479 };
480 tmp.push($scope.getKey(node.data[i]));
481 }
482 $q.all(tmp).then(function () {
483 return d.resolve(node.data);
484 }, function (response) {
485 d.reject(response.statusLine);
486 return $scope.waiting = false;
487 });
488 } else {
489 uri = '';
490 if (node.get) {
491 console.debug(`Trying to get key ${node.get}`);
492 uri = encodeURI(node.get);
493 } else {
494 console.debug(`Trying to get title ${node.title}`);
495 }
496 $http.get(`${window.viewPrefix}${$scope.currentCfg.cfgNum}/${node.get ? uri : node.title}`).then(function (response) {
497 var data;
498 // Set default value if response is null or if asked by server
499 data = response.data;
500 if ((data.value === null || data.error && data.error.match(/setDefault$/)) && node['default'] !== null) {
501 node.data = node['default'];
502 } else {
503 node.data = data.value;
504 }
505 if (node.data && node.data.toString().match(/_Hidden_$/)) {
506 node.type = 'text';
507 node.data = '######';
508 }
509 // Cast int as int (remember that booleans are int for Perl)
510 if (node.type && node.type.match(/^(bool|trool|boolOrExpr)$/)) {
511 if (typeof node.data === 'string' && node.data.match(/^(?:-1|0|1)$/)) {
512 node.data = parseInt(node.data, 10);
513 }
514 }
515 if (node.type && node.type.match(/^int$/)) {
516 node.data = parseInt(node.data, 10);
517 // Split SAML types
518 } else if (node.type && node.type.match(/^(saml(Service|Assertion)|blackWhiteList)$/) && !(typeof node.data === 'object')) {
519 node.data = node.data.split(';');
520 }
521 $scope.waiting = false;
522 return d.resolve(node.data);
523 }, function (response) {
524 readError(response);
525 return d.reject(response.status);
526 });
527 }
528 } else {
529 if (node.data.toString().match(/_Hidden_$/)) {
530 node.type = 'text';
531 node.data = '######';
532 }
533 d.resolve(node.data);
534 }
535 return d.promise;
536 };
537 // function `pathEvent(event, next; current)`:
538 // Called when $location.path() change, launch getCfg() with the new
539 // configuration number
540 pathEvent = function (event, next, current) {
541 var n;
542 n = next.match(new RegExp('#!?/view/(latest|[0-9]+)'));
543 if (n === null) {
544 return $location.path('/view/latest');
545 } else {
546 console.debug(`Trying to get cfg number ${n[1]}`);
547 return $scope.getCfg(n[1]);
548 }
549 };
550 $scope.$on('$locationChangeSuccess', pathEvent);
551 // function `getCfg(n)`:
552 // Download configuration metadatas
553 $scope.getCfg = function (n) {
554 if ($scope.currentCfg.cfgNum !== n) {
555 return $http.get(`${window.viewPrefix}${n}`).then(function (response) {
556 var d;
557 $scope.currentCfg = response.data;
558 d = new Date($scope.currentCfg.cfgDate * 1000);
559 $scope.currentCfg.date = d.toLocaleString();
560 console.debug(`Metadatas of cfg ${n} loaded`);
561 $location.path(`/view/${n}`);
562 return $scope.init();
563 }, function (response) {
564 return readError(response).then(function () {
565 $scope.currentCfg.cfgNum = 0;
566 return $scope.init();
567 });
568 });
569 } else {
570 return $scope.waiting = false;
571 }
572 };
573 // method `getLanguage(lang)`
574 // Launch init() after setting current language
575 $scope.getLanguage = function (lang) {
576 $scope.lang = lang;
577 // Force reload home
578 $scope.form = 'white';
579 $scope.init();
580 return $scope.showM = false;
581 };
582 // Initialization
583
584 // Load JSON files:
585 // - struct.json: the main tree
586 // - languages/<lang>.json: the chosen language datas
587 $scope.init = function () {
588 var tmp;
589 tmp = null;
590 $scope.waiting = true;
591 $scope.breadCrumb = null;
592 $scope.data = [];
593 $scope.confirmNeeded = false;
594 $scope.forceSave = false;
595 $q.all([$translator.init($scope.lang), $http.get(`${window.staticPrefix}struct.json`).then(function (response) {
596 tmp = response.data;
597 console.debug("Structure loaded");
598 })]).then(function () {
599 console.debug("Starting structure binding");
600 $scope.data = tmp;
601 tmp = null;
602 if ($scope.currentCfg.cfgNum !== 0) {
603 setScopeVars($scope);
604 } else {
605 $scope.message = {
606 title: 'emptyConf',
607 message: '__zeroConfExplanations__'
608 };
609 $scope.showModal('message.html');
610 }
611 $scope.form = 'homeViewer';
612 return $scope.waiting = false;
613 }, readError);
614 // Colorized link
615 $scope.activeModule = "viewer";
616 return $scope.myStyle = {
617 color: '#ffb84d'
618 };
619 };
620 c = $location.path().match(new RegExp('^/view/(latest|[0-9]+)'));
621 if (!c) {
622 console.debug("Redirecting to /view/latest");
623 return $location.path('/view/latest');
624 }
625 }]);
626
627 })();