feat(auth): login, MFA and account screens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-04 20:21:33 -03:00
1 parent 67cf62b536
commit 42892cb37f
10 files changed
+1226 -13

No files matched your search

+64 -7
View File
@@ -1,4 +1,5 @@
import { setLang, tr, LOC, currentLang } from './i18n.js';
import { setLang, tr, LOC, currentLang, serverMessage } from './i18n.js';
import { initAccount, refreshAccount } from './account.js';
const SVG_NS = 'http://www.w3.org/2000/svg';
const $ = (selector) => document.querySelector(selector);
@@ -53,6 +54,8 @@ const state = {
expandedHosts: new Set(),
};
let session = { username: '', role: '', csrf: '' };
const VIEW_META = {
overview: {
title: 'Visão geral',
@@ -70,6 +73,10 @@ const VIEW_META = {
title: 'Análise',
sub: 'Ingestão de logs Zeek e relatório da execução',
},
account: {
title: 'Conta',
sub: 'Senha, MFA, sessões e tokens',
},
};
let themePreference = localStorage.getItem('acaua-theme') || 'auto';
@@ -1237,11 +1244,44 @@ function applyViewMeta() {
document.title = `${t(meta.title)} · Acauã`;
}
function goToLogin() {
location.replace('/login.html');
// The page is leaving: callers must not go on to render a failure.
return new Promise(() => {});
}
async function fetchJson(path, options = {}) {
const response = await fetch(path, options);
const method = (options.method || 'GET').toUpperCase();
const headers = { ...options.headers };
if (method !== 'GET' && method !== 'HEAD') headers['X-Acaua-CSRF'] = session.csrf;
const response = await fetch(path, { ...options, headers });
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.error || response.statusText);
return body;
if (response.ok) return body;
// A wrong password in a form is also a 401, but must stay on the page.
if (response.status === 401 && body.error === 'authentication required') return goToLogin();
const raw = body.error || response.statusText;
const error = new Error(serverMessage(raw));
error.code = raw;
error.retryAfter = response.headers.get('Retry-After');
throw error;
}
/** `fetchJson` with a JSON body, for the account screen. */
function accountApi(path, { method = 'GET', body } = {}) {
if (body === undefined) return fetchJson(path, { method });
return fetchJson(path, {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
}
async function logout() {
try {
await fetchJson('/api/auth/logout', { method: 'POST' });
} finally {
location.replace('/login.html');
}
}
async function call(command, args = {}) {
@@ -1315,6 +1355,7 @@ async function refreshAll() {
}
async function analyzeDataset() {
if (session.role !== 'admin') return;
const path = datasetPath.value.trim();
if (!path) {
output.textContent = t('Nenhum dataset selecionado.');
@@ -1336,7 +1377,9 @@ async function analyzeDataset() {
} catch (error) {
reportSummary.hidden = true;
reportStatus.textContent = '—';
output.textContent = message('Falha na análise: {n}', error.message);
output.textContent = error.code === 'analysis failed'
? error.message
: message('Falha na análise: {n}', error.message);
$('#gotoAlerts').hidden = true;
$('#gotoHosts').hidden = true;
$('#openReport').hidden = true;
@@ -1417,6 +1460,7 @@ function showView(target, { updateHash = true } = {}) {
if (target === 'overview') renderCharts();
if (target === 'alerts') renderAlerts();
if (target === 'hosts') renderHosts();
if (target === 'account' && session.csrf) refreshAccount();
window.scrollTo({ top: 0, behavior: 'instant' });
}
@@ -1425,10 +1469,23 @@ function initViewFromHash() {
return VIEW_META[target] ? target : 'overview';
}
function init() {
async function init() {
applyTheme(themePreference);
langSel.value = localStorage.getItem('acaua-lang') || 'auto';
setLang(langSel.value);
const auth = await fetch('/api/auth/state').then((response) => response.json());
if (!auth.authenticated) {
await goToLogin();
return;
}
session = { username: auth.username, role: auth.role, csrf: auth.csrf };
$('#topUser').textContent = session.username;
$('#logoutBtn').addEventListener('click', logout);
if (session.role !== 'admin') {
$('#analysisForm').hidden = true;
$('#analysisLocked').hidden = false;
}
initAccount(accountApi, session);
datasetPath.value = localStorage.getItem('acaua-last-path') || '';
state.view = initViewFromHash();
showView(state.view, { updateHash: false });
@@ -1592,4 +1649,4 @@ function init() {
};
}
init();
init().catch((error) => console.error(error));