Debian Codegraph @

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

raw symbols SCIP
1 (function () {
2 'use strict';
3
4 /*
5 LemonLDAP::NG Manager 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('llngManager', ['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 _checkSaveResponse, _download, _getAll, _stoggle, c, idinc, pathEvent, readError, setDefault, 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 = 'home';
32 $scope.currentCfg = {};
33 $scope.clipboardAvailable = Boolean(navigator.clipboard);
34 $scope.confPrefix = window.confPrefix;
35 $scope.message = {};
36 $scope.result = '';
37 // Import translations functions
38 $scope.translateTitle = function (node) {
39 return $translator.translateField(node, 'title');
40 };
41 $scope.translateP = $translator.translateP;
42 $scope.translate = $translator.translate;
43 // HELP DISPLAY
44 $scope.helpUrl = 'start.html#configuration';
45 $scope.setShowHelp = function (val) {
46 var d;
47 if (val == null) {
48 val = !$scope.showH;
49 }
50 $scope.showH = val;
51 d = new Date(Date.now());
52 d.setFullYear(d.getFullYear() + 1);
53 return $cookies.put('showhelp', val ? 'true' : 'false', {
54 "expires": d
55 });
56 };
57 $scope.showH = $cookies.get('showhelp') === 'false' ? false : true;
58 if ($scope.showH == null) {
59 $scope.setShowHelp(true);
60 }
61 // INTERCEPT AJAX ERRORS
62 readError = function (response) {
63 var e, j;
64 e = response.status;
65 j = response.statusLine;
66 $scope.waiting = false;
67 if (e === 403) {
68 $scope.message = {
69 title: 'forbidden',
70 message: '',
71 items: []
72 };
73 } else if (e === 401) {
74 console.debug('Authentication needed');
75 $scope.message = {
76 title: 'authenticationNeeded',
77 message: '__waitOrF5__',
78 items: []
79 };
80 } else if (e === 400) {
81 $scope.message = {
82 title: 'badRequest',
83 message: j,
84 items: []
85 };
86 } else if (e > 0) {
87 $scope.message = {
88 title: 'badRequest',
89 message: j,
90 items: []
91 };
92 } else {
93 $scope.message = {
94 title: 'networkProblem',
95 message: '',
96 items: []
97 };
98 }
99 return $scope.showModal('message.html');
100 };
101 // Modal launcher
102 $scope.showModal = function (tpl, init) {
103 var d, modalInstance;
104 modalInstance = $uibModal.open({
105 templateUrl: tpl,
106 controller: 'ModalInstanceCtrl',
107 size: 'lg',
108 resolve: {
109 elem: function () {
110 return function (s) {
111 return $scope[s];
112 };
113 },
114 set: function () {
115 return function (f, s) {
116 return $scope[f] = s;
117 };
118 },
119 init: function () {
120 return init;
121 }
122 }
123 });
124 d = $q.defer();
125 modalInstance.result.then(function (msgok) {
126 $scope.message = {
127 title: '',
128 message: '',
129 items: []
130 };
131 return d.resolve(msgok);
132 }, function (msgnok) {
133 $scope.message = {
134 title: '',
135 message: '',
136 items: []
137 };
138 return d.reject(msgnok);
139 });
140 return d.promise;
141 };
142 // FORM DISPLAY FUNCTIONS
143
144 // Function called when a menu item is selected. It launch function stored in
145 // "action" or "title"
146 $scope.menuClick = function (button) {
147 if (button.popup) {
148 window.open(button.popup);
149 } else {
150 if (!button.action) {
151 button.action = button.title;
152 }
153 switch (typeof button.action) {
154 case 'function':
155 button.action($scope.currentNode, $scope);
156 break;
157 case 'string':
158 $scope[button.action]();
159 break;
160 default:
161 console.warn('Unknown action type', typeof button.action);
162 }
163 }
164 return $scope.showM = false;
165 };
166 // Display main form
167 $scope.home = function () {
168 $scope.form = 'home';
169 return $scope.showM = false;
170 };
171 // SAVE FUNCTIONS
172
173 // Private method called by $scope.save()
174 _checkSaveResponse = function (data) {
175 var m;
176 $scope.message = {
177 title: '',
178 message: '',
179 items: [],
180 itemsE: [],
181 itemsNC: [],
182 itemsW: []
183 };
184 if (data.needConfirm) {
185 $scope.confirmNeeded = true;
186 }
187 if (data.message) {
188 $scope.message.message = data.message;
189 }
190 // Sort messages
191 if (data.details) {
192 for (m in data.details) {
193 if (m !== '__changes__') {
194 if (m === '__needConfirmation__') {
195 $scope.message.itemsNC.push({
196 message: m,
197 items: data.details[m]
198 });
199 console.debug('NeedConfirmation:', $scope.message.itemsNC);
200 } else if (m === '__warnings__') {
201 $scope.message.itemsW.push({
202 message: m,
203 items: data.details[m]
204 });
205 console.debug('Warnings:', $scope.message.itemsW);
206 } else {
207 $scope.message.itemsE.push({
208 message: m,
209 items: data.details[m]
210 });
211 console.debug('Errors:', $scope.message.itemsE);
212 }
213 }
214 }
215 $scope.message.items = $scope.message.itemsE.concat($scope.message.itemsNC.concat($scope.message.itemsW));
216 }
217 $scope.waiting = false;
218 if (data.result === 1) {
219 // Force reloading page
220 $location.path('/confs/');
221 $scope.message.title = 'successfullySaved';
222 } else {
223 $scope.message.title = 'saveReport';
224 }
225 return $scope.showModal('message.html');
226 };
227 // Download raw conf
228 $scope.downloadConf = function () {
229 return window.open($scope.confPrefix + $scope.currentCfg.cfgNum + '?full=1');
230 };
231 // Download OIDC metadata
232 $scope.downloadOidcMetadata = function () {
233 return window.open($scope.confPrefix + $scope.currentCfg.cfgNum + '?oidcMetadata=1');
234 };
235 // Download SAML metadata
236 $scope.downloadSamlMetadata = function () {
237 return window.open($scope.confPrefix + $scope.currentCfg.cfgNum + '?samlMetadata=1');
238 };
239 // Main save function
240 $scope.save = function () {
241 $scope.showModal('save.html').then(function () {
242 $scope.waiting = true;
243 $scope.data.push({
244 id: "cfgLog",
245 title: "cfgLog",
246 data: $scope.result ? $scope.result : ''
247 });
248 return $http.post(`${window.confPrefix}?cfgNum=${$scope.currentCfg.cfgNum}&cfgDate=${$scope.currentCfg.cfgDate}${$scope.forceSave ? "&force=1" : ''}`, $scope.data).then(function (response) {
249 $scope.data.pop();
250 return _checkSaveResponse(response.data);
251 }, function (response) {
252 readError(response);
253 return $scope.data.pop();
254 });
255 }, function () {
256 console.debug('Saving canceled');
257 });
258 return $scope.showM = false;
259 };
260 // Raw save function
261 $scope.saveRawConf = function ($fileContent) {
262 $scope.waiting = true;
263 return $http.post(`${window.confPrefix}/raw`, $fileContent).then(function (response) {
264 return _checkSaveResponse(response.data);
265 }, readError);
266 };
267 // Restore raw conffunction
268 $scope.restore = function () {
269 $scope.currentNode = null;
270 return $scope.form = 'restore';
271 };
272 // Cancel save function
273 $scope.cancel = function () {
274 $scope.currentNode.data = null;
275 return $scope.getKey($scope.currentNode);
276 };
277 // NODES MANAGEMENT
278 idinc = 1;
279 $scope._findContainer = function () {
280 return $scope._findScopeContainer().$modelValue;
281 };
282 $scope._findScopeContainer = function () {
283 var cs;
284 cs = $scope.currentScope;
285 while (!cs.$modelValue.type.match(/Container$/)) {
286 cs = cs.$parentNodeScope;
287 }
288 return cs;
289 };
290 $scope._findScopeByKey = function (k) {
291 var cs;
292 cs = $scope.currentScope;
293 while (!(cs.$modelValue.title === k)) {
294 cs = cs.$parentNodeScope;
295 }
296 return cs;
297 };
298 // Add grant rule entry
299 $scope.newGrantRule = function () {
300 var node;
301 node = $scope._findContainer();
302 node.nodes.length;
303 return node.nodes.push({
304 id: `${node.id}/n${idinc++}`,
305 title: 'New rule',
306 re: '"Message"',
307 comment: 'New rule',
308 data: '1',
309 type: "grant"
310 });
311 };
312 // Add rules entry
313 $scope.newRule = function () {
314 var l, n, node;
315 node = $scope._findContainer();
316 l = node.nodes.length;
317 n = l > 0 ? l - 1 : 0;
318 return node.nodes.splice(n, 0, {
319 id: `${node.id}/n${idinc++}`,
320 title: 'New rule',
321 re: '^/new',
322 comment: 'New rule',
323 data: 'accept',
324 type: "rule"
325 });
326 };
327 // Add form replay
328 $scope.newPost = function () {
329 var node;
330 node = $scope._findContainer();
331 return node.nodes.push({
332 id: `${node.id}/n${idinc++}`,
333 title: "/absolute/path/to/form",
334 data: {},
335 type: "post"
336 });
337 };
338 $scope.newPostVar = function () {
339 if ($scope.currentNode.data.vars == null) {
340 $scope.currentNode.data.vars = [];
341 }
342 return $scope.currentNode.data.vars.push(['var1', '$uid']);
343 };
344 // Add auth chain entry to authChoice
345 $scope.newAuthChoice = function () {
346 var node;
347 node = $scope._findContainer();
348 node.nodes.push({
349 id: `${node.id}/n${idinc++}`,
350 title: "1_Key",
351 data: ['Null', 'Null', 'Null'],
352 type: "authChoice"
353 });
354 return $scope.execFilters($scope._findScopeByKey('authParams'));
355 };
356 // Add hash entry
357 $scope.newHashEntry = function () {
358 var node;
359 node = $scope._findContainer();
360 return node.nodes.push({
361 id: `${node.id}/n${idinc++}`,
362 title: 'new',
363 data: '',
364 type: "keyText"
365 });
366 };
367 // Menu cat entry
368 $scope.newCat = function () {
369 var cs;
370 cs = $scope.currentScope;
371 if (cs.$modelValue.type === 'menuApp') {
372 cs = cs.$parentNodeScope;
373 }
374 return cs.$modelValue.nodes.push({
375 id: `${cs.$modelValue.id}/n${idinc++}`,
376 title: "New category",
377 type: "menuCat",
378 nodes: []
379 });
380 };
381 // Menu app entry
382 $scope.newApp = function () {
383 var cs;
384 cs = $scope.currentScope;
385 if (cs.$modelValue.type === 'menuApp') {
386 cs = cs.$parentNodeScope;
387 }
388 return cs.$modelValue.nodes.push({
389 id: `${cs.$modelValue.id}/n${idinc++}`,
390 title: "New application",
391 type: "menuApp",
392 data: {
393 description: "New app description",
394 uri: "https://test.example.com/",
395 tooltip: "New app tooltip",
396 logo: "network.png",
397 display: "auto"
398 }
399 });
400 };
401 // Combination module
402 $scope.newCmbMod = function () {
403 var node;
404 node = $scope._findContainer();
405 node.nodes.push({
406 id: `${node.id}/n${idinc++}`,
407 title: 'new',
408 type: 'cmbModule',
409 data: {
410 type: 'LDAP',
411 for: '0',
412 over: []
413 }
414 });
415 return $scope.execFilters($scope._findScopeByKey('authParams'));
416 };
417 $scope.newSfExtra = function () {
418 var node;
419 node = $scope._findContainer();
420 return node.nodes.push({
421 id: `${node.id}/n${idinc++}`,
422 title: 'new',
423 type: 'sfExtra',
424 data: {
425 type: '',
426 rule: '',
427 logo: '',
428 level: '',
429 label: '',
430 over: []
431 }
432 });
433 };
434 $scope.newSfOver = function () {
435 var d;
436 d = $scope.currentNode.data;
437 if (!d.over) {
438 d.over = [];
439 }
440 return d.over.push([`new${idinc++}`, '']);
441 };
442 $scope.newCmbOver = function () {
443 var d;
444 d = $scope.currentNode.data;
445 if (!d.over) {
446 d.over = [];
447 }
448 return d.over.push([`new${idinc++}`, '']);
449 };
450 $scope.newChoiceOver = function () {
451 var d;
452 d = $scope.currentNode.data;
453 console.debug("data", d);
454 if (!d[5]) {
455 d[5] = [];
456 }
457 return d[5].push([`new${idinc++}`, '']);
458 };
459 // Add host
460 $scope.addHost = function () {
461 var cn;
462 cn = $scope.currentNode;
463 if (!cn.data) {
464 cn.data = [];
465 }
466 return cn.data.push({
467 k: "newHost",
468 h: [{
469 "k": "key",
470 "v": "uid"
471 }]
472 });
473 };
474 // SAML attribute entry
475 $scope.addSamlAttribute = function () {
476 var node;
477 node = $scope._findContainer();
478 return node.nodes.push({
479 id: `${node.id}/n${idinc++}`,
480 title: 'new',
481 type: 'samlAttribute',
482 data: ['0', 'New', '', '']
483 });
484 };
485 // OIDC attribute entry
486 $scope.addOidcAttribute = function () {
487 var node;
488 node = $scope._findContainer();
489 return node.nodes.push({
490 id: `${node.id}/n${idinc++}`,
491 title: 'new',
492 type: 'oidcAttribute',
493 data: ['', 'string', 'auto']
494 });
495 };
496 // Nodes with template
497 $scope.addVhost = function () {
498 var name;
499 name = $scope.domain ? `.${$scope.domain.data}` : '.example.com';
500 $scope.message = {
501 title: 'virtualHostName',
502 field: 'hostname'
503 };
504 return $scope.showModal('prompt.html', name).then(function () {
505 var n;
506 n = $scope.result;
507 if (n) {
508 return $scope.addTemplateNode(n, 'virtualHost');
509 }
510 });
511 };
512 $scope.duplicateVhost = function () {
513 var name;
514 name = $scope.domain ? `.${$scope.domain.data}` : '.example.com';
515 $scope.message = {
516 title: 'virtualHostName',
517 field: 'hostname'
518 };
519 return $scope.showModal('prompt.html', name).then(function () {
520 var n;
521 n = $scope.result;
522 return $scope.duplicateNode(n, 'virtualHost', $scope.currentNode.title);
523 });
524 };
525 $scope.addSamlIDP = function () {
526 return $scope.newTemplateNode('samlIDPMetaDataNode', 'samlPartnerName', 'idp-example');
527 };
528 $scope.addSamlSP = function () {
529 return $scope.newTemplateNode('samlSPMetaDataNode', 'samlPartnerName', 'sp-example');
530 };
531 $scope.duplicateSamlSp = function () {
532 $scope.message = {
533 title: 'samlPartnerName',
534 field: 'name'
535 };
536 return $scope.showModal('prompt.html', 'sp-copy').then(function () {
537 var n;
538 n = $scope.result;
539 return $scope.duplicateNode(n, 'samlSPMetaDataNode', $scope.currentNode.title);
540 });
541 };
542 $scope.addOidcOp = function () {
543 return $scope.newTemplateNode('oidcOPMetaDataNode', 'oidcOPName', 'op-example');
544 };
545 $scope.addOidcRp = function () {
546 return $scope.newTemplateNode('oidcRPMetaDataNode', 'oidcRPName', 'rp-example');
547 };
548 $scope.duplicateOidcRp = function () {
549 $scope.message = {
550 title: 'oidcRPName',
551 field: 'name'
552 };
553 return $scope.showModal('prompt.html', 'rp-copy').then(function () {
554 var n;
555 n = $scope.result;
556 return $scope.duplicateNode(n, 'oidcRPMetaDataNode', $scope.currentNode.title);
557 });
558 };
559 $scope.addCasSrv = function () {
560 return $scope.newTemplateNode('casSrvMetaDataNode', 'casPartnerName', 'srv-example');
561 };
562 $scope.addCasApp = function () {
563 return $scope.newTemplateNode('casAppMetaDataNode', 'casPartnerName', 'app-example');
564 };
565 $scope.duplicateCasApp = function () {
566 $scope.message = {
567 title: 'casPartnerName',
568 field: 'name'
569 };
570 return $scope.showModal('prompt.html', 'app-copy').then(function () {
571 var n;
572 n = $scope.result;
573 return $scope.duplicateNode(n, 'casAppMetaDataNode', $scope.currentNode.title);
574 });
575 };
576 $scope.addKey = function () {
577 return $scope.newTemplateNode('keyNode', 'keyName', 'key-example');
578 };
579 $scope.newTemplateNode = function (type, title, init) {
580 $scope.message = {
581 title: title,
582 field: 'name'
583 };
584 return $scope.showModal('prompt.html', init).then(function () {
585 var name;
586 name = $scope.result;
587 if (name) {
588 return $scope.addTemplateNode(name, type);
589 }
590 });
591 };
592 $scope.addTemplateNode = function (name, type) {
593 var cs, t;
594 cs = $scope.currentScope;
595 while (cs.$modelValue.title !== `${type}s`) {
596 cs = cs.$parentNodeScope;
597 }
598 t = {
599 id: `${type}s/new__${name}`,
600 title: name,
601 type: type,
602 nodes: templates(type, `new__${name}`)
603 };
604 setDefault(t.nodes);
605 cs.$modelValue.nodes.push(t);
606 cs.expand();
607 return t;
608 };
609 setDefault = function (node) {
610 var len, n, o;
611 for (o = 0, len = node.length; o < len; o++) {
612 n = node[o];
613 if (n.cnodes && n.default) {
614 delete n.cnodes;
615 n._nodes = n.default;
616 }
617 if (n._nodes) {
618 setDefault(n._nodes);
619 } else if (n.default || n.default === 0) {
620 n.data = n.default;
621 }
622 }
623 return node;
624 };
625 _getAll = function (node) {
626 var d, d2;
627 d = $q.defer();
628 d2 = $q.defer();
629 if (node._nodes) {
630 _stoggle(node);
631 d.resolve();
632 } else if (node.cnodes) {
633 _download(node).then(function () {
634 return d.resolve();
635 });
636 } else if (node.nodes || node.data) {
637 d.resolve();
638 } else {
639 $scope.getKey(node).then(function () {
640 return d.resolve();
641 });
642 }
643 d.promise.then(function () {
644 var len, n, o, ref, t;
645 t = [];
646 if (node.nodes) {
647 ref = node.nodes;
648 for (o = 0, len = ref.length; o < len; o++) {
649 n = ref[o];
650 t.push(_getAll(n));
651 }
652 }
653 return $q.all(t).then(function () {
654 return d2.resolve();
655 });
656 });
657 return d2.promise;
658 };
659 $scope.duplicateNode = function (name, type, idkey) {
660 var cs;
661 cs = $scope.currentScope;
662 return _getAll($scope.currentNode).then(function () {
663 var t;
664 while (cs.$modelValue.title !== `${type}s`) {
665 cs = cs.$parentNodeScope;
666 }
667 t = JSON.parse(JSON.stringify($scope.currentNode).replace(/[*]/g, '').replace(new RegExp(idkey, 'g'), 'new__' + name));
668 t.id = `${type}s/new__${name}`;
669 t.title = name;
670 cs.$modelValue.nodes.push(t);
671 return t;
672 });
673 };
674 $scope.del = function (a, i) {
675 return a.splice(i, 1);
676 };
677 $scope.deleteEntry = function () {
678 var p;
679 p = $scope.currentScope.$parentNodeScope;
680 $scope.currentScope.remove();
681 return $scope.displayForm(p);
682 };
683 $scope.down = function () {
684 var i, id, ind, len, n, o, p, ref, tmp;
685 id = $scope.currentNode.id;
686 p = $scope.currentScope.$parentNodeScope.$modelValue;
687 ind = p.nodes.length;
688 ref = p.nodes;
689 for (i = o = 0, len = ref.length; o < len; i = ++o) {
690 n = ref[i];
691 if (n.id === id) {
692 ind = i;
693 }
694 }
695 if (ind < p.nodes.length - 1) {
696 tmp = p.nodes[ind];
697 p.nodes[ind] = p.nodes[ind + 1];
698 p.nodes[ind + 1] = tmp;
699 }
700 return ind;
701 };
702 $scope.up = function () {
703 var i, id, ind, len, n, o, p, ref, tmp;
704 id = $scope.currentNode.id;
705 p = $scope.currentScope.$parentNodeScope.$modelValue;
706 ind = -1;
707 ref = p.nodes;
708 for (i = o = 0, len = ref.length; o < len; i = ++o) {
709 n = ref[i];
710 if (n.id === id) {
711 ind = i;
712 }
713 }
714 if (ind > 0) {
715 tmp = p.nodes[ind];
716 p.nodes[ind] = p.nodes[ind - 1];
717 p.nodes[ind - 1] = tmp;
718 }
719 return ind;
720 };
721 // test if value is in select
722 $scope.inSelect = function (value) {
723 var len, n, o, ref;
724 ref = $scope.currentNode.select;
725 for (o = 0, len = ref.length; o < len; o++) {
726 n = ref[o];
727 if (n.k === value) {
728 return true;
729 }
730 }
731 return false;
732 };
733 // This is for rule form: title = comment if defined, else title = re
734 $scope.changeRuleTitle = function (node) {
735 return node.title = node.comment.length > 0 ? node.comment : node.re;
736 };
737 // Node opening
738
739 // authParams mechanism: show used auth modules only (launched by stoggle)
740 $scope.filters = {};
741 $scope.execFilters = function (scope) {
742 var filter, func, ref;
743 scope = scope ? scope : $scope;
744 ref = $scope.filters;
745 for (filter in ref) {
746 func = ref[filter];
747 if ($scope.filters.hasOwnProperty(filter)) {
748 return window.filterFunctions[filter](scope, $q, func);
749 }
750 }
751 return false;
752 };
753 // To avoid binding all the tree, nodes are pushed in DOM only when opened
754 $scope.stoggle = function (scope) {
755 var node;
756 node = scope.$modelValue;
757 _stoggle(node);
758 return scope.toggle();
759 };
760 _stoggle = function (node) {
761 var a, len, len1, len2, n, o, q, r, ref, ref1, ref2;
762 ref = ['nodes', 'nodes_cond'];
763 for (o = 0, len = ref.length; o < len; o++) {
764 n = ref[o];
765 if (node[`_${n}`]) {
766 node[n] = [];
767 ref1 = node[`_${n}`];
768 for (q = 0, len1 = ref1.length; q < len1; q++) {
769 a = ref1[q];
770 node[n].push(a);
771 }
772 delete node[`_${n}`];
773 }
774 }
775 // Call execFilter for authParams
776 if (node._nodes_filter) {
777 if (node.nodes) {
778 ref2 = node.nodes;
779 for (r = 0, len2 = ref2.length; r < len2; r++) {
780 n = ref2[r];
781 n.onChange = $scope.execFilters;
782 }
783 }
784 $scope.filters[node._nodes_filter] = node;
785 return $scope.execFilters();
786 }
787 };
788 // Simple toggle management
789 $scope.toggle = function (scope) {
790 return scope.toggle();
791 };
792 // cnodes management: hash keys/values are loaded when parent node is opened
793 $scope.download = function (scope) {
794 var node;
795 node = scope.$modelValue;
796 return _download(node);
797 };
798 _download = function (node) {
799 var d, uri;
800 d = $q.defer();
801 d.notify('Trying to get datas');
802 $scope.waiting = true;
803 console.debug(`Trying to get key ${node.cnodes}`);
804 uri = encodeURI(node.cnodes);
805 $http.get(`${window.confPrefix}${$scope.currentCfg.cfgNum}/${uri}`).then(function (response) {
806 var a, data, len, o;
807 data = response.data;
808 // Manage datas errors
809 if (!data) {
810 d.reject('Empty response from server');
811 } else if (data.error) {
812 if (data.error.match(/setDefault$/)) {
813 if (node['default']) {
814 node.nodes = node['default'].slice(0);
815 } else {
816 node.nodes = [];
817 }
818 delete node.cnodes;
819 d.resolve('Set data to default value');
820 } else {
821 d.reject(`Server return an error: ${data.error}`);
822 }
823 } else {
824 // Store datas
825 delete node.cnodes;
826 if (!node.type) {
827 node.type = 'keyTextContainer';
828 }
829 node.nodes = [];
830 // TODO: try/catch
831 for (o = 0, len = data.length; o < len; o++) {
832 a = data[o];
833 if (a.template) {
834 a._nodes = templates(a.template, a.title);
835 }
836 node.nodes.push(a);
837 if (a.type.match(/^rule$/)) {
838 console.debug("Parse rule AuthnLevel as integer");
839 if (a.level && typeof a.level === 'string') {
840 a.level = parseInt(a.level, 10);
841 }
842 }
843 }
844 d.resolve('OK');
845 }
846 return $scope.waiting = false;
847 }, function (response) {
848 readError(response);
849 return d.reject('');
850 });
851 return d.promise;
852 };
853 $scope.openCnode = function (scope) {
854 return $scope.download(scope).then(function () {
855 return scope.toggle();
856 });
857 };
858 $scope.copyPath = function () {
859 var text = $scope.breadCrumb.join(" » ");
860 navigator.clipboard.writeText(text).then(function () {
861 $scope.$apply(function () {
862 $scope.copySuccess = true;
863 $timeout(function () {
864 $scope.copySuccess = false;
865 }, 400);
866 });
867 });
868 };
869 setHelp = function (scope) {
870 while (!scope.$modelValue.help && scope.$parentNodeScope) {
871 scope = scope.$parentNodeScope;
872 }
873 return $scope.helpUrl = scope.$modelValue.help || 'start.html#configuration';
874 };
875 // Form management
876
877 // `currentNode` contains the last select node
878
879 // method `diplayForm()`:
880 // - set the `form` property to the name of the form to download
881 // (`text` by default or `home` for node without `type` property)
882 // - launch getKeys to set `node.data`
883 // - hide tree when in XS size
884
885 $scope.getTrPath = function (scope) {
886 var path = [];
887 var trpath = [];
888 var current = scope;
889 var safetycount = 0;
890 while (current && current.$modelValue && safetycount < 100) {
891 safetycount = safetycount + 1;
892 if (current.$modelValue.title && current.$modelValue.title != path[0]) {
893 trpath.unshift(scope.translate(current.$modelValue.title));
894 path.unshift(current.$modelValue.title);
895 }
896 current = current.$parent;
897 }
898 return trpath;
899 };
900 $scope.displayForm = function (scope) {
901 var f, len, n, node, o, ref;
902 node = scope.$modelValue;
903 if (node.cnodes) {
904 $scope.download(scope);
905 }
906 if (node._nodes) {
907 $scope.stoggle(scope);
908 }
909 $scope.currentNode = node;
910 $scope.currentScope = scope;
911 f = node.type ? node.type : 'text';
912 if (node.nodes || node._nodes || node.cnodes) {
913 $scope.form = f !== 'text' ? f : 'mini';
914 } else {
915 $scope.form = f;
916 // Get datas
917 $scope.getKey(node);
918 }
919 if (node.type && node.type === 'simpleInputContainer') {
920 ref = node.nodes;
921 for (o = 0, len = ref.length; o < len; o++) {
922 n = ref[o];
923 $scope.getKey(n);
924 }
925 }
926 $scope.showT = false;
927 $scope.breadCrumb = $scope.getTrPath(scope);
928 return setHelp(scope);
929 };
930 $scope.keyWritable = function (scope) {
931 var node;
932 node = scope.$modelValue;
933 // regexp-assemble of:
934 // authChoice
935 // cmbModule
936 // keyText
937 // menuApp
938 // menuCat
939 // rule
940 // oidcAttribute
941 // samlAttribute
942 // samlIDPMetaDataNode
943 // samlSPMetaDataNode
944 // sfExtra
945 // virtualHost
946 if (node.type && node.type.match(/^(?:s(?:aml(?:(?:ID|S)PMetaDataNod|Attribut)e|fExtra)|oidcAttribute|(?:(?:cmbMod|r)ul|authChoic)e|(?:virtualHos|keyTex)t|menu(?:App|Cat))$/)) {
947 return true;
948 } else {
949 return false;
950 }
951 };
952 // Send test Email
953 $scope.sendTestMail = function () {
954 $scope.message = {
955 title: 'sendTestMail',
956 field: 'dest'
957 };
958 return $scope.showModal('prompt.html').then(function () {
959 var dest;
960 $scope.result;
961 $scope.waiting = true;
962 dest = $scope.result;
963 return $http.post(`${window.confPrefix}/sendTestMail`, {
964 "dest": dest
965 }).then(function (response) {
966 var error, success;
967 success = response.data.success;
968 error = response.data.error;
969 $scope.waiting = false;
970 if (success) {
971 $scope.message = {
972 title: 'ok',
973 message: '__sendTestMailSuccess__',
974 items: []
975 };
976 } else {
977 $scope.message = {
978 title: 'error',
979 message: error,
980 items: []
981 };
982 }
983 return $scope.showModal('message.html');
984 }, readError);
985 }, function () {
986 console.error('Error sending test email');
987 });
988 };
989 // RSA keys generation
990 $scope.newCertificate = function () {
991 return $scope.showModal('password.html').then(function () {
992 var currentNode, password;
993 $scope.waiting = true;
994 currentNode = $scope.currentNode;
995 password = $scope.result;
996 return $http.post(`${window.confPrefix}/newCertificate`, {
997 "password": password
998 }).then(function (response) {
999 currentNode.data[0].data = response.data.private;
1000 currentNode.data[1].data = password;
1001 currentNode.data[2].data = response.data.public;
1002 return $scope.waiting = false;
1003 }, readError);
1004 }, function () {
1005 console.debug('New key cancelled');
1006 });
1007 };
1008 $scope.newEcCertificate = function () {
1009 return $scope.showModal('password.html').then(function () {
1010 var currentNode, password;
1011 $scope.waiting = true;
1012 currentNode = $scope.currentNode;
1013 password = $scope.result;
1014 return $http.post(`${window.confPrefix}/newEcCertificate`, {
1015 "password": password
1016 }).then(function (response) {
1017 currentNode.data[0].data = response.data.private;
1018 currentNode.data[1].data = password;
1019 currentNode.data[2].data = response.data.public;
1020 return $scope.waiting = false;
1021 }, readError);
1022 }, function () {
1023 console.debug('New key cancelled');
1024 });
1025 };
1026 $scope.newEcKeys = function () {
1027 var currentNode;
1028 $scope.waiting = true;
1029 currentNode = $scope.currentNode;
1030 return $http.post(`${window.confPrefix}/newEcKeys`, {
1031 "password": ''
1032 }).then(function (response) {
1033 var i, o;
1034 for (i = o = 0; o <= 3; i = ++o) {
1035 currentNode.data[i + 4].data = currentNode.data[i].data;
1036 }
1037 currentNode.data[0].data = response.data.private;
1038 currentNode.data[1].data = response.data.public;
1039 currentNode.data[2].data = response.data.hash;
1040 currentNode.data[3].data = 'EC';
1041 return $scope.waiting = false;
1042 }, readError);
1043 };
1044 $scope.newCertificateNoPassword = function () {
1045 var currentNode;
1046 $scope.waiting = true;
1047 currentNode = $scope.currentNode;
1048 return $http.post(`${window.confPrefix}/newCertificate`, {
1049 "password": ''
1050 }).then(function (response) {
1051 var i, o;
1052 for (i = o = 0; o <= 3; i = ++o) {
1053 currentNode.data[i + 4].data = currentNode.data[i].data;
1054 }
1055 currentNode.data[0].data = response.data.private;
1056 currentNode.data[1].data = response.data.public;
1057 currentNode.data[2].data = response.data.hash;
1058 currentNode.data[3].data = 'RSA';
1059 return $scope.waiting = false;
1060 }, readError);
1061 };
1062 $scope.newRSAKey = function () {
1063 return $scope.showModal('password.html').then(function () {
1064 var currentNode, password;
1065 $scope.waiting = true;
1066 currentNode = $scope.currentNode;
1067 password = $scope.result;
1068 return $http.post(`${window.confPrefix}/newRSAKey`, {
1069 "password": password
1070 }).then(function (response) {
1071 currentNode.data[0].data = response.data.private;
1072 currentNode.data[1].data = password;
1073 currentNode.data[2].data = response.data.public;
1074 return $scope.waiting = false;
1075 }, readError);
1076 }, function () {
1077 console.debug('New key cancelled');
1078 });
1079 };
1080 // - return a promise with the data:
1081 // - from node when set
1082 // - after downloading else
1083
1084 $scope.getKey = function (node) {
1085 var d, i, len, n, o, ref, tmp, uri;
1086 d = $q.defer();
1087 if (!node.data) {
1088 $scope.waiting = true;
1089 if (node.get && typeof node.get === 'object') {
1090 node.data = [];
1091 tmp = [];
1092 ref = node.get;
1093 for (i = o = 0, len = ref.length; o < len; i = ++o) {
1094 n = ref[i];
1095 node.data[i] = {
1096 title: n.split("/").pop(),
1097 get: n,
1098 id: n
1099 };
1100 tmp.push($scope.getKey(node.data[i]));
1101 }
1102 $q.all(tmp).then(function () {
1103 return d.resolve(node.data);
1104 }, function (response) {
1105 d.reject(response.statusLine);
1106 return $scope.waiting = false;
1107 });
1108 } else {
1109 uri = '';
1110 if (node.get) {
1111 console.debug(`Trying to get key ${node.get}`);
1112 uri = encodeURI(node.get);
1113 } else {
1114 console.debug(`Trying to get title ${node.title}`);
1115 }
1116 $http.get(`${window.confPrefix}${$scope.currentCfg.cfgNum}/${node.get ? uri : node.title}`).then(function (response) {
1117 var data;
1118 // Set default value if response is null or if asked by server
1119 data = response.data;
1120 if ((data.value === null || data.error && data.error.match(/setDefault$/)) && node['default'] !== null) {
1121 node.data = node['default'];
1122 } else {
1123 node.data = data.value;
1124 }
1125 // Cast int as int (remember that booleans are int for Perl)
1126 if (node.type && node.type.match(/^(bool|trool|boolOrExpr)$/)) {
1127 if (typeof node.data === 'string' && node.data.match(/^(?:-1|0|1)$/)) {
1128 node.data = parseInt(node.data, 10);
1129 }
1130 }
1131 if (node.type && node.type.match(/^int$/)) {
1132 node.data = parseInt(node.data, 10);
1133 }
1134 if (node.type && node.type.match(/^select$/)) {
1135 node.data = node.data ? node.data.toString() : '';
1136 // Split SAML types
1137 } else if (node.type && node.type.match(/^(saml(Service|Assertion)|blackWhiteList)$/) && !(node.data && typeof node.data === 'object')) {
1138 node.data = node.data ? node.data.split(';') : [];
1139 }
1140 $scope.waiting = false;
1141 return d.resolve(node.data);
1142 }, function (response) {
1143 readError(response);
1144 return d.reject(response.status);
1145 });
1146 }
1147 } else {
1148 d.resolve(node.data);
1149 }
1150 return d.promise;
1151 };
1152 // function `pathEvent(event, next; current)`:
1153 // Called when $location.path() change, launch getCfg() with the new
1154 // configuration number
1155 pathEvent = function (event, next, current) {
1156 var n;
1157 n = next.match(new RegExp('#!?/confs/(latest|[0-9]+)'));
1158 if (n === null) {
1159 return $location.path('/confs/latest');
1160 } else {
1161 console.debug(`Trying to get cfg number ${n[1]}`);
1162 return $scope.getCfg(n[1]);
1163 }
1164 };
1165 $scope.$on('$locationChangeSuccess', pathEvent);
1166 // function `getCfg(n)`:
1167 // Download configuration metadatas
1168 $scope.getCfg = function (n) {
1169 if ($scope.currentCfg.cfgNum !== n) {
1170 return $http.get(`${window.confPrefix}${n}`).then(function (response) {
1171 var d;
1172 $scope.currentCfg = response.data;
1173 d = new Date($scope.currentCfg.cfgDate * 1000);
1174 $scope.currentCfg.date = d.toLocaleString();
1175 console.debug(`Metadatas of cfg ${n} loaded`);
1176 $location.path(`/confs/${n}`);
1177 return $scope.init();
1178 }, function (response) {
1179 return readError(response).then(function () {
1180 $scope.currentCfg.cfgNum = 0;
1181 return $scope.init();
1182 });
1183 });
1184 } else {
1185 return $scope.waiting = false;
1186 }
1187 };
1188 // method `getLanguage(lang)`
1189 // Launch init() after setting current language
1190 $scope.getLanguage = function (lang) {
1191 $scope.lang = lang;
1192 // Force reload home
1193 $scope.form = 'white';
1194 $scope.init();
1195 return $scope.showM = false;
1196 };
1197 // Initialization
1198
1199 // Load JSON files:
1200 // - struct.json: the main tree
1201 // - languages/<lang>.json: the chosen language datas
1202 $scope.init = function () {
1203 var tmp;
1204 tmp = null;
1205 $scope.waiting = true;
1206 $scope.breadCrumb = null;
1207 $scope.data = [];
1208 $scope.confirmNeeded = false;
1209 $scope.forceSave = false;
1210 $q.all([$translator.init($scope.lang), $http.get(`${window.staticPrefix}struct.json`).then(function (response) {
1211 tmp = response.data;
1212 console.debug("Structure loaded");
1213 })]).then(function () {
1214 console.debug("Starting structure binding");
1215 $scope.data = tmp;
1216 tmp = null;
1217 if ($scope.currentCfg.cfgNum !== 0) {
1218 setScopeVars($scope);
1219 } else {
1220 $scope.message = {
1221 title: 'emptyConf',
1222 message: '__zeroConfExplanations__'
1223 };
1224 $scope.showModal('message.html');
1225 }
1226 $scope.form = 'home';
1227 return $scope.waiting = false;
1228 }, readError);
1229 // Colorized link
1230 $scope.activeModule = "conf";
1231 return $scope.myStyle = {
1232 color: '#ffb84d'
1233 };
1234 };
1235 c = $location.path().match(new RegExp('^/confs/(latest|[0-9]+)'));
1236 if (!c) {
1237 console.debug("Redirecting to /confs/latest");
1238 $location.path('/confs/latest');
1239 }
1240 // File form function
1241 $scope.replaceContentByUrl = function (node, url) {
1242 $scope.waiting = true;
1243 return $http.post(window.scriptname + "prx", {
1244 url: url
1245 }).then(function (response) {
1246 node.data = response.data.content;
1247 return $scope.waiting = false;
1248 }, readError);
1249 };
1250 $scope.replaceContent = function (node, $fileContent) {
1251 return node.data = $fileContent;
1252 };
1253 // Import Filesaver.js saveAs()
1254 $scope.saveAs = function (content, type, filename) {
1255 return saveAs(new Blob([content], {
1256 "type": type
1257 }), filename);
1258 };
1259 // Save as pem, text,...
1260 $scope.saveAsPem = function (cs, scope) {
1261 return scope.saveAs(`${cs.data[0].data}\n${cs.data[2].data}`, 'application/x-pem-file', `${cs.title}.pem`);
1262 };
1263 return $scope.saveAsText = function (cs, scope) {
1264 return scope.saveAs(cs.data, 'text/plain', `${cs.title}.txt`);
1265 };
1266 }]);
1267
1268 })();