Login + ABM de operadores + audit log con UI
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>
This commit is contained in:
@@ -8,7 +8,7 @@ import { toast } from "./toast.js";
|
||||
export async function safeFetch(url, opts = {}, { silent = false, label = null } = {}) {
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, opts);
|
||||
res = await fetch(url, { credentials: "include", ...opts });
|
||||
} catch (err) {
|
||||
if (!silent) toast({ kind: "error", text: `${label || "Red"}: ${err?.message || "sin conexión"}` });
|
||||
throw err;
|
||||
@@ -313,4 +313,52 @@ export const api = {
|
||||
}
|
||||
return data;
|
||||
},
|
||||
|
||||
// --- Auth ---
|
||||
async me() {
|
||||
const res = await fetch("/api/auth/me", { credentials: "include" });
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
return data?.user || null;
|
||||
},
|
||||
async logout() {
|
||||
return fetch("/api/auth/logout", { method: "POST", credentials: "include" }).then(r => r.json());
|
||||
},
|
||||
|
||||
// --- System users (operadores) ---
|
||||
async listSystemUsers() {
|
||||
return safeFetch("/api/system-users", {}, { label: "Operadores" });
|
||||
},
|
||||
async createSystemUser({ email, name, password, active = true }) {
|
||||
return safeFetch("/api/system-users", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, name, password, active }),
|
||||
}, { label: "Crear operador" });
|
||||
},
|
||||
async updateSystemUser(id, payload) {
|
||||
return safeFetch(`/api/system-users/${id}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
}, { label: "Editar operador" });
|
||||
},
|
||||
async deleteSystemUser(id) {
|
||||
return safeFetch(`/api/system-users/${id}`, { method: "DELETE" }, { label: "Eliminar operador" });
|
||||
},
|
||||
|
||||
// --- Audit log ---
|
||||
async auditLog({ limit = 50, before, since, actor_id, entity_type, q } = {}) {
|
||||
const qs = new URLSearchParams();
|
||||
qs.set("limit", String(limit));
|
||||
if (before) qs.set("before", before);
|
||||
if (since) qs.set("since", since);
|
||||
if (actor_id) qs.set("actor_id", String(actor_id));
|
||||
if (entity_type) qs.set("entity_type", entity_type);
|
||||
if (q) qs.set("q", q);
|
||||
return safeFetch(`/api/audit-log?${qs.toString()}`, {}, { silent: true });
|
||||
},
|
||||
async auditActors() {
|
||||
return safeFetch("/api/audit-log/actors", {}, { silent: true });
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user