fix(ros): remove listener que abortava a API apos o login; liberacao de 2min via login automatico
build-image / build-push (push) Successful in 1m47s
build-image / build-push (push) Successful in 1m47s
This commit is contained in:
1 parent
8e65d092e2
commit
fb3135d18f
4 files changed
+90
-39
No files matched your search
@@ -602,8 +602,6 @@
|
||||
let toastTimer = null;
|
||||
let selectedPlanId = null;
|
||||
let mpDevice = null;
|
||||
let freeTimer = null;
|
||||
let freeGrants = 0;
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -655,8 +653,7 @@
|
||||
$('view-pay').classList.toggle('hidden', view !== 'pay');
|
||||
$('view-voucher').classList.toggle('hidden', view !== 'voucher');
|
||||
if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||
if (view !== 'pay' && freeTimer) { clearInterval(freeTimer); freeTimer = null; }
|
||||
if (view === 'pay' && !freeTimer) { freeTimer = setInterval(startFreeAccess, 120000); }
|
||||
|
||||
window.scrollTo({ top: 0, behavior: 'instant' in window ? 'auto' : 'auto' });
|
||||
}
|
||||
|
||||
@@ -787,11 +784,11 @@
|
||||
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
||||
});
|
||||
|
||||
// ===== Internet temporaria para pagar (abre o app do banco) =====
|
||||
// ===== Internet temporaria para pagar (login automatico no hotspot) =====
|
||||
async function startFreeAccess() {
|
||||
if (!mac) return;
|
||||
if (freeGrants >= 12) return;
|
||||
freeGrants++;
|
||||
if (sessionStorage.getItem('freeOk') || sessionStorage.getItem('freeTried')) return;
|
||||
sessionStorage.setItem('freeTried', '1');
|
||||
try {
|
||||
const res = await fetch('/api/access/start', {
|
||||
method: 'POST',
|
||||
@@ -799,10 +796,7 @@
|
||||
body: JSON.stringify({ mac }),
|
||||
});
|
||||
const d = await res.json();
|
||||
if (d.ok) {
|
||||
const mins = Math.round((d.seconds / 60) * 10) / 10;
|
||||
toast('Internet liberada por ' + mins + ' min para pagar');
|
||||
}
|
||||
if (d.loginUrl) window.location.href = d.loginUrl;
|
||||
} catch { /* segue */ }
|
||||
}
|
||||
|
||||
@@ -814,6 +808,8 @@
|
||||
} catch { /* usa padrao */ }
|
||||
}
|
||||
|
||||
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
|
||||
|
||||
loadSiteConfig();
|
||||
loadPlans();
|
||||
startFreeAccess();
|
||||
|
||||
@@ -15,8 +15,10 @@ const config = {
|
||||
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
||||
},
|
||||
port: parseInt(process.env.PORT || '3000', 10),
|
||||
freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 600),
|
||||
freeAccessSeconds: Number(process.env.FREE_ACCESS_SECONDS || 120),
|
||||
freeAccessCooldownSeconds: Number(process.env.FREE_ACCESS_COOLDOWN_SECONDS || 300),
|
||||
ssidName: process.env.SSID_NAME || 'Internet Gratis',
|
||||
hotspotIp: process.env.HOTSPOT_IP || '10.10.10.1',
|
||||
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
||||
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
||||
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
||||
|
||||
+21
-3
@@ -53,18 +53,36 @@ app.post('/api/access/start', async (req, res) => {
|
||||
const { mac } = req.body || {};
|
||||
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
|
||||
try {
|
||||
const r = await allowPaymentAccess(mac);
|
||||
const now = Date.now();
|
||||
const db = getDb();
|
||||
const prev = (db.tempAccess || []).find((t) => t.mac === mac);
|
||||
|
||||
// reusa a janela criada ha menos de X minutos (evita abuso de janelas ilimitadas)
|
||||
if (prev && prev.loginUrl && now - Date.parse(prev.createdAt) < config.freeAccessCooldownSeconds * 1000) {
|
||||
return res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl: prev.loginUrl, reused: true });
|
||||
}
|
||||
|
||||
const minutes = Math.max(1, Math.round(config.freeAccessSeconds / 60));
|
||||
const r = await allowPaymentAccess(mac, minutes);
|
||||
|
||||
const back = encodeURIComponent(config.baseUrl + '/?mac=' + encodeURIComponent(mac) + '&free=1');
|
||||
const loginUrl =
|
||||
`http://${config.hotspotIp}/login` +
|
||||
`?username=${encodeURIComponent(r.user)}` +
|
||||
`&password=${encodeURIComponent(r.pass)}` +
|
||||
`&dst=${back}`;
|
||||
|
||||
db.tempAccess = (db.tempAccess || []).filter((t) => t.mac !== mac);
|
||||
db.tempAccess.push({
|
||||
mac,
|
||||
ip: r.ip,
|
||||
user: r.user,
|
||||
loginUrl,
|
||||
createdAt: new Date(now).toISOString(),
|
||||
expiresAt: now + config.freeAccessSeconds * 1000,
|
||||
});
|
||||
saveDb();
|
||||
res.json({ ok: true, seconds: config.freeAccessSeconds, ip: r.ip });
|
||||
|
||||
res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user });
|
||||
} catch (e) {
|
||||
console.error('[ACESSO]', e.message);
|
||||
res.status(500).json({ error: e.message });
|
||||
|
||||
+59
-24
@@ -87,11 +87,6 @@ async function rosCommand(words, timeoutMs = 8000) {
|
||||
err ? reject(err) : resolve(val);
|
||||
};
|
||||
const timer = setTimeout(() => finish(new Error('timeout MikroTik API')), timeoutMs);
|
||||
socket.on('data', (chunk) => {
|
||||
parser.push(chunk);
|
||||
if (parser.error) finish(new Error(parser.error));
|
||||
else if (parser.done) finish(null, parser.replies);
|
||||
});
|
||||
socket.on('error', (e) => finish(e));
|
||||
socket.on('close', () => {
|
||||
if (!settled) finish(new Error('conexao MikroTik fechada'));
|
||||
@@ -158,26 +153,64 @@ async function hostAddressByMac(mac) {
|
||||
}
|
||||
}
|
||||
|
||||
export async function allowPaymentAccess(mac, speed = '3M/3M') {
|
||||
function freeUserName(mac) {
|
||||
return 'FREE' + String(mac || '').replace(/[^0-9A-Fa-f]/g, '').slice(-10).toUpperCase();
|
||||
}
|
||||
|
||||
async function removeUserByName(name) {
|
||||
try {
|
||||
const rows = await rosCommand(['/ip/hotspot/user/print', `?name=${name}`]);
|
||||
for (const row of rows || []) {
|
||||
const id = pickField(row, '=.id=');
|
||||
if (id) await rosCommand(['/ip/hotspot/user/remove', `=numbers=${id}`]);
|
||||
}
|
||||
} catch { /* ignora */ }
|
||||
}
|
||||
|
||||
async function ensureFreeProfile(rateLimit = '3M/3M') {
|
||||
try {
|
||||
const rows = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']);
|
||||
if (rows && rows.length) {
|
||||
const id = pickField(rows[0], '=.id=');
|
||||
if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]);
|
||||
return;
|
||||
}
|
||||
// neste RouterOS o rate-limit nao e aceito no add: cria e depois define
|
||||
await rosCommand(['/ip/hotspot/user/profile/add', '=name=pix-free', '=shared-users=1']);
|
||||
const again = await rosCommand(['/ip/hotspot/user/profile/print', '?name=pix-free']);
|
||||
const id = pickField((again || [])[0], '=.id=');
|
||||
if (id) await rosCommand(['/ip/hotspot/user/profile/set', `=numbers=${id}`, `=rate-limit=${rateLimit}`]);
|
||||
} catch (e) {
|
||||
console.error('[PERFIL pix-free]', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeActiveByMac(mac) {
|
||||
try {
|
||||
const rows = await rosCommand(['/ip/hotspot/active/print', `?mac-address=${mac}`]);
|
||||
for (const row of rows || []) {
|
||||
const id = pickField(row, '=.id=');
|
||||
if (id) await rosCommand(['/ip/hotspot/active/remove', `=numbers=${id}`]);
|
||||
}
|
||||
} catch { /* ignora */ }
|
||||
}
|
||||
|
||||
// Cria um usuario temporario do hotspot (o portal faz login automatico nele)
|
||||
export async function allowPaymentAccess(mac, minutes = 10) {
|
||||
if (!mac) throw new Error('mac obrigatorio');
|
||||
const ip = await hostAddressByMac(mac);
|
||||
|
||||
// bypass do hotspot por MAC (funciona mesmo antes do login)
|
||||
try {
|
||||
await rosCommand(['/ip/hotspot/ip-binding/add', `=mac-address=${mac}`, '=type=bypassed', '=comment=pix-pagando']);
|
||||
} catch (e) {
|
||||
if (!/already|duplicate/i.test(e.message)) throw e;
|
||||
}
|
||||
|
||||
// limite de banda para essa liberacao temporaria
|
||||
if (ip) {
|
||||
try {
|
||||
await rosCommand(['/queue/simple/add', `=name=pixpagando-${mac}`, `=target=${ip}/32`, `=max-limit=${speed}`]);
|
||||
} catch (e) {
|
||||
if (!/already|duplicate/i.test(e.message)) throw e;
|
||||
}
|
||||
}
|
||||
return { ip, mac };
|
||||
await ensureFreeProfile();
|
||||
const name = freeUserName(mac);
|
||||
const pass = 'F' + Math.random().toString(36).slice(2, 9).toUpperCase();
|
||||
await removeUserByName(name);
|
||||
await rosCommand([
|
||||
'/ip/hotspot/user/add',
|
||||
`=server=${config.mikrotik.server}`,
|
||||
`=name=${name}`,
|
||||
`=password=${pass}`,
|
||||
'=profile=pix-free',
|
||||
`=limit-uptime=${minutes}m`,
|
||||
]);
|
||||
return { user: name, pass, mac };
|
||||
}
|
||||
|
||||
function pickField(row, key) {
|
||||
@@ -201,6 +234,8 @@ export async function paymentAccessStatus(mac) {
|
||||
|
||||
export async function revokePaymentAccess(mac) {
|
||||
if (!mac) return;
|
||||
await removeActiveByMac(mac);
|
||||
await removeUserByName(freeUserName(mac));
|
||||
try {
|
||||
const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);
|
||||
for (const row of bindings || []) {
|
||||
|
||||
Reference in new issue
Block a user