File size: 2,309 Bytes
9705b6c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
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);
/**
* Bans a user based on violation criteria.
*
* If the user's violation count is a multiple of the BAN_INTERVAL, the user will be banned.
* The duration of the ban is determined by the BAN_DURATION environment variable.
* If BAN_DURATION is not set or invalid, the user will not be banned.
* Sessions will be deleted and the refreshToken cookie will be cleared even with
* an invalid or nill duration, which is a "soft" ban; the user can remain active until
* access token expiry.
*
* @async
* @param {Object} req - Express request object containing user information.
* @param {Object} res - Express response object.
* @param {Object} errorMessage - Object containing user violation details.
* @param {string} errorMessage.type - Type of the violation.
* @param {string} errorMessage.user_id - ID of the user who committed the violation.
* @param {number} errorMessage.violation_count - Number of violations committed by the user.
*
* @returns {Promise<void>}
*
*/
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;
|