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.keyTranslatable = function (scope) {
439 var node;
440 node = scope.$modelValue;
441 // Regexp::Assemble->new->add(qw(
442 // authChoice
443 // casAppMetaDataNode
444 // casSrvMetaDataNode
445 // cmbModule
446 // keyNode
447 // keyText
448 // menuApp
449 // menuCat
450 // rule
451 // oidcAttribute
452 // oidcOPMetaDataNode
453 // oidcRPMetaDataNode
454 // samlAttribute
455 // samlIDPMetaDataNode
456 // samlSPMetaDataNode
457 // sfExtra
458 // virtualHost
459 // ))->anchor_line->as_string
460 if (node.type && node.type.match(/^(?:(?:c(?:as(?:App|Srv)MetaDataNod|mbModul)|oidc(?:[OR]PMetaDataNod|Attribut)|authChoic|rul)e|s(?:aml(?:(?:ID|S)PMetaDataNod|Attribut)e|fExtra)|key(?:Node|Text)|menu(?:App|Cat)|virtualHost)$/)) {
461 return true;
462 } else {
463 return false;
464 }
465 };
466 // method `getKey()`:
467 // - return a promise with the data:
468 // - from node when set
469 // - after downloading else
470
471 $scope.getKey = function (node) {
472 var d, i, l, len, n, ref, tmp, uri;
473 d = $q.defer();
474 if (!node.data) {
475 $scope.waiting = true;
476 if (node.get && typeof node.get === 'object') {
477 node.data = [];
478 tmp = [];
479 ref = node.get;
480 for (i = l = 0, len = ref.length; l < len; i = ++l) {
481 n = ref[i];
482 node.data[i] = {
483 title: n.split("/").pop(),
484 get: n,
485 id: n
486 };
487 tmp.push($scope.getKey(node.data[i]));
488 }
489 $q.all(tmp).then(function () {
490 return d.resolve(node.data);
491 }, function (response) {
492 d.reject(response.statusLine);
493 return $scope.waiting = false;
494 });
495 } else {
496 uri = '';
497 if (node.get) {
498 console.debug(`Trying to get key ${node.get}`);
499 uri = encodeURI(node.get);
500 } else {
501 console.debug(`Trying to get title ${node.title}`);
502 }
503 $http.get(`${window.viewPrefix}${$scope.currentCfg.cfgNum}/${node.get ? uri : node.title}`).then(function (response) {
504 var data;
505 // Set default value if response is null or if asked by server
506 data = response.data;
507 if ((data.value === null || data.error && data.error.match(/setDefault$/)) && node['default'] !== null) {
508 node.data = node['default'];
509 } else {
510 node.data = data.value;
511 }
512 if (node.data && node.data.toString().match(/_Hidden_$/)) {
513 node.type = 'text';
514 node.data = '######';
515 }
516 // Cast int as int (remember that booleans are int for Perl)
517 if (node.type && node.type.match(/^(bool|trool|boolOrExpr)$/)) {
518 if (typeof node.data === 'string' && node.data.match(/^(?:-1|0|1)$/)) {
519 node.data = parseInt(node.data, 10);
520 }
521 }
522 if (node.type && node.type.match(/^int$/)) {
523 node.data = parseInt(node.data, 10);
524 // Split SAML types
525 } else if (node.type && node.type.match(/^(saml(Service|Assertion)|blackWhiteList)$/) && !(typeof node.data === 'object')) {
526 node.data = node.data.split(';');
527 }
528 $scope.waiting = false;
529 return d.resolve(node.data);
530 }, function (response) {
531 readError(response);
532 return d.reject(response.status);
533 });
534 }
535 } else {
536 if (node.data.toString().match(/_Hidden_$/)) {
537 node.type = 'text';
538 node.data = '######';
539 }
540 d.resolve(node.data);
541 }
542 return d.promise;
543 };
544 // function `pathEvent(event, next; current)`:
545 // Called when $location.path() change, launch getCfg() with the new
546 // configuration number
547 pathEvent = function (event, next, current) {
548 var n;
549 n = next.match(new RegExp('#!?/view/(latest|[0-9]+)'));
550 if (n === null) {
551 return $location.path('/view/latest');
552 } else {
553 console.debug(`Trying to get cfg number ${n[1]}`);
554 return $scope.getCfg(n[1]);
555 }
556 };
557 $scope.$on('$locationChangeSuccess', pathEvent);
558 // function `getCfg(n)`:
559 // Download configuration metadatas
560 $scope.getCfg = function (n) {
561 if ($scope.currentCfg.cfgNum !== n) {
562 return $http.get(`${window.viewPrefix}${n}`).then(function (response) {
563 var d;
564 $scope.currentCfg = response.data;
565 d = new Date($scope.currentCfg.cfgDate * 1000);
566 $scope.currentCfg.date = d.toLocaleString();
567 console.debug(`Metadatas of cfg ${n} loaded`);
568 $location.path(`/view/${n}`);
569 return $scope.init();
570 }, function (response) {
571 return readError(response).then(function () {
572 $scope.currentCfg.cfgNum = 0;
573 return $scope.init();
574 });
575 });
576 } else {
577 return $scope.waiting = false;
578 }
579 };
580 // method `getLanguage(lang)`
581 // Launch init() after setting current language
582 $scope.getLanguage = function (lang) {
583 $scope.lang = lang;
584 // Force reload home
585 $scope.form = 'white';
586 $scope.init();
587 return $scope.showM = false;
588 };
589 // Initialization
590
591 // Load JSON files:
592 // - struct.json: the main tree
593 // - languages/<lang>.json: the chosen language datas
594 $scope.init = function () {
595 var tmp;
596 tmp = null;
597 $scope.waiting = true;
598 $scope.breadCrumb = null;
599 $scope.data = [];
600 $scope.confirmNeeded = false;
601 $scope.forceSave = false;
602 $q.all([$translator.init($scope.lang), $http.get(`${window.staticPrefix}struct.json`).then(function (response) {
603 tmp = response.data;
604 console.debug("Structure loaded");
605 })]).then(function () {
606 console.debug("Starting structure binding");
607 $scope.data = tmp;
608 tmp = null;
609 if ($scope.currentCfg.cfgNum !== 0) {
610 setScopeVars($scope);
611 } else {
612 $scope.message = {
613 title: 'emptyConf',
614 message: '__zeroConfExplanations__'
615 };
616 $scope.showModal('message.html');
617 }
618 $scope.form = 'homeViewer';
619 return $scope.waiting = false;
620 }, readError);
621 // Colorized link
622 $scope.activeModule = "viewer";
623 return $scope.myStyle = {
624 color: '#ffb84d'
625 };
626 };
627 c = $location.path().match(new RegExp('^/view/(latest|[0-9]+)'));
628 if (!c) {
629 console.debug("Redirecting to /view/latest");
630 return $location.path('/view/latest');
631 }
632 }]);
633
634 })();