feat(auth): login, MFA and account screens
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
67cf62b536
commit
42892cb37f
10 files changed
+1226
-13
No files matched your search
@@ -0,0 +1,378 @@
|
||||
// The "Conta" view. Everything from the server goes in through textContent.
|
||||
import { tr, LOC } from './i18n.js';
|
||||
|
||||
const $ = (selector) => document.querySelector(selector);
|
||||
|
||||
let api = null;
|
||||
let session = { username: '', role: '' };
|
||||
|
||||
function el(tag, props = {}, children = []) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (key === 'text') node.textContent = value;
|
||||
else if (key === 'class') node.className = value;
|
||||
else if (key === 'on') node.addEventListener('click', value);
|
||||
else node.setAttribute(key, value);
|
||||
}
|
||||
for (const child of children) node.append(child);
|
||||
return node;
|
||||
}
|
||||
|
||||
function when(unix) {
|
||||
return unix ? new Date(unix * 1000).toLocaleString(LOC()) : '—';
|
||||
}
|
||||
|
||||
function say(box, text, ok = false) {
|
||||
box.textContent = text;
|
||||
box.className = ok ? 'form-ok' : 'form-error';
|
||||
box.hidden = !text;
|
||||
}
|
||||
|
||||
function explain(error) {
|
||||
if (!error.retryAfter) return error.message;
|
||||
return `${error.message} ${tr('Tente de novo em {n} s.').replace('{n}', error.retryAfter)}`;
|
||||
}
|
||||
|
||||
function fillRows(body, rows, columns, emptyText) {
|
||||
body.replaceChildren(
|
||||
...(rows.length
|
||||
? rows
|
||||
: [el('tr', {}, [el('td', { colspan: String(columns), class: 'empty-cell', text: emptyText })])]),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- Reauthentication ------------------------------------------------------
|
||||
|
||||
class ReauthCancelled extends Error {}
|
||||
|
||||
function promptReauth() {
|
||||
const dialog = $('#reauthDlg');
|
||||
const form = $('#reauthForm');
|
||||
const error = $('#reauthError');
|
||||
const password = $('#reauthPass');
|
||||
const code = $('#reauthCode');
|
||||
return new Promise((resolve, reject) => {
|
||||
const finish = (confirmed) => {
|
||||
form.removeEventListener('submit', submit);
|
||||
$('#reauthCancel').removeEventListener('click', cancel);
|
||||
dialog.removeEventListener('cancel', cancel);
|
||||
password.value = '';
|
||||
code.value = '';
|
||||
dialog.close();
|
||||
if (confirmed) resolve();
|
||||
else reject(new ReauthCancelled());
|
||||
};
|
||||
const cancel = (event) => {
|
||||
event.preventDefault();
|
||||
finish(false);
|
||||
};
|
||||
const submit = async (event) => {
|
||||
event.preventDefault();
|
||||
const button = form.querySelector('button[type="submit"]');
|
||||
button.disabled = true;
|
||||
say(error, '');
|
||||
try {
|
||||
await api('/api/auth/reauth', {
|
||||
method: 'POST',
|
||||
body: { password: password.value, code: code.value.trim() || null },
|
||||
});
|
||||
finish(true);
|
||||
} catch (failure) {
|
||||
say(error, explain(failure));
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
};
|
||||
say(error, '');
|
||||
form.addEventListener('submit', submit);
|
||||
$('#reauthCancel').addEventListener('click', cancel);
|
||||
dialog.addEventListener('cancel', cancel);
|
||||
dialog.showModal();
|
||||
password.focus();
|
||||
});
|
||||
}
|
||||
|
||||
/** Runs a sensitive action, asking for password and code once if the server wants them. */
|
||||
async function withReauth(action) {
|
||||
try {
|
||||
return await action();
|
||||
} catch (error) {
|
||||
if (error.code !== 'recent authentication required') throw error;
|
||||
}
|
||||
await promptReauth();
|
||||
return action();
|
||||
}
|
||||
|
||||
/** Runs a panel's action and reports the outcome in its status line. */
|
||||
async function attempt(box, action, done = '') {
|
||||
say(box, '');
|
||||
try {
|
||||
await action();
|
||||
if (done) say(box, done, true);
|
||||
} catch (error) {
|
||||
if (!(error instanceof ReauthCancelled)) say(box, explain(error));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- One-time secrets ------------------------------------------------------
|
||||
|
||||
function bindSecret({ box, copy, download, fileName, status }) {
|
||||
copy.addEventListener('click', async () => {
|
||||
const label = copy.textContent;
|
||||
try {
|
||||
await navigator.clipboard.writeText(box.textContent);
|
||||
copy.textContent = tr('Copiado');
|
||||
window.setTimeout(() => { copy.textContent = label; }, 1400);
|
||||
} catch {
|
||||
say(status, tr('Não foi possível copiar. Selecione o texto e copie à mão.'));
|
||||
}
|
||||
});
|
||||
download.addEventListener('click', () => {
|
||||
const url = URL.createObjectURL(new Blob([`${box.textContent}\n`], { type: 'text/plain' }));
|
||||
const link = el('a', { href: url, download: fileName });
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Own credentials -------------------------------------------------------
|
||||
|
||||
async function changePassword(event) {
|
||||
event.preventDefault();
|
||||
const box = $('#pwStatus');
|
||||
const form = event.currentTarget;
|
||||
if ($('#pwNew').value !== $('#pwRepeat').value) {
|
||||
say(box, tr('As senhas não coincidem.'));
|
||||
return;
|
||||
}
|
||||
await attempt(box, async () => {
|
||||
await api('/api/auth/password', {
|
||||
method: 'POST',
|
||||
body: { current: $('#pwCurrent').value, new: $('#pwNew').value },
|
||||
});
|
||||
form.reset();
|
||||
await loadSessions();
|
||||
}, tr('Senha trocada. As outras sessões foram encerradas.'));
|
||||
}
|
||||
|
||||
function bindMfa() {
|
||||
const status = $('#mfaStatus');
|
||||
$('#mfaStart').addEventListener('click', () => attempt(status, async () => {
|
||||
const data = await withReauth(() => api('/api/auth/enroll/start', { method: 'POST', body: {} }));
|
||||
$('#mfaQr').src = `data:image/png;base64,${data.qr_png_base64}`;
|
||||
$('#mfaKey').value = data.manual_key;
|
||||
$('#mfaCode').value = '';
|
||||
$('#mfaEnroll').hidden = false;
|
||||
$('#mfaCode').focus();
|
||||
}));
|
||||
$('#mfaEnroll').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
attempt(status, async () => {
|
||||
const reply = await withReauth(() => api('/api/auth/enroll/confirm', {
|
||||
method: 'POST',
|
||||
body: { code: $('#mfaCode').value.trim() },
|
||||
}));
|
||||
$('#mfaEnroll').hidden = true;
|
||||
$('#mfaQr').removeAttribute('src');
|
||||
$('#mfaKey').value = '';
|
||||
$('#mfaActions').hidden = true;
|
||||
$('#mfaRecoveryCodes').textContent = reply.recovery_codes.join('\n');
|
||||
$('#mfaRecovery').hidden = false;
|
||||
});
|
||||
});
|
||||
bindSecret({
|
||||
box: $('#mfaRecoveryCodes'),
|
||||
copy: $('#mfaRecoveryCopy'),
|
||||
download: $('#mfaRecoveryDownload'),
|
||||
fileName: 'acaua-codigos-de-recuperacao.txt',
|
||||
status,
|
||||
});
|
||||
// Activation ended every session of this user, this one included.
|
||||
$('#mfaRecoveryDone').addEventListener('click', () => location.replace('/login.html'));
|
||||
$('#mfaDisable').addEventListener('click', () => {
|
||||
if (!window.confirm(tr('Desativar o MFA desta conta?'))) return;
|
||||
attempt(status, () => withReauth(() => api('/api/auth/mfa/disable', { method: 'POST', body: {} })),
|
||||
tr('MFA desativado.'));
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Sessions and tokens ---------------------------------------------------
|
||||
|
||||
async function loadSessions() {
|
||||
const box = $('#sessionStatus');
|
||||
const list = await api('/api/auth/sessions');
|
||||
fillRows($('#sessionRows'), list.map((s) => el('tr', {}, [
|
||||
el('td', { text: when(s.created_at) }),
|
||||
el('td', { text: when(s.last_seen) }),
|
||||
el('td', { text: when(s.expires_at) }),
|
||||
el('td', { class: 'row-actions' }, [el('button', {
|
||||
type: 'button',
|
||||
class: 'btn small danger',
|
||||
text: 'Encerrar',
|
||||
on: () => attempt(box, async () => {
|
||||
await api('/api/auth/sessions', { method: 'DELETE', body: { id: s.id } });
|
||||
await loadSessions();
|
||||
}),
|
||||
})]),
|
||||
])), 4, 'Nenhuma sessão ativa.');
|
||||
}
|
||||
|
||||
async function loadTokens() {
|
||||
const box = $('#tokenStatus');
|
||||
const list = await api('/api/auth/tokens');
|
||||
fillRows($('#tokenRows'), list.map((token) => el('tr', {}, [
|
||||
el('td', { class: 'mono', text: token.name }),
|
||||
el('td', { text: token.scope === 'admin' ? 'Administração' : 'Leitura' }),
|
||||
el('td', { text: when(token.expires_at) }),
|
||||
el('td', { class: 'row-actions' }, [el('button', {
|
||||
type: 'button',
|
||||
class: 'btn small danger',
|
||||
text: 'Revogar',
|
||||
on: () => attempt(box, async () => {
|
||||
await api('/api/auth/tokens', { method: 'DELETE', body: { id: token.id } });
|
||||
await loadTokens();
|
||||
}),
|
||||
})]),
|
||||
])), 4, 'Nenhum token criado.');
|
||||
}
|
||||
|
||||
function bindTokens() {
|
||||
const status = $('#tokenStatus');
|
||||
$('#tokenForm').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
attempt(status, async () => {
|
||||
const days = Number($('#tokenDays').value);
|
||||
const made = await withReauth(() => api('/api/auth/tokens', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
name: $('#tokenName').value,
|
||||
scope: $('#tokenScope').value,
|
||||
expires_at: Math.floor(Date.now() / 1000) + days * 86400,
|
||||
},
|
||||
}));
|
||||
form.reset();
|
||||
$('#tokenValue').textContent = made.token;
|
||||
$('#tokenOnce').hidden = false;
|
||||
await loadTokens();
|
||||
});
|
||||
});
|
||||
bindSecret({
|
||||
box: $('#tokenValue'),
|
||||
copy: $('#tokenCopy'),
|
||||
download: $('#tokenDownload'),
|
||||
fileName: 'acaua-token.txt',
|
||||
status,
|
||||
});
|
||||
$('#tokenDone').addEventListener('click', () => {
|
||||
$('#tokenValue').textContent = '';
|
||||
$('#tokenOnce').hidden = true;
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Administration --------------------------------------------------------
|
||||
|
||||
function roleSelect(user) {
|
||||
const select = el('select', { name: 'role', 'aria-label': 'Papel' }, [
|
||||
el('option', { value: 'analyst', text: 'Analista' }),
|
||||
el('option', { value: 'admin', text: 'Administrador' }),
|
||||
]);
|
||||
select.value = user.role;
|
||||
select.addEventListener('change', () => attempt($('#userStatus'), async () => {
|
||||
try {
|
||||
await withReauth(() => api('/api/admin/users', {
|
||||
method: 'PATCH',
|
||||
body: { id: user.id, role: select.value },
|
||||
}));
|
||||
} finally {
|
||||
await loadUsers();
|
||||
}
|
||||
}));
|
||||
return select;
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
const box = $('#userStatus');
|
||||
const list = await api('/api/admin/users');
|
||||
fillRows($('#userRows'), list.map((user) => el('tr', {}, [
|
||||
el('td', { class: 'mono', text: user.username }),
|
||||
el('td', {}, [roleSelect(user)]),
|
||||
el('td', { text: user.mfa_enabled ? 'Ativo' : 'Inativo' }),
|
||||
el('td', { text: when(user.created_at) }),
|
||||
el('td', { class: 'row-actions' }, [el('button', {
|
||||
type: 'button',
|
||||
class: 'btn small danger',
|
||||
text: 'Excluir',
|
||||
on: () => {
|
||||
if (!window.confirm(tr('Excluir esta conta? As sessões e os tokens dela também acabam.'))) return;
|
||||
attempt(box, async () => {
|
||||
await withReauth(() => api('/api/admin/users', { method: 'DELETE', body: { id: user.id } }));
|
||||
await loadUsers();
|
||||
});
|
||||
},
|
||||
})]),
|
||||
])), 5, 'Nenhuma conta.');
|
||||
}
|
||||
|
||||
async function loadAudit() {
|
||||
const list = await api('/api/admin/audit?limit=100');
|
||||
fillRows($('#auditRows'), list.slice().reverse().map((entry) => el('tr', {}, [
|
||||
el('td', { class: 'mono', text: entry.ts }),
|
||||
el('td', { class: 'mono', text: entry.action }),
|
||||
el('td', { class: 'mono', text: entry.actor ?? '—' }),
|
||||
el('td', { class: 'mono', text: entry.ip ?? '—' }),
|
||||
el('td', { text: entry.ok ? 'Sim' : 'Não' }),
|
||||
el('td', { class: 'mono', text: entry.detail ?? '—' }),
|
||||
])), 6, 'Nenhum evento registrado.');
|
||||
}
|
||||
|
||||
function bindAdmin() {
|
||||
$('#userForm').addEventListener('submit', (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
attempt($('#userStatus'), async () => {
|
||||
await withReauth(() => api('/api/admin/users', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: $('#userName').value,
|
||||
password: $('#userPass').value,
|
||||
role: $('#userRole').value,
|
||||
},
|
||||
}));
|
||||
form.reset();
|
||||
await Promise.all([loadUsers(), loadAudit()]);
|
||||
}, tr('Conta criada.'));
|
||||
});
|
||||
$('#auditRefresh').addEventListener('click', () => attempt($('#auditStatus'), loadAudit));
|
||||
}
|
||||
|
||||
// ---- Entry points ----------------------------------------------------------
|
||||
|
||||
export function refreshAccount() {
|
||||
attempt($('#sessionStatus'), loadSessions);
|
||||
attempt($('#tokenStatus'), loadTokens);
|
||||
if (session.role === 'admin') {
|
||||
attempt($('#userStatus'), loadUsers);
|
||||
attempt($('#auditStatus'), loadAudit);
|
||||
}
|
||||
}
|
||||
|
||||
export function initAccount(client, current) {
|
||||
api = client;
|
||||
session = current;
|
||||
const admin = session.role === 'admin';
|
||||
$('#accountUser').textContent = session.username;
|
||||
$('#accountRole').textContent = admin ? 'Administrador' : 'Analista';
|
||||
$('#mfaPolicy').textContent = admin
|
||||
? 'O MFA é obrigatório para administradores. Cadastrar de novo troca o segredo e os códigos de recuperação.'
|
||||
: 'O MFA é opcional para analistas. Cadastrar de novo troca o segredo e os códigos de recuperação.';
|
||||
$('#mfaDisable').hidden = admin;
|
||||
$('#tokenScopeAdmin').hidden = !admin;
|
||||
$('#tokenScopeAdmin').disabled = !admin;
|
||||
$('#adminPanels').hidden = !admin;
|
||||
|
||||
$('#passwordForm').addEventListener('submit', changePassword);
|
||||
bindMfa();
|
||||
bindTokens();
|
||||
if (admin) bindAdmin();
|
||||
}
|
||||
Reference in new issue
Block a user