Debian Codegraph @

lemonldap-ng-manager/site/js-src/sessions.js

raw symbols SCIP
1 /*
2 * Sessions explorer
3 */
4 /*
5 * AngularJS application
6 */
7 var categories, hiddenAttributes, llapp, max, menu, overScheme, schemes;
8
9 // Max number of session to display (see overScheme)
10 max = 25;
11
12 // Queries to do each type of display: each array item corresponds to the depth
13 // of opened nodes in the tree
14 schemes = {
15 _whatToTrace: [
16 // First level: display 1 letter
17 function(t, v) {
18 return `groupBy=substr(${t},1)`;
19 },
20 // Second level (if no overScheme), display usernames
21 function(t, v) {
22 return `${t}=${v}*&groupBy=${t}`;
23 },
24 function(t, v) {
25 return `${t}=${v}`;
26 }
27 ],
28 ipAddr: [
29 function(t, v) {
30 return `groupBy=net(${t},16,1)`;
31 },
32 function(t, v) {
33 if (!v.match(/:/)) {
34 v = v + '.';
35 }
36 return `${t}=${v}*&groupBy=net(${t},32,2)`;
37 },
38 function(t, v) {
39 if (!v.match(/:/)) {
40 v = v + '.';
41 }
42 return `${t}=${v}*&groupBy=net(${t},48,3)`;
43 },
44 function(t, v) {
45 if (!v.match(/:/)) {
46 v = v + '.';
47 }
48 return `${t}=${v}*&groupBy=net(${t},128,4)`;
49 },
50 function(t, v) {
51 return `${t}=${v}&groupBy=_whatToTrace`;
52 },
53 function(t, v,
54 q) {
55 return q.replace(/\&groupBy.*$/, '') + `&_whatToTrace=${v}`;
56 }
57 ],
58 _startTime: [
59 function(t, v) {
60 return `groupBy=substr(${t},8)`;
61 },
62 function(t, v) {
63 return `${t}=${v}*&groupBy=substr(${t},10)`;
64 },
65 function(t, v) {
66 return `${t}=${v}*&groupBy=substr(${t},11)`;
67 },
68 function(t, v) {
69 return `${t}=${v}*&groupBy=substr(${t},12)`;
70 },
71 function(t, v) {
72 return `${t}=${v}*&groupBy=_whatToTrace`;
73 },
74 function(t, v, q) {
75 return q.replace(/\&groupBy.*$/, '') + `&_whatToTrace=${v}`;
76 }
77 ],
78 doubleIp: [
79 function(t, v) {
80 return t;
81 },
82 function(t, v) {
83 return `_whatToTrace=${v}&groupBy=ipAddr`;
84 },
85 function(t, v, q) {
86 return q.replace(/\&groupBy.*$/, '') + `&ipAddr=${v}`;
87 }
88 ],
89 _session_uid: [
90 // First level: display 1 letter
91 function(t, v) {
92 return `groupBy=substr(${t},1)`;
93 },
94 // Second level (if no overScheme), display usernames
95 function(t, v) {
96 return `${t}=${v}*&groupBy=${t}`;
97 },
98 function(t, v) {
99 return `${t}=${v}`;
100 }
101 ]
102 };
103
104 // When number of children nodes exceeds "max" value and if "overScheme.<type>"
105 // is available and does not return "null", a level is added. See
106 // "$scope.updateTree" method
107 overScheme = {
108 _whatToTrace: function(t, v, level, over) {
109 // "v.length > over" avoids a loop if one user opened more than "max"
110 // sessions
111 console.debug('overScheme => level', level, 'over', over);
112
113 // no overScheme when over reached the length of previous result
114 if (v.length >= (level+over)) return null;
115 if (level === 1 && v.length > over) {
116 return `${t}=${v}*&groupBy=substr(${t},${level + over + 1})`;
117 } else {
118 return null;
119 }
120 },
121 // Note: IPv4 only
122 ipAddr: function(t, v, level, over) {
123 console.debug('overScheme => level', level, 'over', over);
124 if (level > 0 && level < 4 && !v.match(/^\d+\.\d/) && over < 2) {
125 return `${t}=${v}*&groupBy=net(${t},${16 * level + 4 * (over + 1)},${1 + level + over})`;
126 } else {
127 return null;
128 }
129 },
130 _startTime: function(t, v, level, over) {
131 console.debug('overScheme => level', level, 'over', over);
132 if (level > 3) {
133 return `${t}=${v}*&groupBy=substr(${t},${10 + level + over})`;
134 } else {
135 return null;
136 }
137 },
138 _session_uid: function(t, v, level, over) {
139 console.debug('overScheme => level', level, 'over', over);
140 if (level === 1 && v.length > over) {
141 return `${t}=${v}*&groupBy=substr(${t},${level + over + 1})`;
142 } else {
143 return null;
144 }
145 }
146 };
147
148 hiddenAttributes = '_password';
149
150 // Attributes to group in session display
151 categories = {
152 dateTitle: ['_utime', '_startTime', '_updateTime', '_lastAuthnUTime', '_lastSeen'],
153 connectionTitle: ['ipAddr', '_timezone', '_url'],
154 authenticationTitle: ['_session_id', '_user', '_password', 'authenticationLevel'],
155 modulesTitle: ['_auth', '_userDB', '_passwordDB', '_issuerDB', '_authChoice', '_authMulti', '_userDBMulti', '_2f'],
156 saml: ['_idp', '_idpConfKey', '_samlToken', '_lassoSessionDump', '_lassoIdentityDump'],
157 groups: ['groups', 'hGroups'],
158 ldap: ['dn'],
159 OpenIDConnect: ['_oidc_id_token', '_oidc_OP', '_oidc_access_token', '_oidc_refresh_token', '_oidc_access_token_eol', '_oidcConnectedRP', '_oidcConnectedRPIDs'],
160 sfaTitle: ['_2fDevices'],
161 oidcConsents: ['_oidcConsents']
162 };
163
164 // Menu entries
165 menu = {
166 session: [{
167 title: 'deleteSession',
168 icon: 'trash'
169 },
170 {
171 title: 'globalLogout',
172 icon: 'trash'
173 }
174 ],
175 home: []
176 };
177
178 llapp = angular.module('llngSessionsExplorer', ['ui.tree', 'ui.bootstrap', 'llApp']);
179
180 // Main controller
181 llapp.controller('SessionsExplorerCtrl', [
182 '$scope',
183 '$translator',
184 '$location',
185 '$q',
186 '$http',
187 function($scope,
188 $translator,
189 $location,
190 $q,
191 $http) {
192 var autoId,
193 c,
194 pathEvent,
195 sessionType;
196 $scope.links = links;
197 $scope.menulinks = menulinks;
198 $scope.staticPrefix = staticPrefix;
199 $scope.scriptname = scriptname;
200 $scope.formPrefix = formPrefix;
201 $scope.impPrefix = impPrefix;
202 $scope.sessionTTL = sessionTTL;
203 $scope.availableLanguages = availableLanguages;
204 $scope.waiting = true;
205 $scope.showM = false;
206 $scope.showT = true;
207 $scope.data = [];
208 $scope.currentScope = null;
209 $scope.currentSession = null;
210 $scope.menu = menu;
211 // Import translations functions
212 $scope.translateP = $translator.translateP;
213 $scope.translate = $translator.translate;
214 $scope.translateTitle = function(node) {
215 return $translator.translateField(node, 'title');
216 };
217 sessionType = 'global';
218 // Handle menu items
219 $scope.menuClick = function(button) {
220 if (button.popup) {
221 window.open(button.popup);
222 } else {
223 if (!button.action) {
224 button.action = button.title;
225 }
226 switch (typeof button.action) {
227 case 'function':
228 button.action($scope.currentNode, $scope);
229 break;
230 case 'string':
231 $scope[button.action]();
232 break;
233 default:
234 console.warn('Unknown action type', typeof button.action);
235 }
236 }
237 return $scope.showM = false;
238 };
239 // SESSION MANAGEMENT
240
241 // Delete RP Consent
242 $scope.deleteOIDCConsent = function(rp, epoch) {
243 var items;
244 items = document.querySelectorAll(`.data-${epoch}`);
245 $scope.waiting = true;
246 $http['delete'](`${scriptname}sessions/OIDCConsent/${sessionType}/${$scope.currentSession.id}?rp=${rp}&epoch=${epoch}`).then(function(response) {
247 var e, i, len, results;
248 $scope.waiting = false;
249 results = [];
250 for (i = 0, len = items.length; i < len; i++) {
251 e = items[i];
252 results.push(e.remove());
253 }
254 return results;
255 },
256 function(resp) {
257 return $scope.waiting = false;
258 });
259 return $scope.showT = false;
260 };
261 // Delete
262 $scope.deleteSession = function() {
263 $scope.waiting = true;
264 return $http['delete'](`${scriptname}sessions/${sessionType}/${$scope.currentSession.id}`).then(function(response) {
265 $scope.currentSession = null;
266 $scope.currentScope.remove();
267 return $scope.waiting = false;
268 },
269 function(resp) {
270 return $scope.waiting = false;
271 });
272 };
273 $scope.globalLogout = function() {
274 $scope.waiting = true;
275 return $http['post'](`${scriptname}sessions/glogout/${sessionType}/${$scope.currentSession.id}`).then(function(response) {
276 $scope.currentSession = null;
277 $scope.currentScope.remove();
278 return $scope.waiting = false;
279 },
280 function(resp) {
281 return $scope.waiting = false;
282 });
283 };
284 // Open node
285 $scope.stoggle = function(scope) {
286 var node;
287 node = scope.$modelValue;
288 if (node.nodes.length === 0) {
289 $scope.updateTree(node.value,
290 node.nodes,
291 node.level,
292 node.over,
293 node.query,
294 node.count);
295 }
296 return scope.toggle();
297 };
298 // Display selected session
299 $scope.displaySession = function(scope) {
300 var sessionId, transformSession;
301 // Private functions
302
303 // Session preparation
304 transformSession = function(session) {
305 var _insert, array, attr, attrs, category, cv, element, epoch, i, j, k, key, l, len, len1, len2, len3, len4, len5, m, name, o, oidcConsent, p, real, ref, ref1, res, sfDevice, spoof, subres, tab, time, title, tmp, value;
306 _insert = function(re,
307 title) {
308 var cv, i, key, len, reg, tab, tmp, val, value, vk;
309 tmp = [];
310 reg = new RegExp(re);
311 cv = "";
312 for (key in session) {
313 value = session[key];
314 if (key.match(reg) && value) {
315 cv += `${value}:${key},`;
316 delete session[key];
317 }
318 }
319 if (cv) {
320 cv = cv.replace(/,$/, '');
321 tab = cv.split(',');
322 tab.sort();
323 tab.reverse();
324 for (i = 0, len = tab.length; i < len; i++) {
325 val = tab[i];
326 vk = val.split(':');
327 tmp.push({
328 title: vk[1],
329 value: $scope.localeDate(vk[0])
330 });
331 }
332 return res.push({
333 title: title,
334 nodes: tmp
335 });
336 }
337 };
338 time = session._utime;
339 // 1. Replace values if needed
340 for (key in session) {
341 value = session[key];
342 if (!value) {
343 delete session[key];
344 } else {
345 if (typeof session === 'string' && value.match(/; /)) {
346 session[key] = value.split('; ');
347 }
348 if (typeof session[key] !== 'object') {
349 if (hiddenAttributes.match(new RegExp('\b' + key + '\b'))) {
350 session[key] = '********';
351 } else if (key.match(/^(_utime|_lastAuthnUTime|_lastSeen|notification)$/)) {
352 session[key] = $scope.localeDate(value);
353 } else if (key.match(/^(_startTime|_updateTime)$/)) {
354 session[key] = $scope.strToLocaleDate(value);
355 }
356 }
357 }
358 }
359 res = [];
360 // 2. Push session keys in result, grouped by categories
361 for (category in categories) {
362 attrs = categories[category];
363 subres = [];
364 for (i = 0, len = attrs.length; i < len; i++) {
365 attr = attrs[i];
366 if (session[attr]) {
367 if (attr === "_2fDevices" && session[attr]) {
368 array = JSON.parse(session[attr]);
369 if (array.length > 0) {
370 subres.push({
371 title: "type",
372 value: "name",
373 epoch: "date",
374 td: "0"
375 });
376 for (j = 0, len1 = array.length; j < len1; j++) {
377 sfDevice = array[j];
378 for (key in sfDevice) {
379 value = sfDevice[key];
380 if (key === 'type') {
381 title = value;
382 }
383 if (key === 'name') {
384 name = value;
385 }
386 if (key === 'epoch') {
387 epoch = value;
388 }
389 }
390 subres.push({
391 title: title,
392 value: name,
393 epoch: epoch,
394 td: "1"
395 });
396 }
397 }
398 delete session[attr];
399 } else if (session[attr].toString().match(/"rp":\s*"[\w-]+"/)) {
400 subres.push({
401 title: "RP",
402 value: "scope",
403 epoch: "date",
404 td: "0"
405 });
406 array = JSON.parse(session[attr]);
407 for (k = 0, len2 = array.length; k < len2; k++) {
408 oidcConsent = array[k];
409 for (key in oidcConsent) {
410 value = oidcConsent[key];
411 if (key === 'rp') {
412 title = value;
413 }
414 if (key === 'scope') {
415 name = value;
416 }
417 if (key === 'epoch') {
418 epoch = value;
419 }
420 }
421 subres.push({
422 title: title,
423 value: name,
424 epoch: epoch,
425 td: "2"
426 });
427 }
428 delete session[attr];
429 } else if (session[attr].toString().match(/\w+/)) {
430 subres.push({
431 title: attr,
432 value: session[attr],
433 epoch: ''
434 });
435 delete session[attr];
436 } else {
437 delete session[attr];
438 }
439 } else {
440 delete session[attr];
441 }
442 }
443 if (subres.length > 0) {
444 res.push({
445 title: `__${category}__`,
446 nodes: subres
447 });
448 }
449 }
450 // 3. Add OpenID and notifications already notified
451 _insert('^openid', 'OpenID');
452 _insert('^notification_(.+)', '__notificationsDone__');
453 // 4. Add session history if exists
454 if (session._loginHistory) {
455 tmp = [];
456 if (session._loginHistory.successLogin) {
457 ref = session._loginHistory.successLogin;
458 for (m = 0, len3 = ref.length; m < len3; m++) {
459 l = ref[m];
460 // History custom values
461 cv = "";
462 for (key in l) {
463 value = l[key];
464 if (!key.match(/^(_utime|ipAddr|error)$/)) {
465 cv += `, ${key} : ${value}`;
466 }
467 }
468 tab = cv.split(', ');
469 tab.sort();
470 cv = tab.join(', ');
471 tmp.push({
472 t: l._utime,
473 title: $scope.localeDate(l._utime),
474 value: `Success (IP ${l.ipAddr})` + cv
475 });
476 }
477 }
478 if (session._loginHistory.failedLogin) {
479 ref1 = session._loginHistory.failedLogin;
480 for (o = 0, len4 = ref1.length; o < len4; o++) {
481 l = ref1[o];
482 // History custom values
483 cv = "";
484 for (key in l) {
485 value = l[key];
486 if (!key.match(/^(_utime|ipAddr|error)$/)) {
487 cv += `, ${key} : ${value}`;
488 }
489 }
490 tab = cv.split(', ');
491 tab.sort();
492 cv = tab.join(', ');
493 tmp.push({
494 t: l._utime,
495 title: $scope.localeDate(l._utime),
496 value: `Error ${l.error} (IP ${l.ipAddr})` + cv
497 });
498 }
499 }
500 delete session._loginHistory;
501 tmp.sort(function(a, b) {
502 return b.t - a.t;
503 });
504 res.push({
505 title: '__loginHistory__',
506 nodes: tmp
507 });
508 }
509 // 5. Other keys (attributes and macros)
510 tmp = [];
511 for (key in session) {
512 value = session[key];
513 tmp.push({
514 title: key,
515 value: value
516 });
517 }
518 tmp.sort(function(a, b) {
519 if (a.title > b.title) {
520 return 1;
521 } else if (a.title < b.title) {
522 return -1;
523 } else {
524 return 0;
525 }
526 });
527 // Sort by real and spoofed attributes
528 real = [];
529 spoof = [];
530 for (p = 0, len5 = tmp.length; p < len5; p++) {
531 element = tmp[p];
532 if (element.title.match(new RegExp('^' + $scope.impPrefix + '.+$'))) {
533 console.debug(element, '-> real attribute');
534 real.push(element);
535 } else {
536 //console.debug element, '-> spoofed attribute'
537 spoof.push(element);
538 }
539 }
540 tmp = spoof.concat(real);
541 res.push({
542 title: '__attributesAndMacros__',
543 nodes: tmp
544 });
545 return {
546 _utime: time,
547 nodes: res
548 };
549 };
550 $scope.currentScope = scope;
551 sessionId = scope.$modelValue.session;
552 $http.get(`${scriptname}sessions/${sessionType}/${sessionId}`).then(function(response) {
553 $scope.currentSession = transformSession(response.data);
554 return $scope.currentSession.id = sessionId;
555 });
556 return $scope.showT = false;
557 };
558 $scope.localeDate = function(s) {
559 var d;
560 d = new Date(s * 1000);
561 return d.toLocaleString();
562 };
563 $scope.isValid = function(epoch, type) {
564 var isValid, now, path;
565 path = $location.path();
566 now = Date.now() / 1000;
567 console.debug("Path", path);
568 console.debug("Session epoch", epoch);
569 console.debug("Current date", now);
570 console.debug("Session TTL", sessionTTL);
571 isValid = now - epoch < sessionTTL || $location.path().match(/^\/persistent/);
572 if (type === 'msg') {
573 console.debug("Return msg");
574 if (isValid) {
575 return "info";
576 } else {
577 return "warning";
578 }
579 } else if (type === 'style') {
580 console.debug("Return style");
581 if (isValid) {
582 return {};
583 } else {
584 return {
585 'color': '#627990',
586 'font-style': 'italic'
587 };
588 }
589 } else {
590 console.debug("Return isValid");
591 return isValid;
592 }
593 };
594 $scope.strToLocaleDate = function(s) {
595 var arrayDate, d;
596 arrayDate = s.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/);
597 if (!arrayDate.length) {
598 return s;
599 }
600 d = new Date(`${arrayDate[1]}-${arrayDate[2]}-${arrayDate[3]}T${arrayDate[4]}:${arrayDate[5]}:${arrayDate[6]}`);
601 return d.toLocaleString();
602 };
603 // Function to change interface language
604 $scope.getLanguage = function(lang) {
605 $scope.lang = lang;
606 $scope.form = 'white';
607 $scope.init();
608 return $scope.showM = false;
609 };
610 // URI local path management
611 pathEvent = function(event, next, current) {
612 var n;
613 n = next.match(/#!?\/(\w+)/);
614 sessionType = 'global';
615 if (n === null) {
616 $scope.type = '_whatToTrace';
617 } else if (n[1].match(/^(persistent|offline)$/)) {
618 sessionType = RegExp.$1;
619 $scope.type = '_session_uid';
620 } else {
621 $scope.type = n[1];
622 }
623 return $scope.init();
624 };
625 $scope.$on('$locationChangeSuccess', pathEvent);
626 // Function to update tree: download value of opened subkey
627 autoId = 0;
628 $scope.updateTree = function(value, node, level, over, currentQuery, count) {
629 var query, scheme, tmp;
630 $scope.waiting = true;
631 // Query scheme selection:
632
633 // - if defined above
634 // - _updateTime must be displayed as startTime
635 // - default to _whatToTrace scheme
636 scheme = schemes[$scope.type] ? schemes[$scope.type] : $scope.type === '_updateTime' ? schemes._startTime : schemes._whatToTrace;
637 // Build query using schemes
638 query = scheme[level]($scope.type, value, currentQuery);
639 // If number of session exceeds "max" and overScheme exists, call it
640 if (count > max && overScheme[$scope.type]) {
641 if (tmp = overScheme[$scope.type]($scope.type, value, level, over, currentQuery)) {
642 over++;
643 query = tmp;
644 level = level - 1;
645 } else {
646 over = 0;
647 }
648 } else {
649 over = 0;
650 }
651 // Launch HTTP query
652 $http.get(`${scriptname}sessions/${sessionType}?${query}`).then(function(response) {
653 var data, i, len, n, ref;
654 data = response.data;
655 if (data.result) {
656 for (i = 0; i < data.values.length; i++) {
657 n = data.values[i];
658 autoId++;
659 n.id = `node${autoId}`;
660 if (level < scheme.length - 1) {
661 n.nodes = [];
662 n.level = level + 1;
663 n.query = query;
664 n.over = over;
665 // Date display in tree
666 if ($scope.type.match(/^(?:start|update)Time$/)) {
667 // 12 digits -> 12:34
668 n.title = n.value.replace(/^(\d{8})(\d{2})(\d{2})$/,
669 // 11 digits -> 12:30
670 '$2:$3').replace(/^(\d{8})(\d{2})(\d)$/,
671 // 10 digits -> 12h
672 '$2:$30').replace(/^(\d{8})(\d{2})$/,
673 // 8 digits -> 2016-03-15
674 '$2h').replace(/^(\d{4})(\d{2})(\d{2})/,
675 '$1-$2-$3');
676 }
677 }
678 node.push(n);
679 }
680 if (value === '') {
681 $scope.total = data.total;
682 }
683 }
684 return $scope.waiting = false;
685 },
686 function(resp) {
687 return $scope.waiting = false;
688 });
689 // Highlight current selection
690 console.debug("Selection", sessionType);
691 $scope.navssoStyle = {
692 color: '#777'
693 };
694 $scope.offlineStyle = {
695 color: '#777'
696 };
697 $scope.persistentStyle = {
698 color: '#777'
699 };
700 if (sessionType === 'global') {
701 $scope.navssoStyle = {
702 color: '#333'
703 };
704 }
705 if (sessionType === 'offline') {
706 $scope.offlineStyle = {
707 color: '#333'
708 };
709 }
710 if (sessionType === 'persistent') {
711 return $scope.persistentStyle = {
712 color: '#333'
713 };
714 }
715 };
716 // Intialization function
717 // Simply set $scope.waiting to false during $translator and tree root
718 // initialization
719 $scope.init = function() {
720 $scope.waiting = true;
721 $scope.data = [];
722 $scope.currentScope = null;
723 $scope.currentSession = null;
724 $q.all([$translator.init($scope.lang),
725 $scope.updateTree('',
726 $scope.data,
727 0,
728 0)
729 ]).then(function() {
730 return $scope.waiting = false;
731 },
732 function(resp) {
733 return $scope.waiting = false;
734 });
735 // Colorized link
736 $scope.activeModule = "sessions";
737 return $scope.myStyle = {
738 color: '#ffb84d'
739 };
740 };
741 // Query scheme initialization
742 // Default to '_whatToTrace'
743 c = $location.path().match(/^\/(\w+)/);
744 return $scope.type = c ? c[1] : '_whatToTrace';
745 }
746 ]);