feat: add hotspot admin panel and harden payment provisioning
build-image / build-push (push) Failing after 1m36s
build-image / build-push (push) Failing after 1m36s
This commit is contained in:
1 parent
fb3135d18f
commit
ebb2d1d792
25 files changed
+832
-686
No files matched your search
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;--bg:#101820;--card:#17232e;--line:#2b3c4c;--text:#f4f6f8;--muted:#a4b2c0;--blue:#246bfd}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 system-ui,sans-serif}header,main,footer{max-width:1280px;margin:auto;padding:24px}header{display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}header strong{font-size:25px;letter-spacing:.06em}header span{color:#82aaff}header p{margin:0;color:var(--muted)}a{color:#9bbbff}h1{font-size:32px;line-height:1.2;margin:8px 0 12px}h2{font-size:20px;margin:0 0 8px}p{color:var(--muted);margin:6px 0 18px}.eyebrow{font-size:12px;font-weight:700;letter-spacing:.15em;color:#82aaff}.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:24px;margin-bottom:20px}.login{max-width:520px;margin:8vh auto}.login label{margin:24px 0 16px}.login button{width:100%;margin-bottom:18px}small{color:var(--muted)}label{display:flex;flex-direction:column;gap:8px;font-size:13px;font-weight:600}input,select,button{font:inherit;border-radius:8px;min-height:44px;padding:10px 14px}input,select{background:#101820;color:var(--text);border:1px solid #486078;width:100%}button{background:var(--blue);color:white;font-weight:650;border:1px solid transparent;cursor:pointer}button:hover{filter:brightness(1.14)}button:disabled{opacity:.5;cursor:wait}.secondary{background:transparent;border-color:#486078}.danger{background:#652e3a;border-color:#c76a7c}.toolbar,.section-title{display:flex;justify-content:space-between;align-items:center;gap:18px}.actions{display:flex;gap:10px}.metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.metrics span{display:block;color:var(--muted);font-size:13px}.metrics strong{display:block;font-size:30px;margin-top:8px}.filters{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin:18px 0}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:14px}th{text-align:left;color:var(--muted);font-size:12px;text-transform:uppercase;letter-spacing:.04em}td,th{padding:14px 12px;border-bottom:1px solid var(--line);vertical-align:top}td small{display:block}.badge{display:inline-block;padding:3px 9px;border-radius:20px;background:#2a3a4b;font-size:12px;white-space:nowrap}.badge.online{background:#174b3f;color:#9fecd3}.badge.blocked{background:#5b2934;color:#ffc2cc}.create-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:18px;align-items:end}.notice{padding:18px;margin-top:20px;border:1px solid #4488ff;border-radius:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}#message{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);max-width:90vw;width:600px;background:#243b53;border:1px solid #82aaff;padding:16px 22px;border-radius:12px;color:white;box-shadow:0 8px 30px #0008;z-index:10}#message.error{background:#542634;border-color:#e992a5}footer{color:var(--muted);text-align:center;font-size:12px}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #a0bcff;outline-offset:3px}[hidden]{display:none!important}@media(max-width:750px){header,main,footer{padding:16px}.card{padding:18px}.metrics{grid-template-columns:repeat(2,1fr);gap:10px}.toolbar,.section-title{align-items:flex-start;flex-direction:column}.filters,.create-grid{grid-template-columns:1fr}.login{margin:30px auto}h1{font-size:27px}td,th{padding:12px 8px}}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!doctype html>
|
||||
<html lang="pt-BR">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Administração • INCTG Wi-Fi</title>
|
||||
<link rel="stylesheet" href="/admin.css">
|
||||
<script src="/admin.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header><div><strong>INCTG <span>Wi-Fi</span></strong><p>Administração do hotspot</p></div><a href="/">Abrir portal ↗</a></header>
|
||||
<main>
|
||||
<section id="login" class="card login"><p class="eyebrow">ACESSO RESTRITO</p><h1>Seu hotspot, sob controle.</h1><p>Entre com o ADMIN_TOKEN configurado no servidor.</p>
|
||||
<form id="loginForm"><label>Token administrativo<input id="token" type="password" autocomplete="off" required minlength="32"></label><button>Entrar no painel</button></form><small>O token permanece apenas na memória desta aba. Ao sair ou recarregar, entre novamente.</small></section>
|
||||
<div id="dashboard" hidden>
|
||||
<div class="toolbar"><div><p class="eyebrow">VISÃO GERAL</p><h1>Usuários e pagamentos</h1><p id="updated">Carregando…</p></div><div class="actions"><button id="refresh" class="secondary">Atualizar</button><button id="logout" class="secondary">Sair</button></div></div>
|
||||
<div class="metrics"><article class="card"><span>Usuários</span><strong id="total">—</strong></article><article class="card"><span>Online</span><strong id="online">—</strong></article><article class="card"><span>Bloqueados</span><strong id="blocked">—</strong></article><article class="card"><span>Pagamentos aprovados*</span><strong id="revenue">—</strong></article></div>
|
||||
<section class="card"><div class="section-title"><div><h2>Usuários do hotspot</h2><p>Bloquear também encerra sessões e remove cookies de acesso.</p></div><button id="export" class="secondary">Exportar CSV</button></div>
|
||||
<div class="filters"><label>Buscar<input id="search" type="search" placeholder="Usuário, perfil, IP ou MAC"></label><label>Situação<select id="filter"><option value="all">Todos</option><option value="online">Online</option><option value="blocked">Bloqueados</option><option value="offline">Offline</option></select></label></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>Usuário / perfil</th><th>Situação</th><th>Dispositivo</th><th>Tempo usado / limite</th><th>Tráfego</th><th>Ação</th></tr></thead><tbody id="users"></tbody></table></div><p id="empty" hidden>Nenhum usuário encontrado.</p></section>
|
||||
<section class="card"><h2>Criar usuário</h2><p>O limite corresponde ao tempo acumulado de conexão. Deixe a senha vazia para gerar uma automaticamente.</p>
|
||||
<form id="createForm" class="create-grid"><label>Usuário<input name="name" required pattern="[A-Za-z0-9_.@-]{1,64}" maxlength="64" placeholder="visitante-01"></label><label>Perfil<select id="profile" name="profile" required></select></label><label>Limite de uso<input name="uptime" required value="1h" placeholder="1h, 1d ou 1w"></label><label>Senha<input name="password" type="password" minlength="8" maxlength="128" autocomplete="new-password" placeholder="Gerar automaticamente"></label><label>Observação<input name="comment" maxlength="200"></label><button>Criar usuário</button></form>
|
||||
<div id="credentials" class="notice" hidden><strong>Usuário criado. Guarde as credenciais:</strong><pre id="newCredentials"></pre><button id="hideCredentials" class="secondary">Ocultar</button></div></section>
|
||||
<section class="card"><h2>Pagamentos recentes</h2><p>*Total referente aos últimos 100 registros, sem representar um fechamento contábil.</p><div class="table-wrap"><table><thead><tr><th>Data</th><th>Plano</th><th>Valor</th><th>Status</th><th>Voucher</th></tr></thead><tbody id="payments"></tbody></table></div></section>
|
||||
<section class="card"><h2>Atividade administrativa</h2><div class="table-wrap"><table><thead><tr><th>Data</th><th>Ação</th><th>Usuário / quantidade</th></tr></thead><tbody id="audit"></tbody></table></div></section>
|
||||
</div>
|
||||
<p id="message" role="status" aria-live="polite" hidden></p>
|
||||
</main><footer>INCTG · Tecnologia que resolve.</footer>
|
||||
</body></html>
|
||||
@@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
let token = '';
|
||||
let users = [];
|
||||
let noticeTimer;
|
||||
const $ = id => document.getElementById(id);
|
||||
function message(text, error = false) {
|
||||
$('message').textContent = text; $('message').className = error ? 'error' : ''; $('message').hidden = false;
|
||||
clearTimeout(noticeTimer); noticeTimer = setTimeout(() => $('message').hidden = true, 8000);
|
||||
}
|
||||
function logout() {
|
||||
token = ''; users = []; $('token').value = ''; $('login').hidden = false; $('dashboard').hidden = true;
|
||||
for (const id of ['users', 'payments', 'audit', 'newCredentials']) $(id).replaceChildren();
|
||||
$('credentials').hidden = true;
|
||||
}
|
||||
async function api(path, options = {}) {
|
||||
const res = await fetch('/api/admin' + path, { ...options, headers: { 'x-admin-token': token, ...(options.body ? { 'Content-Type': 'application/json' } : {}) }, cache: 'no-store' });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (res.status === 401) logout();
|
||||
throw new Error(data.error || 'Não foi possível concluir a operação.');
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function cell(row, text) { const td = document.createElement('td'); td.textContent = text ?? '—'; row.append(td); return td; }
|
||||
function date(value) { return value ? new Date(value).toLocaleString('pt-BR') : '—'; }
|
||||
function renderUsers() {
|
||||
const q = $('search').value.trim().toLowerCase(), filter = $('filter').value;
|
||||
const visible = users.filter(u => JSON.stringify(u).toLowerCase().includes(q) && (filter === 'all' || filter === 'blocked' && u.disabled || filter === 'online' && u.sessions.length || filter === 'offline' && !u.sessions.length));
|
||||
$('users').replaceChildren(); $('empty').hidden = visible.length > 0;
|
||||
for (const u of visible) {
|
||||
const row = document.createElement('tr');
|
||||
const name = cell(row, u.name); const profile = document.createElement('small'); profile.textContent = u.profile; name.append(profile);
|
||||
const state = cell(row, ''); const badge = document.createElement('span'); badge.className = 'badge ' + (u.disabled ? 'blocked' : u.sessions.length ? 'online' : ''); badge.textContent = u.disabled ? 'Bloqueado' : u.sessions.length ? 'Online' : 'Offline'; state.append(badge);
|
||||
cell(row, u.sessions.map(s => [s.ip, s.mac].filter(Boolean).join(' · ')).join('\n') || '—');
|
||||
cell(row, u.uptime + ' / ' + (u.limitUptime === '0s' ? 'Sem limite' : u.limitUptime));
|
||||
cell(row, ((u.bytesIn + u.bytesOut) / 1048576).toFixed(1) + ' MB');
|
||||
const action = cell(row, ''); const button = document.createElement('button'); button.className = u.disabled ? 'secondary' : 'danger'; button.textContent = u.disabled ? 'Desbloquear' : 'Bloquear';
|
||||
button.onclick = async () => {
|
||||
if (!u.disabled && !confirm('Bloquear ' + u.name + ' e encerrar suas sessões?')) return;
|
||||
button.disabled = true;
|
||||
try { await api('/users/' + encodeURIComponent(u.id), { method: 'PATCH', body: JSON.stringify({ disabled: !u.disabled }) }); await refresh(); message('Usuário atualizado.'); }
|
||||
catch (e) { message(e.message + ' Atualize a lista para conferir o estado atual.', true); }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
action.append(button); $('users').append(row);
|
||||
}
|
||||
}
|
||||
async function refresh() {
|
||||
$('refresh').disabled = true;
|
||||
try {
|
||||
const results = await Promise.allSettled(['/users', '/payments', '/profiles', '/audit'].map(async path => (await api(path)).json()));
|
||||
if (!token) return;
|
||||
const errors = results.map((r, i) => r.status === 'rejected' ? ['Usuários', 'Pagamentos', 'Perfis', 'Atividade'][i] + ': ' + r.reason.message : null).filter(Boolean);
|
||||
if (results[0].status === 'fulfilled') {
|
||||
users = results[0].value; renderUsers(); $('total').textContent = users.length; $('online').textContent = users.filter(u => u.sessions.length).length; $('blocked').textContent = users.filter(u => u.disabled).length;
|
||||
} else { users = []; renderUsers(); for (const id of ['total','online','blocked']) $(id).textContent = '—'; }
|
||||
$('payments').replaceChildren(); $('revenue').textContent = '—';
|
||||
if (results[1].status === 'fulfilled') {
|
||||
const payments = results[1].value;
|
||||
$('revenue').textContent = payments.filter(p => p.status === 'paid').reduce((n,p) => n + p.price,0).toLocaleString('pt-BR',{style:'currency',currency:'BRL'});
|
||||
for (const p of payments) { const row = document.createElement('tr'); [date(p.createdAt), p.planId, Number(p.price).toLocaleString('pt-BR',{style:'currency',currency:'BRL'}), p.status, p.voucher?.user || '—'].forEach(v => cell(row,v)); $('payments').append(row); }
|
||||
}
|
||||
if (results[2].status === 'fulfilled') {
|
||||
const selected = $('profile').value; $('profile').replaceChildren();
|
||||
for (const p of results[2].value) { const o = document.createElement('option'); o.value = p.name; o.textContent = p.name + (p.rateLimit ? ' · ' + p.rateLimit : ''); $('profile').append(o); }
|
||||
if ([...$('profile').options].some(o => o.value === selected)) $('profile').value = selected;
|
||||
}
|
||||
$('audit').replaceChildren();
|
||||
if (results[3].status === 'fulfilled') for (const a of results[3].value) { const row = document.createElement('tr'); [date(a.at),a.action,a.target].forEach(v => cell(row,v)); $('audit').append(row); }
|
||||
$('updated').textContent = 'Última consulta: ' + new Date().toLocaleTimeString('pt-BR') + (errors.length ? ' · Há dados indisponíveis' : '');
|
||||
if (errors.length) message(errors.join(' | '), true);
|
||||
} finally { $('refresh').disabled = false; }
|
||||
}
|
||||
$('loginForm').onsubmit = async event => {
|
||||
event.preventDefault(); token = $('token').value.trim(); const button = event.submitter; button.disabled = true;
|
||||
try { await api('/audit'); $('token').value = ''; $('login').hidden = true; $('dashboard').hidden = false; await refresh(); }
|
||||
catch (e) { message(e.message, true); } finally { button.disabled = false; }
|
||||
};
|
||||
$('logout').onclick = logout;
|
||||
$('refresh').onclick = () => refresh().catch(e => message(e.message,true));
|
||||
$('search').oninput = renderUsers; $('filter').onchange = renderUsers;
|
||||
$('createForm').onsubmit = async event => {
|
||||
event.preventDefault(); const button = event.submitter; button.disabled = true;
|
||||
try {
|
||||
const data = Object.fromEntries(new FormData(event.target));
|
||||
const created = await (await api('/users',{method:'POST',body:JSON.stringify(data)})).json();
|
||||
$('newCredentials').textContent = 'Usuário: ' + created.name + '\nSenha: ' + created.password; $('credentials').hidden = false; event.target.reset(); await refresh(); message('Usuário criado.');
|
||||
} catch (e) { message(e.message,true); } finally { button.disabled = false; }
|
||||
};
|
||||
$('hideCredentials').onclick = () => { $('newCredentials').replaceChildren(); $('credentials').hidden = true; };
|
||||
$('export').onclick = async () => {
|
||||
$('export').disabled = true;
|
||||
try { const blob = await (await api('/users/export')).blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='hotspot-usuarios.csv'; a.click(); setTimeout(()=>URL.revokeObjectURL(url),1000); message('CSV exportado sem senhas.'); }
|
||||
catch(e) { message(e.message,true); } finally { $('export').disabled = false; }
|
||||
};
|
||||
@@ -602,6 +602,7 @@
|
||||
let toastTimer = null;
|
||||
let selectedPlanId = null;
|
||||
let mpDevice = null;
|
||||
let checkoutBusy = false;
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -690,6 +691,9 @@
|
||||
}
|
||||
|
||||
async function checkout(planId) {
|
||||
if (checkoutBusy) return;
|
||||
checkoutBusy = true;
|
||||
$('payerNext').disabled = true;
|
||||
try {
|
||||
const payerName = $('payerName').value.trim();
|
||||
const payerEmail = $('payerEmail').value.trim();
|
||||
@@ -705,6 +709,7 @@
|
||||
if (data.error) throw new Error(data.error);
|
||||
|
||||
currentPaymentId = data.paymentId;
|
||||
sessionStorage.setItem('paymentId', currentPaymentId);
|
||||
$('payTitle').textContent = data.planName + ' · ' + money(data.price);
|
||||
$('qrImg').src = data.qrCodeBase64 ? 'data:image/png;base64,' + data.qrCodeBase64 : '';
|
||||
$('copiaCola').textContent = data.copiaCola || '';
|
||||
@@ -715,6 +720,9 @@
|
||||
pollTimer = setInterval(verify, 6000);
|
||||
} catch (e) {
|
||||
toast('Erro: ' + e.message);
|
||||
} finally {
|
||||
checkoutBusy = false;
|
||||
$('payerNext').disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -730,6 +738,7 @@
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch('/api/status/' + encodeURIComponent(currentPaymentId));
|
||||
if (!res.ok) throw new Error('Falha na consulta');
|
||||
const data = await res.json();
|
||||
if (data.status === 'paid' && data.voucher) {
|
||||
clearInterval(pollTimer); pollTimer = null;
|
||||
@@ -763,7 +772,7 @@
|
||||
$('payerNext').addEventListener('click', () => checkout(selectedPlanId));
|
||||
|
||||
// ===== Login no hotspot (voucher) =====
|
||||
const HS_LOGIN = 'http://10.10.10.1/login';
|
||||
let HS_LOGIN = 'http://10.10.10.1/login';
|
||||
|
||||
function hsUrl(user, pass) {
|
||||
return HS_LOGIN + '?username=' + encodeURIComponent(user) + '&password=' + encodeURIComponent(pass);
|
||||
@@ -777,13 +786,22 @@
|
||||
const u = $('hsUser').value.trim();
|
||||
const p = $('hsPass').value;
|
||||
if (!u || !p) { toast('Informe usuário e senha'); return; }
|
||||
window.location.href = hsUrl(u, p);
|
||||
hotspotLogin(u, p);
|
||||
});
|
||||
|
||||
$('hsAutoLogin').addEventListener('click', () => {
|
||||
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
||||
hotspotLogin($('vUser').textContent, $('vPass').textContent);
|
||||
});
|
||||
|
||||
function hotspotLogin(user, pass, destination) {
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST'; form.action = HS_LOGIN;
|
||||
for (const [name, value] of Object.entries({ username: user, password: pass, ...(destination ? { dst: destination } : {}) })) {
|
||||
const field = document.createElement('input'); field.type = 'hidden'; field.name = name; field.value = value; form.append(field);
|
||||
}
|
||||
document.body.append(form); form.submit();
|
||||
}
|
||||
|
||||
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
|
||||
async function startFreeAccess() {
|
||||
if (!mac) return;
|
||||
@@ -796,7 +814,11 @@
|
||||
body: JSON.stringify({ mac }),
|
||||
});
|
||||
const d = await res.json();
|
||||
if (d.loginUrl) window.location.href = d.loginUrl;
|
||||
if (!res.ok) { sessionStorage.removeItem('freeTried'); return; }
|
||||
if (d.loginUrl) {
|
||||
const target = new URL(d.loginUrl);
|
||||
hotspotLogin(target.searchParams.get('username'), target.searchParams.get('password'), target.searchParams.get('dst'));
|
||||
}
|
||||
} catch { /* segue */ }
|
||||
}
|
||||
|
||||
@@ -805,14 +827,18 @@
|
||||
const res = await fetch('/api/config');
|
||||
const d = await res.json();
|
||||
if (d.ssid) $('ssidLabel').textContent = d.ssid;
|
||||
if (/^(?:\d{1,3}\.){3}\d{1,3}$/.test(d.hotspotIp)) HS_LOGIN = 'http://' + d.hotspotIp + '/login';
|
||||
} catch { /* usa padrao */ }
|
||||
}
|
||||
|
||||
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
|
||||
|
||||
loadSiteConfig();
|
||||
loadSiteConfig().then(startFreeAccess);
|
||||
loadPlans();
|
||||
startFreeAccess();
|
||||
if (sessionStorage.getItem('paymentId')) {
|
||||
currentPaymentId = sessionStorage.getItem('paymentId');
|
||||
verify();
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user