From a8a4bf7f6abd9a37f71a2df1bf68d5e0ddf89503 Mon Sep 17 00:00:00 2001 From: Douglas Barone Date: Thu, 14 Jan 2021 10:07:29 -0400 Subject: [PATCH] Refactor --- server/src/lib/paloalto.js | 88 +++++++++++++++++++------------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/server/src/lib/paloalto.js b/server/src/lib/paloalto.js index 68c9b66..bda2a1c 100644 --- a/server/src/lib/paloalto.js +++ b/server/src/lib/paloalto.js @@ -7,56 +7,58 @@ import { subMinutes } from 'date-fns' import qs from 'qs' import { logError, logSuccess } from './logger' -const DEBOUNCE_TIME_IN_MS = 5000 const TIMEOUT_IN_MINUTES = '3' const httpsAgent = new https.Agent({ rejectUnauthorized: false }) -let working = false - -async function updateUserIdMappings() { - if (working) return -1 - - working = true - +async function getDevicesWithUserFromNet(network) { const now = new Date() const timeoutThreshold = subMinutes(now, TIMEOUT_IN_MINUTES) + const wifiDevices = await prisma.wifiDevice.findMany({ + where: { + userId: { not: null }, + status: 'ONLINE', + lastSeen: { gt: timeoutThreshold }, + ip: { startsWith: network } + }, + select: { + ip: true, + user: { select: { sAMAccountName: true } } + } + }) + return wifiDevices +} + +function createCommand(devices) { + const entries = devices.reduce( + (entries, device) => + entries + + `\n`, + '' + ) + + return ` + + 1.0 + update + + + ${entries} + + + ` +} + +async function updateUserIdMappings() { try { - const wifiDevices = await prisma.wifiDevice.findMany({ - where: { - userId: { not: null }, - status: 'ONLINE', - lastSeen: { gt: timeoutThreshold }, - ip: { startsWith: process.env.PA_NET } - }, - select: { - ip: true, - user: { select: { sAMAccountName: true } } - } - }) + const devices = await getDevicesWithUserFromNet(process.env.PA_NET) - if (wifiDevices.length == 0) return 0 + if (devices.length == 0) return 0 - const entries = wifiDevices.reduce( - (entries, device) => - entries + - `\n`, - '' - ) - - const cmd = ` - - 1.0 - update - - - ${entries} - - - ` + const cmd = createCommand(devices) await axios({ url: `https://${process.env.PA_HOST}/api/`, @@ -73,11 +75,11 @@ async function updateUserIdMappings() { logSuccess({ tags: ['user-id', 'paloalto'], - message: `Updated ${wifiDevices.length} user-id mappings`, - data: wifiDevices + message: `Updated ${devices.length} user-id mappings`, + data: devices }) - return wifiDevices.length + return devices.length } catch (e) { logError({ tags: ['paloalto', 'user-id'], @@ -86,10 +88,6 @@ async function updateUserIdMappings() { }) return 'Não foi possível atualizar. Veja o log do servidor' - } finally { - setTimeout(() => { - working = false - }, DEBOUNCE_TIME_IN_MS) } }