From 844ed006cc7aa966f00a5016f5a3b92af79e736c Mon Sep 17 00:00:00 2001 From: Gitea OpenCode Agent Date: Thu, 15 Oct 2026 12:36:28 +0000 Subject: [PATCH] Fix issue #51: Error when opening manage acconuts --- backend/src/routes/user.js | 109 +++++++ .../windows/AccountManagementWindow.vue | 289 ++++++++++++++++++ .../app/components/windows/SettingsWindow.vue | 18 +- frontend/app/services/WindowDefinitions.js | 6 + frontend/i18n/locales/ca/settings.json | 26 +- frontend/i18n/locales/ca/windows.json | 1 + frontend/i18n/locales/en/settings.json | 26 +- frontend/i18n/locales/en/windows.json | 1 + frontend/i18n/locales/es/settings.json | 26 +- frontend/i18n/locales/es/windows.json | 1 + tests/manage-accounts.test.js | 217 +++++++++++++ 11 files changed, 705 insertions(+), 15 deletions(-) create mode 100644 frontend/app/components/windows/AccountManagementWindow.vue create mode 100644 tests/manage-accounts.test.js diff --git a/backend/src/routes/user.js b/backend/src/routes/user.js index 8fd8db66..a9bc6aeb 100644 --- a/backend/src/routes/user.js +++ b/backend/src/routes/user.js @@ -193,4 +193,113 @@ router.get('/get-settings', passport.authenticate('jwt', {session: false}), asyn } }); +// -- Account management (the "Manage accounts" window of the site settings) ---- +// /api/user is mounted before the JWT guard, so every route below authenticates +// inline; and only an administrator gets past isAdmin (services/middleware.js). + +router.get('/list', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => { + try { + // No account gets out with its password or an unfinished setup code. + const users = await User.find().select('-password -setupCode').sort({ date: 1 }); + res.json({ status: "ok", users }); + } catch (err) { + console.error(err); + res.json({ status: "error", msg: "errors.internal" }); + } +}); + +// The admin creates the account with the password its user logs in with; the +// setupCode flow above stays as it is, nothing on the frontend completes it. +router.post('/create', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => { + try { + const { name, username, email, password } = req.body; + if (!(name && username && email && password)) { + return res.json({ status: "error", msg: "errors.missing-data" }); + } + + const existingUser = await User.findOne({ + $or: [ + { email: email }, + { username: username } + ] + }); + if (existingUser) { + return res.json({ + status: "error", + msg: "register.errors.email-username-exists" + }); + } + + const salt = await bcrypt.genSalt(10); + let user = new User({ + name: name, + username: username, + email: email, + password: await bcrypt.hash(password, salt) + }); + await user.save(); + res.json({ + status: "ok", + user: { + _id: user._id, + name: user.name, + username: user.username, + email: user.email, + admin: user.admin, + date: user.date + } + }); + } catch (err) { + console.error(err); + res.json({ status: "error", msg: "errors.internal" }); + } +}); + +router.post('/set-admin', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => { + try { + const { id, admin } = req.body; + if (!id || typeof admin !== 'boolean') { + return res.json({ status: "error", msg: "errors.missing-data" }); + } + + // Switching one's own rights off could leave an instance with nobody who + // can manage accounts at all, so the row for yourself stays closed. + if (String(req.user._id) === String(id)) { + return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-admin" }); + } + + const user = await User.findOne({ _id: id }); + if (!user) return res.json({ status: "error", msg: "errors.notfound" }); + + user.admin = admin; + await user.save(); + res.json({ status: "ok", user: { _id: user._id, admin: user.admin } }); + } catch (err) { + console.error(err); + res.json({ status: "error", msg: "errors.internal" }); + } +}); + +// Only the account itself goes; what it created stays as it is. +router.post('/delete', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => { + try { + const { id } = req.body; + if (!id) return res.json({ status: "error", msg: "errors.missing-data" }); + + // Same guard as the admin switch: nobody locks themselves out on the way out. + if (String(req.user._id) === String(id)) { + return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-delete" }); + } + + const user = await User.findOne({ _id: id }); + if (!user) return res.json({ status: "error", msg: "errors.notfound" }); + + await user.deleteOne(); + res.json({ status: "ok" }); + } catch (err) { + console.error(err); + res.json({ status: "error", msg: "errors.internal" }); + } +}); + module.exports = router; \ No newline at end of file diff --git a/frontend/app/components/windows/AccountManagementWindow.vue b/frontend/app/components/windows/AccountManagementWindow.vue new file mode 100644 index 00000000..48cc2a3c --- /dev/null +++ b/frontend/app/components/windows/AccountManagementWindow.vue @@ -0,0 +1,289 @@ + + + + + + + diff --git a/frontend/app/components/windows/SettingsWindow.vue b/frontend/app/components/windows/SettingsWindow.vue index 235dcef2..ff9d1890 100644 --- a/frontend/app/components/windows/SettingsWindow.vue +++ b/frontend/app/components/windows/SettingsWindow.vue @@ -80,21 +80,15 @@ onMounted(() => { }); function OpenManageAccounts(){ - ClearWindow('settings'); + ClearWindow({ type: 'settings' }); CreateWindow('account_management', { - type: 'account_management', - title: 'settings.site-administration.manage-accounts.title', - id: 'account-management', + // Back returns to the settings tab this button sits on; CreateWindow leaves + // a window that is already open alone. back: () => { - ClearWindow('account-management') - CreateWindow('settings', { - id: 'settings', - type: 'settings', - title: 'settings.title', - back: () => { ClearWindow('settings'); CreateWindow('main_menu'); } - }); + ClearWindow({ type: 'account_management' }); + CreateWindow('settings'); } - }) + }); } const getLocaleName = (locale) => { diff --git a/frontend/app/services/WindowDefinitions.js b/frontend/app/services/WindowDefinitions.js index 60fb27db..115cc3aa 100644 --- a/frontend/app/services/WindowDefinitions.js +++ b/frontend/app/services/WindowDefinitions.js @@ -34,6 +34,12 @@ const defWindows = { }, movable: true }, + account_management: { + title: 'windows.account-management', + component: () => import('~/components/windows/AccountManagementWindow.vue'), + close: () => ClearWindow({type: 'account_management'}), + movable: true + }, create_campaign: { title: "windows.create-campaign", component: () => import('~/components/windows/CreateCampaignWindow.vue'), diff --git a/frontend/i18n/locales/ca/settings.json b/frontend/i18n/locales/ca/settings.json index 715a1f63..0f654888 100644 --- a/frontend/i18n/locales/ca/settings.json +++ b/frontend/i18n/locales/ca/settings.json @@ -8,6 +8,30 @@ "language": "Idioma" }, "site-administration": { - "manage-accounts": "Gestiona els comptes" + "manage-accounts": "Gestiona els comptes", + "accounts": { + "you": "tu", + "admin": "Administrador", + "make-admin": "Fes-lo administrador", + "remove-admin": "Treu-li l'administrador", + "delete": "Elimina", + "new-account": "Nou compte", + "name": "Nom", + "username": "Nom d'usuari", + "email": "Correu electrònic", + "password": "Contrasenya", + "create": "Crea el compte", + "created": "Compte creat", + "updated": "Compte actualitzat", + "deleted": "Compte eliminat", + "errors": { + "name-empty": "Si us plau, introdueix un nom.", + "username-empty": "Si us plau, introdueix un nom d'usuari.", + "email-empty": "Si us plau, introdueix un correu electrònic vàlid.", + "password-empty": "Si us plau, introdueix una contrasenya.", + "self-admin": "No pots canviar els teus propis privilegis d'administrador.", + "self-delete": "No pots eliminar el teu propi compte." + } + } } } \ No newline at end of file diff --git a/frontend/i18n/locales/ca/windows.json b/frontend/i18n/locales/ca/windows.json index 9a28fcd5..bb86f379 100644 --- a/frontend/i18n/locales/ca/windows.json +++ b/frontend/i18n/locales/ca/windows.json @@ -5,6 +5,7 @@ "example": "Finestra d'exemple", "edit-profile": "Editar perfil", "settings": "Configuració", + "account-management": "Gestió dels comptes", "create-campaign": "Crear campanya", "create-map": "Crear mapa", "map-viewer": "Mapa", diff --git a/frontend/i18n/locales/en/settings.json b/frontend/i18n/locales/en/settings.json index 8be61593..0b2b76c5 100644 --- a/frontend/i18n/locales/en/settings.json +++ b/frontend/i18n/locales/en/settings.json @@ -8,6 +8,30 @@ "language": "Language" }, "site-administration": { - "manage-accounts": "Manage accounts" + "manage-accounts": "Manage accounts", + "accounts": { + "you": "you", + "admin": "Administrator", + "make-admin": "Make administrator", + "remove-admin": "Remove administrator", + "delete": "Delete", + "new-account": "New account", + "name": "Name", + "username": "Username", + "email": "Email", + "password": "Password", + "create": "Create account", + "created": "Account created", + "updated": "Account updated", + "deleted": "Account deleted", + "errors": { + "name-empty": "Please enter a name.", + "username-empty": "Please enter a username.", + "email-empty": "Please enter a valid email address.", + "password-empty": "Please enter a password.", + "self-admin": "You cannot change your own administrator rights.", + "self-delete": "You cannot delete your own account." + } + } } } \ No newline at end of file diff --git a/frontend/i18n/locales/en/windows.json b/frontend/i18n/locales/en/windows.json index 93536f61..e063057f 100644 --- a/frontend/i18n/locales/en/windows.json +++ b/frontend/i18n/locales/en/windows.json @@ -5,6 +5,7 @@ "example": "Example Window", "edit-profile": "Edit Profile", "settings": "Settings", + "account-management": "Manage accounts", "create-campaign": "Create Campaign", "create-map": "Create Map", "map-viewer": "Map", diff --git a/frontend/i18n/locales/es/settings.json b/frontend/i18n/locales/es/settings.json index d292a08e..ef02cf6c 100644 --- a/frontend/i18n/locales/es/settings.json +++ b/frontend/i18n/locales/es/settings.json @@ -8,6 +8,30 @@ "language": "Idioma" }, "site-administration": { - "manage-accounts": "Gestionar cuentas" + "manage-accounts": "Gestionar cuentas", + "accounts": { + "you": "tú", + "admin": "Administrador", + "make-admin": "Nombrar administrador", + "remove-admin": "Quitar administrador", + "delete": "Eliminar", + "new-account": "Nueva cuenta", + "name": "Nombre", + "username": "Nombre de usuario", + "email": "Correo electrónico", + "password": "Contraseña", + "create": "Crear cuenta", + "created": "Cuenta creada", + "updated": "Cuenta actualizada", + "deleted": "Cuenta eliminada", + "errors": { + "name-empty": "Por favor, introduce un nombre.", + "username-empty": "Por favor, introduce un nombre de usuario.", + "email-empty": "Por favor, introduce un correo electrónico válido.", + "password-empty": "Por favor, introduce una contraseña.", + "self-admin": "No puedes cambiar tus propios privilegios de administrador.", + "self-delete": "No puedes eliminar tu propia cuenta." + } + } } } \ No newline at end of file diff --git a/frontend/i18n/locales/es/windows.json b/frontend/i18n/locales/es/windows.json index 98f34193..23e5817e 100644 --- a/frontend/i18n/locales/es/windows.json +++ b/frontend/i18n/locales/es/windows.json @@ -5,6 +5,7 @@ "example": "Ventana de ejemplo", "edit-profile": "Editar perfil", "settings": "Configuración", + "account-management": "Gestionar cuentas", "create-campaign": "Crear campanya", "create-map": "Crear mapa", "map-viewer": "Mapa", diff --git a/tests/manage-accounts.test.js b/tests/manage-accounts.test.js new file mode 100644 index 00000000..183c435a --- /dev/null +++ b/tests/manage-accounts.test.js @@ -0,0 +1,217 @@ +// Tests for "Manage accounts" of Syndria98/dragonroll#51: the button on the settings window's site +// administration tab opened a window type (`account_management`) that was never registered in +// `WindowDefinitions.js`, so `getComponent` dereferenced `defWindows[type].component` on `undefined` — +// `can't access property "component", (intermediate value)[type] is undefined` — instead of opening +// anything. The window is the site administration screen now (list accounts, create one, grant or +// take administrator rights, delete one), guarded on the backend by the `isAdmin` middleware. +// +// Like tests/settings-window.test.js, the window wiring is read from the sources; the window registry +// is also checked against every window type the frontend opens, which is what catches this class of +// bug before the click does. +// +// Run with `npm test` from the repository root, or `node --test tests/`. + +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); + +const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8"); + +const frontendApp = path.join(__dirname, "..", "frontend", "app"); +const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js"); +const settingsWindowSource = read("frontend", "app", "components", "windows", "SettingsWindow.vue"); +const accountsWindowSource = read("frontend", "app", "components", "windows", "AccountManagementWindow.vue"); +const userRouteSource = read("backend", "src", "routes", "user.js"); + +// -- the window registry ------------------------------------------------------- + +// Top-level entries of `defWindows`: every entry sits at 2 spaces, its contents at 4+. +function registryEntries() { + const header = /^ {2}([A-Za-z_]\w*):\s*\{/gm; + const marks = []; + let match; + while ((match = header.exec(windowDefsSource))) marks.push({ type: match[1], index: match.index }); + assert.ok(marks.length > 0, "expected window definitions to register windows"); + + const entries = {}; + marks.forEach((mark, i) => { + const end = i + 1 < marks.length ? marks[i + 1].index : windowDefsSource.length; + entries[mark.type] = windowDefsSource.slice(mark.index, end); + }); + return entries; +} + +function* sourceFiles(dir) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) yield* sourceFiles(full); + else if (/\.(vue|js|ts)$/.test(entry.name)) yield full; + } +} + +test("account_management is a registered window with a component on disk", () => { + const entries = registryEntries(); + const definition = entries["account_management"]; + assert.ok(definition, "account_management must be registered or getComponent opens undefined"); + assert.match(definition, /AccountManagementWindow\.vue/); + const component = path.join(frontendApp, "components", "windows", "AccountManagementWindow.vue"); + assert.ok(fs.existsSync(component), "the window component file must exist"); +}); + +test("no window is opened with a type that is not registered", () => { + const registered = registryEntries(); + // The type is the first string argument of CreateWindow; CreateChildWindow takes a parent + // (GetFirstWindowId('main_menu')-style, a registered type itself) before the type. Data + // objects after it hold strings that mean nothing to the registry, so they stay unmatched. + const createWindow = /CreateWindow\(\s*['"]([a-z_]+)['"]/g; + const createChildWindow = /CreateChildWindow\(\s*(?:GetFirstWindowId\(\s*['"]([a-z_]+)['"]\s*\)|[a-z_]+)\s*,\s*['"]([a-z_]+)['"]/g; + + for (const file of sourceFiles(frontendApp)) { + const source = fs.readFileSync(file, "utf8"); + const found = [...source.matchAll(createWindow), ...source.matchAll(createChildWindow)]; + for (const match of found) { + for (const type of match.slice(1)) { + if (!type) continue; + assert.ok( + registered[type], + `${path.relative(frontendApp, file)} opens '${type}', which WindowDefinitions.js does not define` + ); + } + } + } +}); + +test("every registered window points at a component file that exists", () => { + for (const [type, definition] of Object.entries(registryEntries())) { + const imported = /import\(['"]([^'"]+)['"]\)/.exec(definition)?.[1]; + assert.ok(imported, `${type} must import a component`); + const file = path.join(frontendApp, imported.replace(/^~\//, "")); + assert.ok(fs.existsSync(file), `${type} points at ${imported}, which is not there`); + } +}); + +// -- opening it from the settings window ---------------------------------------- + +const openManageAccounts = /function OpenManageAccounts\(\)\s*\{[\s\S]*?\n\}/.exec(settingsWindowSource)?.[0]; + +test("the settings tab opens the account window and can come back", () => { + assert.ok(openManageAccounts, "expected an OpenManageAccounts in the settings window"); + assert.match(openManageAccounts, /CreateWindow\(\s*'account_management'/); + // ClearWindow takes a selector object; a bare string matched neither `selector.type` nor + // `selector.id` and closed nothing, leaving both windows stacked. + assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'settings'\s*\}\s*\)/); + assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'account_management'\s*\}\s*\)/); + assert.match(openManageAccounts, /CreateWindow\(\s*'settings'/, "back returns to the settings window"); + assert.doesNotMatch(settingsWindowSource, /ClearWindow\(\s*['"]/g, "no ClearWindow call may pass a bare string"); +}); + +// -- the account management window ------------------------------------------------ + +test("the account window talks to the account management endpoints", () => { + assert.match(accountsWindowSource, /Server\(\)\.get\(['"]\/user\/list['"]/); + assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/create['"]/); + assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/set-admin['"]/); + assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/delete['"]/); +}); + +test("the window closes the switches on the row of the admin using it", () => { + // The server answers the same way to anybody who still posts it (see below); the row just + // does not invite the attempt. + assert.match(accountsWindowSource, /v-if="!IsSelf\(user\)"/); + assert.match(accountsWindowSource, /GetUser\(\)\?\._id/); +}); + +// -- the backend routes ----------------------------------------------------------- + +function routeDeclaration(method, route) { + const declaration = new RegExp(`router\\.${method}\\(['"]${route}['"][^\\n]*`).exec(userRouteSource)?.[0]; + assert.ok(declaration, `expected a ${method.toUpperCase()} ${route} route`); + // /api/user is mounted before the JWT guard: without inline authentication the route would + // be public to any request (landmine 5 of AGENTS.md), and only an admin may manage accounts. + assert.match(declaration, /passport\.authenticate\(['"]jwt['"]/); + assert.match(declaration, /isAdmin/, `${route} may only be answered for an administrator`); + return declaration; +} + +function routeBlock(method, route) { + const start = userRouteSource.indexOf(`router.${method}('${route}'`); + assert.ok(start !== -1, `expected a ${method.toUpperCase()} ${route} route`); + const next = userRouteSource.indexOf(`\nrouter.`, start + 1); + return userRouteSource.slice(start, next === -1 ? userRouteSource.length : next); +} + +test("GET /user/list answers the accounts without passwords or setup codes", () => { + routeDeclaration("get", "/list"); + assert.match(routeBlock("get", "/list"), /select\(['"]-password -setupCode['"]\)/); +}); + +test("POST /user/create stores a hashed password and refuses duplicates", () => { + const block = routeBlock("post", "/create"); + assert.match(block, /bcrypt\.hash\(password/, "the password must not go in as it came"); + assert.match(block, /register\.errors\.email-username-exists/, "duplicates answer with the register message"); + assert.doesNotMatch(block, /setupCode/, "no half-finished setup account is invented here"); +}); + +for (const route of ["/set-admin", "/delete"]) { + test(`POST /user${route} refuses to act on the admin that is asking`, () => { + routeDeclaration("post", route); + const block = routeBlock("post", route); + assert.match(block, /String\(req\.user\._id\) === String\(id\)/, "an admin keeps their own account closed"); + assert.match(block, /errors\.internal/); + }); +} + +// -- i18n -------------------------------------------------------------------------- + +test("every locale titles the account window and names its strings", () => { + const required = [ + "accounts.you", + "accounts.admin", + "accounts.make-admin", + "accounts.remove-admin", + "accounts.delete", + "accounts.new-account", + "accounts.name", + "accounts.username", + "accounts.email", + "accounts.password", + "accounts.create", + "accounts.created", + "accounts.updated", + "accounts.deleted", + "accounts.errors.self-admin", + "accounts.errors.self-delete", + ]; + + for (const locale of ["en", "es", "ca"]) { + const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json")); + assert.ok(windows["account-management"]?.trim(), `${locale} is missing the account window title`); + + const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json")); + assert.ok(settings["site-administration"]?.["manage-accounts"]?.trim(), `${locale} is missing manage accounts`); + for (const key of required) { + const value = key.split(".").reduce((node, part) => node?.[part], settings["site-administration"]); + assert.ok(value?.trim(), `${locale} is missing settings.site-administration.${key}`); + } + } +}); + +test("every accounts string the window translates exists in every locale", () => { + // $t keys with nothing to translate fall back to the key itself, so every accounts key the + // window uses has to be carried by every locale. (`errors.internal` is the envelope fallback + // every window toasts the same way and stays out of it.) + const used = [...new Set( + [...accountsWindowSource.matchAll(/\$t\(\s*['"](settings\.site-administration\.accounts\.[\w.-]+)['"]/g)] + .map((key) => key[1]) + )]; + assert.ok(used.length >= 14, `expected the window's translated strings, found ${used.length}`); + + for (const locale of ["en", "es", "ca"]) { + const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json")); + for (const key of used) { + const value = key.split(".").slice(1).reduce((node, part) => node?.[part], settings); + assert.ok(typeof value === "string" && value.trim(), `${locale} is missing ${key}`); + } + } +}); -- 2.39.5