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 toastTimer = null;
|
||||||
let selectedPlanId = null;
|
let selectedPlanId = null;
|
||||||
let mpDevice = null;
|
let mpDevice = null;
|
||||||
let freeTimer = null;
|
|
||||||
let freeGrants = 0;
|
|
||||||
|
|
||||||
const $ = (id) => document.getElementById(id);
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
@@ -655,8 +653,7 @@
|
|||||||
$('view-pay').classList.toggle('hidden', view !== 'pay');
|
$('view-pay').classList.toggle('hidden', view !== 'pay');
|
||||||
$('view-voucher').classList.toggle('hidden', view !== 'voucher');
|
$('view-voucher').classList.toggle('hidden', view !== 'voucher');
|
||||||
if (view !== 'pay' && pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
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' });
|
window.scrollTo({ top: 0, behavior: 'instant' in window ? 'auto' : 'auto' });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -787,11 +784,11 @@
|
|||||||
window.location.href = hsUrl($('vUser').textContent, $('vPass').textContent);
|
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() {
|
async function startFreeAccess() {
|
||||||
if (!mac) return;
|
if (!mac) return;
|
||||||
if (freeGrants >= 12) return;
|
if (sessionStorage.getItem('freeOk') || sessionStorage.getItem('freeTried')) return;
|
||||||
freeGrants++;
|
sessionStorage.setItem('freeTried', '1');
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/access/start', {
|
const res = await fetch('/api/access/start', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -799,10 +796,7 @@
|
|||||||
body: JSON.stringify({ mac }),
|
body: JSON.stringify({ mac }),
|
||||||
});
|
});
|
||||||
const d = await res.json();
|
const d = await res.json();
|
||||||
if (d.ok) {
|
if (d.loginUrl) window.location.href = d.loginUrl;
|
||||||
const mins = Math.round((d.seconds / 60) * 10) / 10;
|
|
||||||
toast('Internet liberada por ' + mins + ' min para pagar');
|
|
||||||
}
|
|
||||||
} catch { /* segue */ }
|
} catch { /* segue */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -814,6 +808,8 @@
|
|||||||
} catch { /* usa padrao */ }
|
} catch { /* usa padrao */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (new URLSearchParams(location.search).get('free') === '1') sessionStorage.setItem('freeOk', '1');
|
||||||
|
|
||||||
loadSiteConfig();
|
loadSiteConfig();
|
||||||
loadPlans();
|
loadPlans();
|
||||||
startFreeAccess();
|
startFreeAccess();
|
||||||
|
|||||||
@@ -15,8 +15,10 @@ const config = {
|
|||||||
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
server: process.env.MIKROTIK_SERVER || 'guest-hotspot',
|
||||||
},
|
},
|
||||||
port: parseInt(process.env.PORT || '3000', 10),
|
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',
|
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',
|
baseUrl: process.env.BASE_URL || 'http://192.168.3.100:3000',
|
||||||
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
adminToken: process.env.ADMIN_TOKEN || 'dev-token',
|
||||||
dataDir: process.env.DATA_DIR || path.join(__dirname, '..', 'data'),
|
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 || {};
|
const { mac } = req.body || {};
|
||||||
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
|
if (!mac) return res.status(400).json({ error: 'mac obrigatorio' });
|
||||||
try {
|
try {
|
||||||
const r = await allowPaymentAccess(mac);
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const db = getDb();
|
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 = (db.tempAccess || []).filter((t) => t.mac !== mac);
|
||||||
db.tempAccess.push({
|
db.tempAccess.push({
|
||||||
mac,
|
mac,
|
||||||
ip: r.ip,
|
user: r.user,
|
||||||
|
loginUrl,
|
||||||
createdAt: new Date(now).toISOString(),
|
createdAt: new Date(now).toISOString(),
|
||||||
expiresAt: now + config.freeAccessSeconds * 1000,
|
expiresAt: now + config.freeAccessSeconds * 1000,
|
||||||
});
|
});
|
||||||
saveDb();
|
saveDb();
|
||||||
res.json({ ok: true, seconds: config.freeAccessSeconds, ip: r.ip });
|
|
||||||
|
res.json({ ok: true, seconds: config.freeAccessSeconds, loginUrl, user: r.user });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[ACESSO]', e.message);
|
console.error('[ACESSO]', e.message);
|
||||||
res.status(500).json({ error: 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);
|
err ? reject(err) : resolve(val);
|
||||||
};
|
};
|
||||||
const timer = setTimeout(() => finish(new Error('timeout MikroTik API')), timeoutMs);
|
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('error', (e) => finish(e));
|
||||||
socket.on('close', () => {
|
socket.on('close', () => {
|
||||||
if (!settled) finish(new Error('conexao MikroTik fechada'));
|
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');
|
if (!mac) throw new Error('mac obrigatorio');
|
||||||
const ip = await hostAddressByMac(mac);
|
await ensureFreeProfile();
|
||||||
|
const name = freeUserName(mac);
|
||||||
// bypass do hotspot por MAC (funciona mesmo antes do login)
|
const pass = 'F' + Math.random().toString(36).slice(2, 9).toUpperCase();
|
||||||
try {
|
await removeUserByName(name);
|
||||||
await rosCommand(['/ip/hotspot/ip-binding/add', `=mac-address=${mac}`, '=type=bypassed', '=comment=pix-pagando']);
|
await rosCommand([
|
||||||
} catch (e) {
|
'/ip/hotspot/user/add',
|
||||||
if (!/already|duplicate/i.test(e.message)) throw e;
|
`=server=${config.mikrotik.server}`,
|
||||||
}
|
`=name=${name}`,
|
||||||
|
`=password=${pass}`,
|
||||||
// limite de banda para essa liberacao temporaria
|
'=profile=pix-free',
|
||||||
if (ip) {
|
`=limit-uptime=${minutes}m`,
|
||||||
try {
|
]);
|
||||||
await rosCommand(['/queue/simple/add', `=name=pixpagando-${mac}`, `=target=${ip}/32`, `=max-limit=${speed}`]);
|
return { user: name, pass, mac };
|
||||||
} catch (e) {
|
|
||||||
if (!/already|duplicate/i.test(e.message)) throw e;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { ip, mac };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function pickField(row, key) {
|
function pickField(row, key) {
|
||||||
@@ -201,6 +234,8 @@ export async function paymentAccessStatus(mac) {
|
|||||||
|
|
||||||
export async function revokePaymentAccess(mac) {
|
export async function revokePaymentAccess(mac) {
|
||||||
if (!mac) return;
|
if (!mac) return;
|
||||||
|
await removeActiveByMac(mac);
|
||||||
|
await removeUserByName(freeUserName(mac));
|
||||||
try {
|
try {
|
||||||
const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);
|
const bindings = await rosCommand(['/ip/hotspot/ip-binding/print', `?mac-address=${mac}`]);
|
||||||
for (const row of bindings || []) {
|
for (const row of bindings || []) {
|
||||||
|
|||||||
Reference in new issue
Block a user