|
const Session = require('../models/Session'); |
|
const getLogStores = require('./getLogStores'); |
|
const { isEnabled, math, removePorts } = require('../server/utils'); |
|
const { BAN_VIOLATIONS, BAN_INTERVAL } = process.env ?? {}; |
|
const interval = math(BAN_INTERVAL, 20); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const banViolation = async (req, res, errorMessage) => { |
|
if (!isEnabled(BAN_VIOLATIONS)) { |
|
return; |
|
} |
|
|
|
if (!errorMessage) { |
|
return; |
|
} |
|
|
|
const { type, user_id, prev_count, violation_count } = errorMessage; |
|
|
|
const prevThreshold = Math.floor(prev_count / interval); |
|
const currentThreshold = Math.floor(violation_count / interval); |
|
|
|
if (prevThreshold >= currentThreshold) { |
|
return; |
|
} |
|
|
|
await Session.deleteAllUserSessions(user_id); |
|
res.clearCookie('refreshToken'); |
|
|
|
const banLogs = getLogStores('ban'); |
|
const duration = banLogs.opts.ttl; |
|
|
|
if (duration <= 0) { |
|
return; |
|
} |
|
|
|
req.ip = removePorts(req); |
|
console.log(`[BAN] Banning user ${user_id} @ ${req.ip} for ${duration / 1000 / 60} minutes`); |
|
const expiresAt = Date.now() + duration; |
|
await banLogs.set(user_id, { type, violation_count, duration, expiresAt }); |
|
await banLogs.set(req.ip, { type, user_id, violation_count, duration, expiresAt }); |
|
|
|
errorMessage.ban = true; |
|
errorMessage.ban_duration = duration; |
|
|
|
return; |
|
}; |
|
|
|
module.exports = banViolation; |
|
|