Files
Chronos/src/Titano.Server/Admin/web/pages/users.js
T
Claude a2713ab08b fix(admin-web): layout, accessibility, right-to-left, plurals and dark theme
Tables become ARIA tables laid out as subgrids that drop secondary columns
in narrow panels; stat tiles stay on one row; charts are named and keep
their axis labels inside; paths, templates and logs stay left to right;
counts use plural keys; the panel follows the system theme with a toggle.
Own account: Change password instead of Reset password.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-06 20:57:18 +00:00

316 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset accounts, or to
// change one's own password (a reset of one's own account would end this session and lose the temporary password).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText, emptyState, markInvalid, clearInvalid, redraw, focusPlace, restoreFocus } from "../ui.js";
import { icons } from "../icons.js";
const ROLES = ["viewer", "uploader", "editor", "admin"];
const TB = 1e12;
const RENDER_NODE = 32;
/** API error codes that belong to one field of the side forms. */
const FIELD_ERRORS = { invalid_username: "username", username_taken: "username", weak_password: "password", wrong_password: "current", same_password: "next" };
export async function render(root, { api, info, setMeta, actions }) {
let users = [];
let filter = "";
let freeBytes = 0;
let tokenDays = 30;
let opener = null;
actions.innerHTML = `
<input class="input search" type="search" id="search" dir="auto" data-i18n-placeholder="Admin.Users.Search" data-i18n-title="Admin.Users.Search.Tip" aria-label="${attr(t("Admin.Users.Search"))}">
<button class="btn primary" id="new" data-i18n="Admin.Users.New" data-i18n-title="Admin.Users.New.Tip"></button>`;
applyStrings(actions);
const search = actions.querySelector("#search");
search.addEventListener("input", () => {
filter = search.value.trim().toLowerCase();
drawTable();
});
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<div class="panel flush">
<div class="table users" role="table" aria-label="${attr(t("Admin.Nav.Users"))}">
<div class="thead" role="row">
<span role="columnheader" data-i18n="Admin.Users.User"></span><span role="columnheader" data-i18n="Admin.Users.Role"></span>
<span role="columnheader" class="col-quota" data-i18n="Admin.Users.Quota"></span><span role="columnheader" class="col-seen" data-i18n="Admin.Users.LastSeen"></span>
<span role="columnheader" class="col-uploads end" data-i18n="Admin.Users.Uploads"></span><span role="columnheader" class="col-status" data-i18n="Admin.Users.Status"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
<div class="table-foot"><span id="policy" class="muted"></span><span class="spacer"></span>
<a href="#/logs?view=signins" data-i18n="Admin.Users.SignInLog" data-i18n-title="Admin.Users.SignInLog.Tip"></a></div>
</div>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
const side = root.querySelector("#side");
side.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
e.preventDefault();
closeSide();
}
});
async function load() {
try {
const [list, stats, settings] = await Promise.all([
api.get("/api/v1/users"),
api.get("/api/v1/archive/stats").catch(() => null),
api.get("/api/v1/server/settings").catch(() => null),
]);
users = list;
freeBytes = stats?.freeBytes ?? 0;
tokenDays = settings?.tokenLifetimeDays ?? tokenDays;
} catch (err) {
toast(errorText(err), true);
return;
}
const active = users.filter((u) => !u.user.disabled).length;
setMeta(`${plural("Admin.Users.Accounts", users.length)} · ${plural("Admin.Users.ActiveCount", active)}`);
root.querySelector("#policy").textContent =
`${plural("Admin.Users.PasswordPolicy", info?.limits?.passwordMinLength ?? 10)} · ${plural("Admin.Users.TokenPolicy", tokenDays)}`;
drawTable();
}
function drawTable() {
const host = root.querySelector("#rows");
redraw(host, () => {
const rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter));
host.innerHTML = rows.map(rowHtml).join("") || `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Users.Empty",
`<button class="btn small" id="clear" data-i18n="Admin.Users.ClearSearch" data-i18n-title="Admin.Users.ClearSearch.Tip"></button>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => {
const row = users.find((u) => u.user.id === button.closest("[data-key]").dataset.key);
act(button.dataset.act, row.user);
}));
host.querySelector("#clear")?.addEventListener("click", () => {
search.value = "";
filter = "";
drawTable();
search.focus();
});
}
function rowHtml(row) {
const u = row.user;
const own = u.id === api.user().id;
const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null]
.filter(Boolean).join(" · ");
const quotaText = t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes));
const quota = u.quotaBytes > 0
? `<div class="progress-cell">${bar(u.usedBytes / u.quotaBytes, u.disabled)}<span class="num ellipsis" title="${attr(quotaText)}">${escapeHtml(quotaText)}</span></div>`
: `<span class="muted num">${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}</span>`;
const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—";
const button = (act, key, extra = "") => `<button class="btn small${extra}" data-act="${act}" data-i18n="Admin.Users.${key}" data-i18n-title="Admin.Users.${key}.Tip"></button>`;
const buttons = u.disabled
? button("enable", "Enable") + button("delete", "Delete", " destructive")
: button("edit", "Edit") + (own ? button("password", "ChangePassword") : button("reset", "Reset") + button("disable", "Disable"));
return `
<div class="row${u.disabled ? " dim" : ""}" role="row" data-key="${attr(u.id)}">
<span class="person" role="cell"><span class="avatar ${attr(u.role)}" aria-hidden="true">${escapeHtml(u.username.slice(0, 1).toUpperCase())}</span>
<span class="stack"><strong class="ellipsis" dir="auto" title="${attr(u.username)}">${escapeHtml(u.username)}</strong>
<small dir="auto" title="${attr(subtitle)}">${escapeHtml(subtitle)}</small></span></span>
<span class="ellipsis" role="cell" data-i18n="Admin.Role.${cap(u.role)}"></span>
<span class="col-quota" role="cell">${quota}</span>
<span class="col-seen ellipsis" role="cell" dir="auto" title="${attr(seen)}">${escapeHtml(seen)}</span>
<span class="col-uploads num end" role="cell">${formatNumber(row.uploadsLast30Days)}</span>
<span class="col-status state ${u.disabled ? "cancelled" : "done"}" role="cell"><span aria-hidden="true">${u.disabled ? "○" : "●"}</span>
<span data-i18n="${u.disabled ? "Admin.Users.Disabled" : "Admin.Users.Active"}"></span></span>
<span class="row-actions" role="cell">${buttons}</span>
</div>`;
}
async function act(action, user) {
try {
if (action === "edit") return openForm(user);
if (action === "password") return openPasswordForm();
if (action === "reset") {
showPassword(await api.post(`/api/v1/users/${user.id}/reset-password`, {}));
} else if (action === "disable" || action === "enable") {
await api.patch(`/api/v1/users/${user.id}`, { disabled: action === "disable" });
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Users.DeleteTitle", user.username),
body: t("Admin.Users.DeleteBody"),
confirm: t("Admin.Users.DeleteConfirm"),
confirmTip: t("Admin.Users.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: user.username,
});
if (!confirmed) return;
await api.del(`/api/v1/users/${user.id}`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
/** Shows the side panel, remembering which control opened it so closing returns the keyboard there. */
function openSide(html) {
if (side.hidden) {
const scope = actions.contains(document.activeElement) ? actions : root;
opener = { scope, place: focusPlace(scope) };
}
side.hidden = false;
side.innerHTML = html;
applyStrings(side);
side.querySelector("#close").addEventListener("click", closeSide);
}
function closeSide() {
side.hidden = true;
side.innerHTML = "";
if (opener) restoreFocus(opener.scope, opener.place);
opener = null;
}
function openForm(user) {
const editing = user !== null;
const quotaTb = editing && user.quotaBytes > 0 ? +(user.quotaBytes / TB).toFixed(3) : 0;
const renderNode = editing ? (user.permissions & RENDER_NODE) !== 0 : false;
openSide(`
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Users.EditTitle" : "Admin.Users.New"}"></h2>
<label><span data-i18n="Admin.Users.Username"></span>
<input class="input" name="username" required autocomplete="off" dir="auto" value="${attr(user?.username ?? "")}" ${editing ? "disabled" : ""} data-i18n-title="Admin.Users.Username.Tip"></label>
<label><span data-i18n="Admin.Users.DisplayName"></span>
<input class="input" name="displayName" autocomplete="off" dir="auto" value="${attr(user?.displayName ?? "")}" data-i18n-title="Admin.Users.DisplayName.Tip"></label>
<fieldset><legend data-i18n="Admin.Users.Role"></legend>
${ROLES.map((r) => `<label class="check"><input type="radio" name="role" value="${r}" ${(user?.role ?? "editor") === r ? "checked" : ""} data-i18n-title="Admin.Users.Role.${cap(r)}.Tip"><span data-i18n="Admin.Role.${cap(r)}"></span></label>`).join("")}
</fieldset>
<label><span data-i18n="Admin.Users.Quota"></span>
<span class="inline"><input class="input narrow num" name="quota" type="number" min="0" step="0.1" value="${quotaTb}" data-i18n-title="Admin.Users.Quota.Tip"><span>TB</span>
<small class="muted">${escapeHtml(t("Admin.Users.FreeOnServer", formatBytes(freeBytes)))}</small></span></label>
${editing ? "" : `
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" name="password" autocomplete="off" spellcheck="false" dir="ltr" value="${attr(generatePassword())}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="regenerate" data-i18n-title="Admin.Users.Regenerate.Tip">${icons.refresh}</button></span></label>
<label class="check"><input type="checkbox" checked disabled data-i18n-title="Admin.Users.MustChangeFlag.Tip"><span data-i18n="Admin.Users.MustChangeFlag"></span></label>`}
<label class="check"><input type="checkbox" name="renderNode" ${renderNode ? "checked" : ""} data-i18n-title="Admin.Users.RenderNode.Tip"><span data-i18n="Admin.Users.RenderNode"></span></label>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Users.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Users.Create.Tip"}"></button>
</div>
</form>`);
const form = side.querySelector("form");
side.querySelector("#regenerate")?.addEventListener("click", () => {
form.elements.password.value = generatePassword();
clearInvalid(form.elements.password);
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB);
try {
if (editing) {
await api.patch(`/api/v1/users/${user.id}`, {
displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on",
});
closeSide();
} else {
showPassword(await api.post("/api/v1/users", {
username: String(data.get("username")).trim(), displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes,
password: String(data.get("password")), allowRenderNode: data.get("renderNode") === "on",
}));
}
await load();
} catch (err) {
fieldError(form, err, err.details === "quotaBytes" ? "quota" : FIELD_ERRORS[err.code]);
}
});
form.querySelector("input:not([disabled])").focus();
}
/** The caller's own password, changed with the current one; this session stays signed in. */
function openPasswordForm() {
const field = (name, key, complete) => `<label><span data-i18n="Admin.Password.${key}"></span>
<input class="input" name="${name}" type="password" autocomplete="${complete}" required data-i18n-title="Admin.Password.${key}.Tip"></label>`;
openSide(`
<form class="form" novalidate>
<h2 data-i18n="Admin.Password.Title"></h2>
${field("current", "Current", "current-password")}${field("next", "New", "new-password")}${field("repeat", "Repeat", "new-password")}
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="Admin.Password.Save" data-i18n-title="Admin.Users.SavePassword.Tip"></button>
</div>
</form>`);
const form = side.querySelector("form");
form.addEventListener("submit", async (e) => {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
if (data.get("next") !== data.get("repeat")) {
fieldError(form, { message: t("Admin.Password.Mismatch"), status: 400 }, "repeat");
return;
}
try {
await api.changePassword(String(data.get("current")), String(data.get("next")));
closeSide();
toast(t("Admin.Users.PasswordChanged"));
} catch (err) {
fieldError(form, err, FIELD_ERRORS[err.code]);
}
});
form.querySelector("input").focus();
}
/** The one-time password of a new or reset account, shown once in the side panel. */
function showPassword(result) {
openSide(`
<div class="form">
<h2 dir="auto">${escapeHtml(result.user.username)}</h2>
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" readonly dir="ltr" value="${attr(result.temporaryPassword)}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="copy" data-i18n-title="Admin.Users.Copy.Tip">${icons.copy}</button></span></label>
<div class="buttons"><button class="btn" type="button" id="close" data-i18n="Admin.Common.Close" data-i18n-title="Admin.Common.Close.Tip"></button></div>
</div>`);
const input = side.querySelector("input");
side.querySelector("#copy").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(result.temporaryPassword);
toast(t("Admin.Users.Copied"));
} catch {
input.select();
}
});
input.focus();
input.select();
}
await load();
}
/** An API failure on a side form: the field it concerns gets the error border, the message and the focus; a toast announces it. */
function fieldError(form, err, name) {
const message = err.code === "username_taken" ? t("Admin.Users.Taken") : errorText(err);
const field = name ? form.elements[name] : null;
if (field) {
markInvalid(field, message);
field.focus();
}
toast(message, true);
}
/** Three groups of four unambiguous characters, like the server's own temporary passwords. */
function generatePassword() {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
const chars = [];
while (chars.length < 12) {
// Bytes at or above 248 (8 × 31) are skipped so every character is equally likely.
for (const b of crypto.getRandomValues(new Uint8Array(16))) {
if (b < 248 && chars.length < 12) chars.push(alphabet[b % alphabet.length]);
}
}
return `${chars.slice(0, 4).join("")}-${chars.slice(4, 8).join("")}-${chars.slice(8).join("")}`;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}