This commit is contained in:
Douglas Barone 2021-01-14 10:07:29 -04:00
parent 00097c68d2
commit a8a4bf7f6a

View File

@ -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 +
`<entry name="ifms\\${device.user.sAMAccountName}" ip="${device.ip}" timeout="${TIMEOUT_IN_MINUTES}"/>\n`,
''
)
return `
<uid-message>
<version>1.0</version>
<type>update</type>
<payload>
<login>
${entries}
</login>
</payload>
</uid-message>`
}
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 +
`<entry name="ifms\\${device.user.sAMAccountName}" ip="${device.ip}" timeout="${TIMEOUT_IN_MINUTES}"/>\n`,
''
)
const cmd = `
<uid-message>
<version>1.0</version>
<type>update</type>
<payload>
<login>
${entries}
</login>
</payload>
</uid-message>`
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)
}
}