123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465 |
- import async from "async";
- import { isAdminRequired } from "./hooks";
- import moduleManager from "../../index";
- const DBModule = moduleManager.modules.db;
- const UtilsModule = moduleManager.modules.utils;
- const WSModule = moduleManager.modules.ws;
- const CacheModule = moduleManager.modules.cache;
- const PunishmentsModule = moduleManager.modules.punishments;
- CacheModule.runJob("SUB", {
- channel: "ip.ban",
- cb: data => {
- WSModule.runJob("EMIT_TO_ROOM", {
- room: "admin.punishments",
- args: ["event:admin.punishment.created", { data: { punishment: data.punishment } }]
- });
- WSModule.runJob("SOCKETS_FROM_IP", { ip: data.ip }, this).then(sockets => {
- sockets.forEach(socket => {
- socket.disconnect(true);
- });
- });
- }
- });
- export default {
-
- getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
- const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
- async.waterfall(
- [
-
- next => next(null, []),
-
- (pipeline, next) => {
-
- const statusFilterExists = queries.map(query => query.filter.property).indexOf("status") !== -1;
-
- const statusPropertyExists = properties.indexOf("status") !== -1;
-
- if (!statusFilterExists && !statusPropertyExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- status: {
- $cond: [
- { $eq: ["$active", true] },
- { $cond: [{ $gt: [new Date(), "$expiresAt"] }, "Inactive", "Active"] },
- "Inactive"
- ]
- }
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
-
- const valueFilterExists = queries.map(query => query.filter.property).indexOf("value") !== -1;
-
- if (!valueFilterExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- valueOID: {
- $convert: {
- input: "$value",
- to: "objectId",
- onError: "unknown",
- onNull: "unknown"
- }
- }
- }
- });
-
- pipeline.push({
- $lookup: {
- from: "users",
- localField: "valueOID",
- foreignField: "_id",
- as: "valueUser"
- }
- });
-
- pipeline.push({
- $unwind: {
- path: "$valueUser",
- preserveNullAndEmptyArrays: true
- }
- });
-
- pipeline.push({
- $addFields: {
- valueUsername: {
- $cond: [
- { $eq: ["$type", "banUserId"] },
- { $ifNull: ["$valueUser.username", "unknown"] },
- null
- ]
- }
- }
- });
-
- pipeline.push({
- $project: {
- valueOID: 0,
- valueUser: 0
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
-
- const punishedByFilterExists =
- queries.map(query => query.filter.property).indexOf("punishedBy") !== -1;
-
- if (!punishedByFilterExists) return next(null, pipeline);
-
- pipeline.push({
- $addFields: {
- punishedByOID: {
- $convert: {
- input: "$punishedBy",
- to: "objectId",
- onError: "unknown",
- onNull: "unknown"
- }
- }
- }
- });
-
- pipeline.push({
- $lookup: {
- from: "users",
- localField: "punishedByOID",
- foreignField: "_id",
- as: "punishedByUser"
- }
- });
-
- pipeline.push({
- $unwind: {
- path: "$punishedByUser",
- preserveNullAndEmptyArrays: true
- }
- });
-
- pipeline.push({
- $addFields: {
- punishedByUsername: {
- $ifNull: ["$punishedByUser.username", "unknown"]
- }
- }
- });
-
- pipeline.push({
- $project: {
- punishedByOID: 0,
- punishedByUser: 0
- }
- });
- return next(null, pipeline);
- },
-
- (pipeline, next) => {
- let queryError;
- const newQueries = queries.flatMap(query => {
- const { data, filter, filterType } = query;
- const newQuery = {};
- if (filterType === "regex") {
- newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
- } else if (filterType === "contains") {
- newQuery[filter.property] = new RegExp(
- `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
- "i"
- );
- } else if (filterType === "exact") {
- newQuery[filter.property] = data.toString();
- } else if (filterType === "datetimeBefore") {
- newQuery[filter.property] = { $lte: new Date(data) };
- } else if (filterType === "datetimeAfter") {
- newQuery[filter.property] = { $gte: new Date(data) };
- } else if (filterType === "numberLesserEqual") {
- newQuery[filter.property] = { $lte: data };
- } else if (filterType === "numberLesser") {
- newQuery[filter.property] = { $lt: data };
- } else if (filterType === "numberGreater") {
- newQuery[filter.property] = { $gt: data };
- } else if (filterType === "numberGreaterEqual") {
- newQuery[filter.property] = { $gte: data };
- } else if (filterType === "numberEquals" || filterType === "boolean") {
- newQuery[filter.property] = { $eq: data };
- }
- if (filter.property === "value") return { $or: [newQuery, { valueUsername: newQuery.value }] };
- if (filter.property === "punishedBy")
- return { $or: [newQuery, { punishedByUsername: newQuery.punishedBy }] };
- return newQuery;
- });
- if (queryError) next(queryError);
- const queryObject = {};
- if (newQueries.length > 0) {
- if (operator === "and") queryObject.$and = newQueries;
- else if (operator === "or") queryObject.$or = newQueries;
- else if (operator === "nor") queryObject.$nor = newQueries;
- }
- pipeline.push({ $match: queryObject });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- const newSort = Object.fromEntries(
- Object.entries(sort).map(([property, direction]) => [
- property,
- direction === "ascending" ? 1 : -1
- ])
- );
- if (Object.keys(newSort).length > 0) pipeline.push({ $sort: newSort });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- pipeline.push({ $project: Object.fromEntries(properties.map(property => [property, 1])) });
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- pipeline.push({
- $facet: {
- count: [{ $count: "count" }],
- documents: [{ $skip: pageSize * (page - 1) }, { $limit: pageSize }]
- }
- });
-
- next(null, pipeline);
- },
-
- (pipeline, next) => {
- punishmentModel.aggregate(pipeline).exec((err, result) => {
-
-
- if (err) return next(err);
- if (result[0].count.length === 0) return next(null, 0, []);
- const { count } = result[0].count[0];
- const { documents } = result[0];
-
- return next(null, count, documents);
- });
- }
- ],
- async (err, count, punishments) => {
- if (err && err !== true) {
- err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
- this.log("ERROR", "PUNISHMENTS_GET_DATA", `Failed to get data from punishments. "${err}"`);
- return cb({ status: "error", message: err });
- }
- this.log("SUCCESS", "PUNISHMENTS_GET_DATA", `Got data from punishments successfully.`);
- return cb({
- status: "success",
- message: "Successfully got data from punishments.",
- data: { data: punishments, count }
- });
- }
- );
- }),
-
- getPunishmentsForUser: isAdminRequired(async function getPunishmentsForUser(session, userId, cb) {
- const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
- punishmentModel.find({ type: "banUserId", value: userId }, async (err, punishments) => {
- if (err) {
- err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
- this.log(
- "ERROR",
- "GET_PUNISHMENTS_FOR_USER",
- `Getting punishments for user ${userId} failed. "${err}"`
- );
- return cb({ status: "error", message: err });
- }
- this.log("SUCCESS", "GET_PUNISHMENTS_FOR_USER", `Got punishments for user ${userId} successful.`);
- return cb({ status: "success", data: { punishments } });
- });
- }),
-
- findOne: isAdminRequired(async function findOne(session, punishmentId, cb) {
- const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
- async.waterfall([next => punishmentModel.findOne({ _id: punishmentId }, next)], async (err, punishment) => {
- if (err) {
- err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
- this.log(
- "ERROR",
- "GET_PUNISHMENT_BY_ID",
- `Getting punishment with id ${punishmentId} failed. "${err}"`
- );
- return cb({ status: "error", message: err });
- }
- this.log("SUCCESS", "GET_PUNISHMENT_BY_ID", `Got punishment with id ${punishmentId} successful.`);
- return cb({ status: "success", data: { punishment } });
- });
- }),
-
- banIP: isAdminRequired(function banIP(session, value, reason, expiresAt, cb) {
- async.waterfall(
- [
- next => {
- if (!value) return next("You must provide an IP address to ban.");
- if (!reason) return next("You must provide a reason for the ban.");
- return next();
- },
- next => {
- if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
- const date = new Date();
- switch (expiresAt) {
- case "1h":
- expiresAt = date.setHours(date.getHours() + 1);
- break;
- case "12h":
- expiresAt = date.setHours(date.getHours() + 12);
- break;
- case "1d":
- expiresAt = date.setDate(date.getDate() + 1);
- break;
- case "1w":
- expiresAt = date.setDate(date.getDate() + 7);
- break;
- case "1m":
- expiresAt = date.setMonth(date.getMonth() + 1);
- break;
- case "3m":
- expiresAt = date.setMonth(date.getMonth() + 3);
- break;
- case "6m":
- expiresAt = date.setMonth(date.getMonth() + 6);
- break;
- case "1y":
- expiresAt = date.setFullYear(date.getFullYear() + 1);
- break;
- case "never":
- expiresAt = new Date(3093527980800000);
- break;
- default:
- return next("Invalid expire date.");
- }
- return next();
- },
- next => {
- PunishmentsModule.runJob(
- "ADD_PUNISHMENT",
- {
- type: "banUserIp",
- value,
- reason,
- expiresAt,
- punishedBy: session.userId
- },
- this
- )
- .then(punishment => {
- next(null, punishment);
- })
- .catch(next);
- }
- ],
- async (err, punishment) => {
- if (err && err !== true) {
- err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
- this.log(
- "ERROR",
- "BAN_IP",
- `User ${session.userId} failed to ban IP address ${value} with the reason ${reason}. '${err}'`
- );
- cb({ status: "error", message: err });
- }
- this.log(
- "SUCCESS",
- "BAN_IP",
- `User ${session.userId} has successfully banned IP address ${value} with the reason ${reason}.`
- );
- CacheModule.runJob("PUB", {
- channel: "ip.ban",
- value: { ip: value, punishment }
- });
- return cb({
- status: "success",
- message: "Successfully banned IP address."
- });
- }
- );
- })
- };
|