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:
58
public/login.js
Normal file
58
public/login.js
Normal file
@@ -0,0 +1,58 @@
|
||||
const form = document.getElementById("loginForm");
|
||||
const errorBox = document.getElementById("errorBox");
|
||||
const submitBtn = document.getElementById("submitBtn");
|
||||
|
||||
const ERROR_MESSAGES = {
|
||||
missing_credentials: "Completá email y contraseña.",
|
||||
invalid_credentials: "Email o contraseña incorrectos.",
|
||||
user_inactive: "El usuario está deshabilitado.",
|
||||
};
|
||||
|
||||
function showError(code) {
|
||||
errorBox.textContent = ERROR_MESSAGES[code] || "No pudimos iniciarte sesión.";
|
||||
errorBox.classList.add("visible");
|
||||
}
|
||||
|
||||
function clearError() {
|
||||
errorBox.classList.remove("visible");
|
||||
errorBox.textContent = "";
|
||||
}
|
||||
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
clearError();
|
||||
const email = form.email.value.trim();
|
||||
const password = form.password.value;
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "Entrando...";
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ email, password }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok || !data.ok) {
|
||||
showError(data.error || "login_failed");
|
||||
return;
|
||||
}
|
||||
const next = new URLSearchParams(window.location.search).get("next") || "/home";
|
||||
window.location.replace(next);
|
||||
} catch (err) {
|
||||
showError("network");
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "Entrar";
|
||||
}
|
||||
});
|
||||
|
||||
// Si ya hay sesión activa, ir directo al home.
|
||||
fetch("/api/auth/me", { credentials: "include" })
|
||||
.then((r) => (r.ok ? r.json() : null))
|
||||
.then((d) => {
|
||||
if (d?.ok) window.location.replace("/home");
|
||||
})
|
||||
.catch(() => {});
|
||||
Reference in New Issue
Block a user