Debian Codegraph @

public/js/users.js

raw symbols SCIP
1 /**
2 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
3 * Copyright (C) 2023-2025 Aleksey Andreev (liuch)
4 *
5 * Available at:
6 * https://github.com/liuch/dmarc-srg
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the Free
10 * Software Foundation, either version 3 of the License.
11 *
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 const User = { name: null, level: null, auth_type: null };
22
23 class UserList {
24 constructor() {
25 this._page = null;
26 this._table = null;
27 this._scroll = null;
28 this._element = document.getElementById("main-block");
29 this._sort = { column: "name", direction: "ascent" };
30 }
31
32 display() {
33 this._make_page_container();
34 this._make_scroll_container();
35 this._make_table();
36 this._scroll.append(this._table.element());
37 this._page.append(this._scroll);
38 this._element.appendChild(this._page);
39 this._table.focus();
40 }
41
42 update() {
43 this._fetch_list();
44 }
45
46 title() {
47 return "User List";
48 }
49
50 _fetch_list() {
51 this._table.display_status("wait");
52 return window.fetch("users.php", {
53 method: "GET",
54 cache: "no-store",
55 headers: HTTP_HEADERS,
56 credentials: "same-origin"
57 }).then(resp => {
58 if (!resp.ok) throw new Error("Failed to fetch the user list");
59 return resp.json();
60 }).then(data => {
61 this._table.display_status(null);
62 Common.checkResult(data);
63 const d = { more: data.more };
64 d.rows = data.users.map(it => this._make_row_data(it));
65 d.rows.push(new NewUserRow(5));
66 const fr = new UserFrame(d, this._table.last_row_index() + 1);
67 this._table.clear();
68 this._table.add_frame(fr);
69 if (this._sort.column) this._table.sort(this._sort.column, this._sort.direction);
70 this._table.focus();
71 }).catch(err => {
72 Common.displayError(err);
73 this._table.display_status("error", err.message || null);
74 });
75 }
76
77 _make_page_container() {
78 this._page = document.createElement("div");
79 this._page.classList.add("page-container");
80 }
81
82 _make_scroll_container() {
83 this._scroll = document.createElement("div");
84 this._scroll.classList.add("table-wrapper");
85 }
86
87 _make_table() {
88 this._table = new ITable({
89 class: "main-table users",
90 onclick: row => {
91 const data = row.userdata();
92 if (data) this._display_edit_dialog(data);
93 },
94 onsort: col => {
95 const dir = col.sorted() && "toggle" || "ascent";
96 this._table.set_sorted(col.name(), dir);
97 this._table.sort(col.name(), col.sorted());
98 this._sort.column = col.name();
99 this._sort.direction = col.sorted();
100 this._table.focus();
101 },
102 onfocus: el => scroll_to_element(el, this._scroll)
103 });
104 [
105 { content: "", sortable: true, name: "status", class: "cell-status" },
106 { content: "Name", sortable: true, name: "name" },
107 { content: "Access level", sortable: false, name: "level" },
108 { content: "Domains", sortable: false, name: "domains" },
109 { content: "Updated", sortable: true, name: "date" },
110 ].forEach(col => {
111 const c = this._table.add_column(col);
112 if (c.name() === this._sort.column) c.sort(this._sort.direction);
113 });
114 }
115
116 _make_row_data(d) {
117 const rd = { cells: [], userdata: d.name };
118 rd.cells.push(new UserStatusCell(d.enabled));
119 rd.cells.push({ content: d.name, class: "user-name" });
120 rd.cells.push({ content: d.level, class: "user-level" });
121 rd.cells.push({ content: d.domains });
122 rd.cells.push(new UserTimeCell(new Date(d.updated_time)));
123 return rd;
124 }
125
126 _display_edit_dialog(username) {
127 const dlg_par = {};
128 if (username === "*new") {
129 dlg_par["new"] = true;
130 }
131 else {
132 dlg_par.name = username;
133 dlg_par.minimal = User.level !== "admin";
134 }
135 const dlg = new UserEditDialog(dlg_par);
136 this._element.appendChild(dlg.element());
137 dlg.show().then(d => {
138 if (d) this.update();
139 }).finally(() => {
140 dlg.element().remove();
141 this._table.focus();
142 });
143 }
144 }
145
146 class UserStatusCell extends ITableCell {
147 constructor(is_enabled, props) {
148 props ||= {};
149 const ca = (props.class || "").split(" ");
150 ca.push(is_enabled && "state-green" || "state-gray");
151 props.class = ca.filter(s => s.length > 0).join(" ");
152 super(is_enabled, props);
153 }
154
155 value(target) {
156 if (target === "dom") {
157 const div = document.createElement("div");
158 div.classList.add("state-background", "status-indicator");
159 if (!this._title) div.title = this._content && "enabled" || "disabled";
160 return div;
161 }
162 return this._content;
163 }
164 }
165
166 class UserTimeCell extends ITableCell {
167 value(target) {
168 if (target === "dom") return this._content && this._content.toUIString() || "";
169 if (target === "sort") return this._content && this._content.valueOf() || 0;
170 super.value(target);
171 }
172 }
173
174 class NewUserRow extends ITableRow {
175 constructor(col_cnt) {
176 super({
177 userdata: "*new",
178 cells: []
179 });
180 this._col_cnt = col_cnt;
181 }
182
183 element() {
184 if (!this._element) {
185 super.element();
186 this._element.classList.add("colspanned", "virtual-item");
187 for (let i = 0; i < this._col_cnt; ++i) {
188 const cell = document.createElement("div");
189 cell.classList.add("table-cell");
190 cell.textContent = !i && "New user" || "\u00A0";
191 this._element.appendChild(cell);
192 }
193 }
194 return this._element;
195 }
196 }
197
198 class UserFrame extends ITableFrame {
199 sort(col_idx, direction) {
200 this._sort_dir = (direction === "ascent" && 1) || (direction === "descent" && 2) || 0;
201 super.sort(col_idx, direction);
202 }
203
204 _compare_cells(c1, c2) {
205 if (!c1) {
206 return this._sort_dir === 2;
207 }
208 if (!c2) {
209 return this._sort_dir === 1;
210 }
211 return super._compare_cells(c1, c2);
212 }
213 }
214
215 class UserEditDialog extends VerticalDialog {
216 constructor(params) {
217 params ||= {}
218 const ba = [];
219 if (!params.minimal) ba.push("save");
220 ba.push("close");
221 let title = null;
222 if (!params["new"]) {
223 title = "User settings";
224 if (!params.minimal) ba.splice(1, 0, "delete");
225 } else {
226 title = "New user";
227 }
228 super({ title: title, buttons: ba });
229 this._data = params;
230 this._name_el = null;
231 this._alvl_el = null;
232 this._actv_el = null;
233 this._doms_el = null;
234 this._pasw_el = null;
235 this._c_tm_el = null;
236 this._u_tm_el = null;
237 this._domains = new Set();
238 this._fetched = false;
239 }
240
241 _gen_content() {
242 const min = this._data.minimal;
243
244 // Name
245 const nm = document.createElement("input");
246 nm.type = "text";
247 if (!this._data["new"]) {
248 nm.value = this._data.name;
249 nm.disabled = true;
250 }
251 nm.required = true;
252 nm.maxLength = 32;
253 this._insert_input_row("Name", nm);
254 this._name_el = nm;
255
256 // Level
257 const lv = document.createElement("select");
258 [ "Manager", "User" ].forEach(val => {
259 const op = document.createElement("option");
260 op.value = val.toLowerCase();
261 op.textContent = val;
262 lv.appendChild(op);
263 });
264 lv.required = true;
265 lv.value = "user";
266 if (min) lv.disabled = true;
267 this._insert_input_row("Level", lv);
268 this._alvl_el = lv;
269
270 if (!min) {
271 // Enabled
272 const en = document.createElement("select");
273 [ "Yes", "No" ].forEach(val => {
274 const op = document.createElement("option");
275 op.value = val.toLowerCase();
276 op.textContent = val;
277 en.appendChild(op);
278 });
279 en.required = true;
280 this._insert_input_row("Enabled", en);
281 this._actv_el = en;
282
283 // Domains
284 const dm = document.createElement("multi-select");
285 dm.setAttribute("placeholder", "No domains");
286 dm.setLabel("Domains");
287 this._insert_input_row("Domains", dm);
288 this._doms_el = dm;
289 }
290
291 // Password
292 const sp = document.createElement("span");
293 sp.classList.add("value");
294 sp.textContent = "None ";
295 if (!this._data["new"]) {
296 const pw = document.createElement("a");
297 pw.href = "";
298 pw.textContent = "[ Change ]";
299 sp.appendChild(pw);
300 pw.addEventListener("click", event => {
301 event.preventDefault();
302 this._display_password_dialog(pw);
303 });
304 }
305 this._insert_input_row("Password", sp);
306 this._pasw_el = sp;
307
308 // Created
309 const ct = document.createElement("input");
310 ct.type = "text";
311 ct.value = "n/a";
312 ct.disabled = true;
313 this._insert_input_row("Created", ct);
314 this._c_tm_el = ct;
315
316 // Updated
317 const ut = document.createElement("input");
318 ut.type = "text";
319 ut.value = "n/a";
320 ut.disabled = true;
321 this._insert_input_row("Updated", ut);
322 this._u_tm_el = ut;
323
324
325 this._inputs.addEventListener("input", event => this._input_handler(event));
326 this._doms_el && this._doms_el.addEventListener("change", event => this._input_handler(event));
327
328 if (!this._fetched) this._fetch_data();
329 }
330
331 _input_handler(event) {
332 if (!this._fetched) return;
333
334 let dis = true;
335 if (this._name_el.value.trim() !== "" && this._alvl_el.value !== "") {
336 if (this._alvl_el.dataset.server !== this._alvl_el.value) {
337 dis = false;
338 } else if (this._actv_el && this._actv_el.dataset.server !== this._actv_el.value) {
339 dis = false;
340 } else if (this._doms_el) {
341 const dlist = this._doms_el.getValues();
342 if (dlist.length != this._domains.size || !dlist.every(d => this._domains.has(d))) {
343 dis = false;
344
345 }
346 }
347 }
348 this._buttons[1].disabled = dis;
349 }
350
351 _add_button(container, text, type) {
352 let dsbl = false;
353 let lstn = null;
354 switch (type) {
355 case "save":
356 text = "Save";
357 dsbl = true;
358 lstn = this._save.bind(this);
359 break;
360 case "delete":
361 text = "Delete";
362 lstn = this._confirm_delete.bind(this);
363 break;
364 default:
365 super._add_button(container, text, type);
366 return;
367 }
368 const btn = document.createElement("button");
369 btn.type = "button";
370 btn.disabled = dsbl;
371 btn.textContent = text;
372 btn.addEventListener("click", lstn);
373 container.appendChild(btn);
374 this._buttons.push(btn);
375 }
376
377 _fetch_data() {
378 this._enable_ui(false);
379 this.display_status("wait", "Getting data...");
380 const url = new URL("users.php", document.location);
381 url.searchParams.set("user", this._data.name || "");
382
383 return window.fetch(url, {
384 method: "GET",
385 cache: "no-store",
386 headers: HTTP_HEADERS,
387 credentials: "same-origin"
388 }).then(resp => {
389 if (!resp.ok) throw new Error("Failed to fetch data");
390 return resp.json();
391 }).then(data => {
392 this._fetched = true;
393 Common.checkResult(data);
394 [ "created_time", "updated_time" ].forEach(it => {
395 data[it] && (data[it] = new Date(data[it]))
396 });
397 this._update_ui(data);
398 this._enable_ui(true);
399 }).catch(err => {
400 Common.displayError(err);
401 this.display_status("error", err.message);
402 }).finally(() => {
403 this.display_status("wait", null);
404 });
405 }
406
407 _enable_ui(en) {
408 this._name_el.disabled = !en || !this._data["new"];
409 this._alvl_el.disabled = !en || this._data.minimal;
410 if (this._actv_el) this._actv_el.disabled = !en;
411 if (this._doms_el) this._doms_el.disabled = !en;
412 for (let i = 2; i < this._buttons.length - 1; ++i) {
413 this._buttons[i].disabled = !en;
414 }
415 this.focus();
416 }
417
418 _update_ui(data) {
419 if (data.level) this._set_option_value(this._alvl_el, data.level);
420 if (this._actv_el) this._set_option_value(this._actv_el, (data.enabled || this._data["new"]) ? "yes" : "no");
421 if (this._doms_el) {
422 this._domains = new Set(data.domains.assigned);
423 data.domains.available.forEach(d => this._doms_el.appendItem(d));
424 if (data.domains.assigned) this._doms_el.setValues(data.domains.assigned);
425 }
426 if (data.password) this._set_password_yes();
427 this._c_tm_el.value = data.created_time && data.created_time.toUIString() || "n/a";
428 this._u_tm_el.value = data.updated_time && data.updated_time.toUIString() || "n/a";
429 }
430
431 _set_password_yes() {
432 this._pasw_el.childNodes[0].textContent = "Yes ";
433 }
434
435 _set_option_value(el, data) {
436 let val = "";
437 for (let i = 0; i < el.options.length; ++i) {
438 const op = el.options[i];
439 if (data === op.value) {
440 op.setAttribute("selected", "");
441 val = op.value;
442 }
443 else {
444 op.removeAttribute("selected");
445 }
446 }
447 el.value = val;
448 el.dataset.server = val;
449 }
450
451 _save() {
452 this._enable_ui(false);
453 this.display_status("wait", "Sending data to the server...");
454
455 const body = {};
456 body.name = this._data["new"] && this._name_el.value || this._data.name;
457 body.level = this._alvl_el.value;
458 body.enabled = this._actv_el && this._actv_el.value === "yes";
459 body.action = this._data["new"] && "add" || "update";
460 if (this._doms_el) {
461 const dlist = this._doms_el.getValues();
462 if (this._domains.size != dlist.length || dlist.some(d => !this._domains.has(d))) {
463 body.domains = dlist;
464 }
465 }
466
467 window.fetch("users.php", {
468 method: "POST",
469 cache: "no-store",
470 headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
471 credentials: "same-origin",
472 body: JSON.stringify(body)
473 }).then(resp => {
474 if (!resp.ok)
475 throw new Error("Failed to " + (body.new && "add" || "update") + " the user data");
476 return resp.json();
477 }).then(data => {
478 Common.checkResult(data);
479 this._result = body;
480 this.hide();
481 Notification.add({
482 text: `The user ${body.name} successfully ` + (body.action === "add" && "added" || "updated")
483 });
484 }).catch(err => {
485 Common.displayError(err);
486 this.display_status("error", err.message);
487 }).finally(() => {
488 this.display_status("wait", null);
489 this._enable_ui(true);
490 });
491 }
492
493 _confirm_delete() {
494 if (confirm("Are sure you want to delete this user?")) this._delete();
495 }
496
497 _delete() {
498 this._enable_ui(false);
499 this.display_status("wait", "Sending a request to the server...");
500
501 const body = { name: this._data.name, action: "delete" };
502 window.fetch("users.php", {
503 method: "POST",
504 cache: "no-store",
505 headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
506 credentials: "same-origin",
507 body: JSON.stringify(body)
508 }).then(resp => {
509 if (!resp.ok) throw new Error("Failed to delete the user");
510 return resp.json();
511 }).then(data => {
512 Common.checkResult(data);
513 this._result = data;
514 this.hide();
515 Notification.add({ text: `The user ${body.name} successfully removed` });
516 }).catch(err => {
517 Common.displayError(err);
518 this.display_status("error", err.message);
519 }).finally(() => {
520 this.display_status("wait", null);
521 this._enable_ui(true);
522 });
523 }
524
525 _display_password_dialog(source_el) {
526 const dlg = new PasswordDialog({
527 username: this._data.name,
528 current_password: this._data.name === User.name
529 });
530 this._element.classList.add("hidden");
531 document.getElementById("main-block").appendChild(dlg.element());
532 dlg.show().then(d => {
533 if (d) this._set_password_yes();
534 }).finally(() => {
535 dlg.element().remove();
536 this._element.classList.remove("hidden");
537 source_el.focus();
538 });
539 }
540 }
541
542 class PasswordDialog extends VerticalDialog {
543 constructor(params) {
544 super({ title: `Password change [${params.username}]`, buttons: [ "apply", "cancel" ] });
545 this._data = params;
546 this._apl_bt = null;
547 this._pw_cur = null;
548 this._pw_nw1 = null;
549 this._pw_nw2 = null;
550 }
551
552 _gen_content() {
553 if (this._data.current_password) {
554 const pw_cur = document.createElement("input");
555 pw_cur.type = "password";
556 pw_cur.required = true;
557 this._insert_input_row("Current password", pw_cur);
558 this._pw_cur = pw_cur;
559 }
560
561 const pw_nw1 = document.createElement("input");
562 pw_nw1.type = "password";
563 pw_nw1.required = true;
564 this._insert_input_row("New password", pw_nw1);
565 this._pw_nw1 = pw_nw1;
566
567 const pw_nw2 = document.createElement("input");
568 pw_nw2.type = "password";
569 pw_nw2.required = true;
570 this._insert_input_row("Confirm password", pw_nw2);
571 this._pw_nw2 = pw_nw2;
572
573 this._inputs.addEventListener("input", event => {
574 this._apl_bt.disabled = [ this._pw_cur, this._pw_nw1, this._pw_nw2 ].some(el => {
575 return el && el.value === "";
576 });
577 });
578 }
579
580 _add_button(c, t, type) {
581 super._add_button(c, t, type);
582 if (type === "submit") {
583 this._apl_bt = this._buttons[this._buttons.length - 1];
584 this._apl_bt.disabled = true;
585 }
586 }
587
588 _submit() {
589 if (this._pw_nw1.value !== this._pw_nw2.value) {
590 this.display_status("error", "New password and confirm password don't match");
591 this._pw_nw1.focus();
592 return;
593 }
594
595 this.display_status("wait", "Updating the password...");
596 this._enable_ui(false);
597
598 const body = {
599 name: this._data.username,
600 action: "set_password",
601 new_password: this._pw_nw1.value
602 };
603 if (this._pw_cur) body.password = this._pw_cur.value;
604 window.fetch("users.php", {
605 method: "POST",
606 cache: "no-store",
607 headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
608 credentials: "same-origin",
609 body: JSON.stringify(body)
610 }).then(resp => {
611 if (!resp.ok)
612 throw new Error("Failed to " + (body.new && "add" || "update") + " the user data");
613 return resp.json();
614 }).then(data => {
615 Common.checkResult(data);
616 this._result = true;
617 this.hide();
618 Notification.add({ text: "The password has been successfully updated" });
619 }).catch(err => {
620 Common.displayError(err);
621 this.display_status("error", err.message);
622 }).finally(() => {
623 this.display_status("wait", null);
624 this._enable_ui(true);
625 });
626 }
627
628 _enable_ui(en) {
629 if (this._pw_cur) this._pw_cur.disabled = !en;
630 this._pw_nw1.disabled = !en;
631 this._pw_nw2.disabled = !en;
632 this.focus();
633 }
634 }