Backend:
- 3 migrations: system_users (citext email único, password_hash, active),
system_sessions (UUID + expires_at + revoked_at), ALTER audit_log con
actor_user_id/actor_email/actor_ip/action_path/summary y entity_id NULL.
- src/modules/auth/: usersRepo, sessionsRepo, passwords (bcrypt cost 10),
auth (login/logout), bootstrap (crea admin desde ADMIN_EMAIL/PASSWORD si
la tabla está vacía). 4 tests passwords (hash distinto cada vez, verify
rechaza, longitud mínima 8).
- middleware/requireAuth: lee cookie bot_session, busca sesión activa,
popula req.user. Whitelist: /styles, /components, /lib, /login, /, /home
y SPA paths (HTML carga sin auth, el JS gatea con /api/auth/me).
- middleware/auditWriter: registra cada POST/PUT/DELETE 2xx en audit_log
con req.user, IP, body redactado (passwords/tokens/secrets). Handlers
pueden enriquecer summary via res.locals.audit.
- routes: /api/auth/{login,logout,me} (cookie httpOnly + DB session),
/api/system-users (ABM con guards: cant_delete_self, cant_deactivate_self,
email único, password ≥ 8), /api/audit-log + /api/audit-log/actors.
- src/app.js: orden estricto — webhooks (sin auth) → auth routes (sin auth)
→ /login HTML → static → SPA HTML → requireAuth + auditWriter → API admin.
Bootstrap del primer admin se ejecuta en index.js antes de listen. Usa
ADMIN_EMAIL/ADMIN_PASSWORD/ADMIN_NAME del .env. Si no están seteados y la
tabla está vacía, warn y exit (nadie puede loguearse).
Frontend:
- /login.html + /login.js: form simple, POST a /api/auth/login con
credentials:include, redirect a ?next=... o /home. Si ya hay sesión
activa, va directo a /home.
- public/app.js gate: chequea /api/auth/me antes de initRouter; sin sesión
redirige a /login?next=<path>. window.__USER__ disponible para shell.
- ops-shell: nav agrega "Operadores" + "Actividad". Header derecha muestra
email del user + botón Salir (POST /api/auth/logout + redirect /login).
- system-users-crud: CRUD lista/form (estilo settings). Crear/editar/
cambiar password/eliminar. UI muestra badge "Vos" + bloquea eliminarse
ni desactivarse a uno mismo.
- audit-log: tabla read-only con filtros (actor, entity_type, since,
search), paginación 50, badges por acción, modal de detalles con
changes JSON. /api/audit-log/actors pobla el dropdown de operadores.
Smoke E2E: login OK + cookie set, /me 200; logout → /me 401; settings POST
genera fila en audit_log con actor_email + action_path; ABM crea/borra
operadores con guards; intentar borrarse devuelve 400 cant_delete_self.
161/161 tests verde (pre-existentes 157 + 4 passwords nuevos).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
260 lines
11 KiB
JavaScript
260 lines
11 KiB
JavaScript
import { api } from "../lib/api.js";
|
|
import { modal } from "../lib/modal.js";
|
|
import { toast } from "../lib/toast.js";
|
|
|
|
class SystemUsersCrud extends HTMLElement {
|
|
constructor() {
|
|
super();
|
|
this.attachShadow({ mode: "open" });
|
|
this.users = [];
|
|
this.selected = null; // user seleccionado (objeto)
|
|
this.editing = null; // copia editable de selected
|
|
this.creating = false; // si true, editing es un user nuevo
|
|
this.loading = false;
|
|
this.saving = false;
|
|
|
|
this.shadowRoot.innerHTML = `
|
|
<style>
|
|
:host { display:block; height:100%; padding:16px 24px 24px; overflow:auto; }
|
|
* { box-sizing:border-box; font-family: var(--font-sans); }
|
|
.container { max-width:1200px; margin:0 auto; }
|
|
.toolbar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 4px 16px; position:sticky; top:0; background:var(--bg); border-bottom:1px solid var(--border); margin-bottom:16px; }
|
|
.toolbar-title { margin:0; font-size:18px; font-weight:600; }
|
|
.toolbar button { padding:8px 14px; font-size:13px; }
|
|
|
|
.grid { display:grid; grid-template-columns: minmax(280px,360px) minmax(0,1fr); gap:16px; align-items:start; }
|
|
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
|
|
.panel { background:var(--panel); border:1px solid var(--border); border-radius:10px; padding:16px; }
|
|
.panel h3 { margin:0 0 12px; font-size:14px; font-weight:600; color:var(--text-muted); text-transform:uppercase; letter-spacing:.4px; }
|
|
|
|
.list { display:flex; flex-direction:column; gap:6px; max-height:60vh; overflow-y:auto; }
|
|
.empty { padding:24px; color:var(--text-muted); text-align:center; font-size:13px; }
|
|
.item { padding:10px 12px; border:1px solid var(--border); border-radius:var(--r-md); cursor:pointer; transition:all .15s; background:var(--panel-2); }
|
|
.item:hover { border-color:var(--border-hi); }
|
|
.item.active { border-color:var(--accent); background:var(--accent-soft); }
|
|
.item.inactive { opacity:.55; }
|
|
.item-email { font-size:13px; font-weight:500; color:var(--text); }
|
|
.item-name { font-size:11px; color:var(--text-muted); margin-top:2px; }
|
|
.badge { display:inline-block; font-size:10px; padding:1px 6px; border-radius:6px; margin-left:6px; }
|
|
.badge.you { background:var(--accent-soft); color:var(--accent-hover); }
|
|
.badge.off { background:var(--panel-3); color:var(--text-muted); }
|
|
|
|
.form .field { margin-bottom:14px; }
|
|
.form label { display:block; font-size:11px; color:var(--text-muted); margin-bottom:6px; text-transform:uppercase; letter-spacing:.4px; }
|
|
.form input, .form select { width:100%; padding:9px 12px; font-size:13px; border:1px solid var(--border-hi); border-radius:var(--r-md); background:var(--panel-2); color:var(--text); }
|
|
.form input:focus, .form select:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-soft); }
|
|
.form-hint { font-size:11px; color:var(--text-muted); margin-top:4px; }
|
|
.form-actions { display:flex; gap:8px; flex-wrap:wrap; margin-top:16px; }
|
|
button { cursor:pointer; background:var(--accent); color:var(--text-on-acc, #fff); border:none; border-radius:var(--r-md); padding:9px 16px; font-size:13px; font-weight:500; }
|
|
button:hover { background:var(--accent-hover); }
|
|
button:disabled { opacity:.5; cursor:not-allowed; }
|
|
button.secondary { background:var(--panel); color:var(--text); border:1px solid var(--border-hi); }
|
|
button.secondary:hover { border-color:var(--accent); color:var(--accent-hover); }
|
|
button.danger { background:var(--err); color:#fff; border:none; }
|
|
button.danger:hover { filter:brightness(0.95); }
|
|
|
|
.placeholder { padding:24px; color:var(--text-muted); text-align:center; font-size:13px; }
|
|
</style>
|
|
<div class="container">
|
|
<div class="toolbar">
|
|
<h2 class="toolbar-title">Operadores</h2>
|
|
<div><button id="btnNew" type="button">+ Nuevo operador</button></div>
|
|
</div>
|
|
<div class="grid">
|
|
<div class="panel">
|
|
<h3>Lista</h3>
|
|
<div class="list" id="list"></div>
|
|
</div>
|
|
<div class="panel">
|
|
<h3 id="formTitle">Detalle</h3>
|
|
<div id="formSlot"></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
connectedCallback() {
|
|
this.shadowRoot.getElementById("btnNew").addEventListener("click", () => this.startCreate());
|
|
this.load();
|
|
}
|
|
|
|
meId() {
|
|
const u = window.__USER__;
|
|
return u ? Number(u.id) : null;
|
|
}
|
|
|
|
async load() {
|
|
this.loading = true;
|
|
this.renderList();
|
|
try {
|
|
const data = await api.listSystemUsers();
|
|
this.users = data.items || [];
|
|
this.loading = false;
|
|
// Si hay seleccionado, refrescar referencia.
|
|
if (this.selected) {
|
|
this.selected = this.users.find((u) => Number(u.id) === Number(this.selected.id)) || null;
|
|
}
|
|
this.renderList();
|
|
this.renderForm();
|
|
} catch (e) {
|
|
this.loading = false;
|
|
this.renderList();
|
|
}
|
|
}
|
|
|
|
startCreate() {
|
|
this.creating = true;
|
|
this.selected = null;
|
|
this.editing = { email: "", name: "", password: "", active: true };
|
|
this.renderList();
|
|
this.renderForm();
|
|
}
|
|
|
|
selectUser(user) {
|
|
this.creating = false;
|
|
this.selected = user;
|
|
this.editing = { ...user, password: "" };
|
|
this.renderList();
|
|
this.renderForm();
|
|
}
|
|
|
|
renderList() {
|
|
const list = this.shadowRoot.getElementById("list");
|
|
if (this.loading) { list.innerHTML = `<div class="empty">Cargando...</div>`; return; }
|
|
if (!this.users.length) { list.innerHTML = `<div class="empty">No hay operadores</div>`; return; }
|
|
const meId = this.meId();
|
|
list.innerHTML = this.users.map((u) => {
|
|
const isMe = Number(u.id) === meId;
|
|
const active = !this.creating && this.selected?.id === u.id ? "active" : "";
|
|
const inactive = !u.active ? "inactive" : "";
|
|
return `
|
|
<div class="item ${active} ${inactive}" data-id="${u.id}">
|
|
<div class="item-email">${this.escapeHtml(u.email)}${isMe ? '<span class="badge you">Vos</span>' : ""}${!u.active ? '<span class="badge off">Inactivo</span>' : ""}</div>
|
|
<div class="item-name">${this.escapeHtml(u.name)}</div>
|
|
</div>
|
|
`;
|
|
}).join("");
|
|
list.querySelectorAll(".item[data-id]").forEach((el) => {
|
|
el.addEventListener("click", () => {
|
|
const u = this.users.find((x) => String(x.id) === el.dataset.id);
|
|
if (u) this.selectUser(u);
|
|
});
|
|
});
|
|
}
|
|
|
|
renderForm() {
|
|
const title = this.shadowRoot.getElementById("formTitle");
|
|
const slot = this.shadowRoot.getElementById("formSlot");
|
|
if (!this.editing) {
|
|
title.textContent = "Detalle";
|
|
slot.innerHTML = `<div class="placeholder">Seleccioná un operador o creá uno nuevo.</div>`;
|
|
return;
|
|
}
|
|
const isCreate = this.creating;
|
|
const meId = this.meId();
|
|
const isSelf = !isCreate && Number(this.selected?.id) === meId;
|
|
title.textContent = isCreate ? "Nuevo operador" : `Editar — ${this.selected?.email || ""}`;
|
|
|
|
slot.innerHTML = `
|
|
<div class="form">
|
|
<div class="field">
|
|
<label>Email</label>
|
|
<input id="fEmail" type="email" value="${this.escapeHtml(this.editing.email || "")}" ${isCreate ? "" : "disabled"} placeholder="ej. juan@local" autocomplete="off" />
|
|
${!isCreate ? '<div class="form-hint">El email no se puede cambiar (volvete a crear el operador si hace falta).</div>' : ""}
|
|
</div>
|
|
<div class="field">
|
|
<label>Nombre</label>
|
|
<input id="fName" type="text" value="${this.escapeHtml(this.editing.name || "")}" placeholder="Juan Pérez" />
|
|
</div>
|
|
<div class="field">
|
|
<label>${isCreate ? "Contraseña" : "Cambiar contraseña (opcional)"}</label>
|
|
<input id="fPassword" type="password" value="" placeholder="${isCreate ? "Mínimo 8 caracteres" : "Dejar vacío para no cambiar"}" autocomplete="new-password" />
|
|
${isCreate ? '<div class="form-hint">Mínimo 8 caracteres.</div>' : ""}
|
|
</div>
|
|
${isCreate ? "" : `
|
|
<div class="field">
|
|
<label>Estado</label>
|
|
<select id="fActive" ${isSelf ? "disabled" : ""}>
|
|
<option value="true" ${this.editing.active ? "selected" : ""}>Activo</option>
|
|
<option value="false" ${!this.editing.active ? "selected" : ""}>Inactivo</option>
|
|
</select>
|
|
${isSelf ? '<div class="form-hint">No podés desactivarte a vos mismo.</div>' : ""}
|
|
</div>
|
|
`}
|
|
<div class="form-actions">
|
|
<button id="btnSave" type="button">${this.saving ? "Guardando..." : isCreate ? "Crear" : "Guardar cambios"}</button>
|
|
<button id="btnCancel" type="button" class="secondary">Cancelar</button>
|
|
${isCreate || isSelf ? "" : '<button id="btnDelete" type="button" class="danger" style="margin-left:auto;">Eliminar</button>'}
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
this.shadowRoot.getElementById("btnCancel").addEventListener("click", () => {
|
|
this.creating = false;
|
|
this.editing = this.selected ? { ...this.selected, password: "" } : null;
|
|
this.renderForm();
|
|
});
|
|
this.shadowRoot.getElementById("btnSave").addEventListener("click", () => this.save());
|
|
this.shadowRoot.getElementById("btnDelete")?.addEventListener("click", () => this.remove());
|
|
}
|
|
|
|
async save() {
|
|
const f = this.shadowRoot;
|
|
const email = f.getElementById("fEmail").value.trim();
|
|
const name = f.getElementById("fName").value.trim();
|
|
const password = f.getElementById("fPassword").value;
|
|
const activeEl = f.getElementById("fActive");
|
|
const active = activeEl ? activeEl.value === "true" : true;
|
|
|
|
if (this.creating) {
|
|
if (!email) return toast({ kind: "error", text: "Email requerido" });
|
|
if (!name) return toast({ kind: "error", text: "Nombre requerido" });
|
|
if (!password || password.length < 8) return toast({ kind: "error", text: "Contraseña mínimo 8 caracteres" });
|
|
} else {
|
|
if (!name) return toast({ kind: "error", text: "Nombre requerido" });
|
|
if (password && password.length < 8) return toast({ kind: "error", text: "Contraseña mínimo 8 caracteres" });
|
|
}
|
|
|
|
this.saving = true;
|
|
this.renderForm();
|
|
try {
|
|
if (this.creating) {
|
|
await api.createSystemUser({ email, name, password, active });
|
|
toast({ kind: "ok", text: "Operador creado" });
|
|
} else {
|
|
const payload = { name, active };
|
|
if (password) payload.password = password;
|
|
await api.updateSystemUser(this.selected.id, payload);
|
|
toast({ kind: "ok", text: "Cambios guardados" });
|
|
}
|
|
this.creating = false;
|
|
await this.load();
|
|
} catch (e) {
|
|
// safeFetch ya muestra toast
|
|
} finally {
|
|
this.saving = false;
|
|
this.renderForm();
|
|
}
|
|
}
|
|
|
|
async remove() {
|
|
if (!this.selected) return;
|
|
const ok = await modal.confirm(`¿Eliminar al operador ${this.selected.email}? Pierde acceso al sistema.`, { confirmText: "Eliminar", cancelText: "Cancelar" });
|
|
if (!ok) return;
|
|
try {
|
|
await api.deleteSystemUser(this.selected.id);
|
|
toast({ kind: "ok", text: "Operador eliminado" });
|
|
this.selected = null;
|
|
this.editing = null;
|
|
await this.load();
|
|
} catch (e) {}
|
|
}
|
|
|
|
escapeHtml(s) {
|
|
return String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
}
|
|
}
|
|
|
|
customElements.define("system-users-crud", SystemUsersCrud);
|