punishments.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import async from "async";
  2. import { isAdminRequired } from "./hooks";
  3. import moduleManager from "../../index";
  4. const DBModule = moduleManager.modules.db;
  5. const UtilsModule = moduleManager.modules.utils;
  6. const WSModule = moduleManager.modules.ws;
  7. const CacheModule = moduleManager.modules.cache;
  8. const PunishmentsModule = moduleManager.modules.punishments;
  9. CacheModule.runJob("SUB", {
  10. channel: "ip.ban",
  11. cb: data => {
  12. WSModule.runJob("EMIT_TO_ROOM", {
  13. room: "admin.punishments",
  14. args: ["event:admin.punishment.created", { data: { punishment: data.punishment } }]
  15. });
  16. WSModule.runJob("SOCKETS_FROM_IP", { ip: data.ip }, this).then(sockets => {
  17. sockets.forEach(socket => {
  18. socket.disconnect(true);
  19. });
  20. });
  21. }
  22. });
  23. export default {
  24. /**
  25. * Gets punishments, used in the admin punishments page by the AdvancedTable component
  26. *
  27. * @param {object} session - the session object automatically added by the websocket
  28. * @param page - the page
  29. * @param pageSize - the size per page
  30. * @param properties - the properties to return for each punishment
  31. * @param sort - the sort object
  32. * @param queries - the queries array
  33. * @param operator - the operator for queries
  34. * @param cb
  35. */
  36. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  37. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  38. async.waterfall(
  39. [
  40. next => {
  41. const newQueries = queries.map(query => {
  42. const { data, filter, filterType } = query;
  43. const newQuery = {};
  44. if (filterType === "regex") {
  45. newQuery[filter.property] = new RegExp(`${data.slice(1, data.length - 1)}`, "i");
  46. } else if (filterType === "contains") {
  47. newQuery[filter.property] = new RegExp(
  48. `${data.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}`,
  49. "i"
  50. );
  51. } else if (filterType === "exact") {
  52. newQuery[filter.property] = data.toString();
  53. } else if (filterType === "datetimeBefore") {
  54. newQuery[filter.property] = { $lte: new Date(data) };
  55. } else if (filterType === "datetimeAfter") {
  56. newQuery[filter.property] = { $gte: new Date(data) };
  57. } else if (filterType === "numberLesserEqual") {
  58. newQuery[filter.property] = { $lte: data };
  59. } else if (filterType === "numberLesser") {
  60. newQuery[filter.property] = { $lt: data };
  61. } else if (filterType === "numberGreater") {
  62. newQuery[filter.property] = { $gt: data };
  63. } else if (filterType === "numberGreaterEqual") {
  64. newQuery[filter.property] = { $gte: data };
  65. } else if (filterType === "numberEquals") {
  66. newQuery[filter.property] = { $eq: data };
  67. }
  68. return newQuery;
  69. });
  70. const queryObject = {};
  71. if (newQueries.length > 0) {
  72. if (operator === "and") queryObject.$and = newQueries;
  73. else if (operator === "or") queryObject.$or = newQueries;
  74. else if (operator === "nor") queryObject.$nor = newQueries;
  75. }
  76. next(null, queryObject);
  77. },
  78. (queryObject, next) => {
  79. punishmentModel.find(queryObject).count((err, count) => {
  80. next(err, queryObject, count);
  81. });
  82. },
  83. (queryObject, count, next) => {
  84. punishmentModel
  85. .find(queryObject)
  86. .sort(sort)
  87. .skip(pageSize * (page - 1))
  88. .limit(pageSize)
  89. .select(properties.join(" "))
  90. .exec((err, punishments) => {
  91. next(err, count, punishments);
  92. });
  93. }
  94. ],
  95. async (err, count, punishments) => {
  96. if (err && err !== true) {
  97. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  98. this.log("ERROR", "PUNISHMENTS_GET_DATA", `Failed to get data from punishments. "${err}"`);
  99. return cb({ status: "error", message: err });
  100. }
  101. this.log("SUCCESS", "PUNISHMENTS_GET_DATA", `Got data from punishments successfully.`);
  102. return cb({
  103. status: "success",
  104. message: "Successfully got data from punishments.",
  105. data: { data: punishments, count }
  106. });
  107. }
  108. );
  109. }),
  110. /**
  111. * Gets all punishments for a user
  112. *
  113. * @param {object} session - the session object automatically added by the websocket
  114. * @param {string} userId - the id of the user
  115. * @param {Function} cb - gets called with the result
  116. */
  117. getPunishmentsForUser: isAdminRequired(async function getPunishmentsForUser(session, userId, cb) {
  118. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  119. punishmentModel.find({ type: "banUserId", value: userId }, async (err, punishments) => {
  120. if (err) {
  121. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  122. this.log(
  123. "ERROR",
  124. "GET_PUNISHMENTS_FOR_USER",
  125. `Getting punishments for user ${userId} failed. "${err}"`
  126. );
  127. return cb({ status: "error", message: err });
  128. }
  129. this.log("SUCCESS", "GET_PUNISHMENTS_FOR_USER", `Got punishments for user ${userId} successful.`);
  130. return cb({ status: "success", data: { punishments } });
  131. });
  132. }),
  133. /**
  134. * Returns a punishment by id
  135. *
  136. * @param {object} session - the session object automatically added by the websocket
  137. * @param {string} punishmentId - the punishment id
  138. * @param {Function} cb - gets called with the result
  139. */
  140. findOne: isAdminRequired(async function findOne(session, punishmentId, cb) {
  141. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  142. async.waterfall([next => punishmentModel.findOne({ _id: punishmentId }, next)], async (err, punishment) => {
  143. if (err) {
  144. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  145. this.log(
  146. "ERROR",
  147. "GET_PUNISHMENT_BY_ID",
  148. `Getting punishment with id ${punishmentId} failed. "${err}"`
  149. );
  150. return cb({ status: "error", message: err });
  151. }
  152. this.log("SUCCESS", "GET_PUNISHMENT_BY_ID", `Got punishment with id ${punishmentId} successful.`);
  153. return cb({ status: "success", data: { punishment } });
  154. });
  155. }),
  156. /**
  157. * Bans an IP address
  158. *
  159. * @param {object} session - the session object automatically added by the websocket
  160. * @param {string} value - the ip address that is going to be banned
  161. * @param {string} reason - the reason for the ban
  162. * @param {string} expiresAt - the time the ban expires
  163. * @param {Function} cb - gets called with the result
  164. */
  165. banIP: isAdminRequired(function banIP(session, value, reason, expiresAt, cb) {
  166. async.waterfall(
  167. [
  168. next => {
  169. if (!value) return next("You must provide an IP address to ban.");
  170. if (!reason) return next("You must provide a reason for the ban.");
  171. return next();
  172. },
  173. next => {
  174. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  175. const date = new Date();
  176. switch (expiresAt) {
  177. case "1h":
  178. expiresAt = date.setHours(date.getHours() + 1);
  179. break;
  180. case "12h":
  181. expiresAt = date.setHours(date.getHours() + 12);
  182. break;
  183. case "1d":
  184. expiresAt = date.setDate(date.getDate() + 1);
  185. break;
  186. case "1w":
  187. expiresAt = date.setDate(date.getDate() + 7);
  188. break;
  189. case "1m":
  190. expiresAt = date.setMonth(date.getMonth() + 1);
  191. break;
  192. case "3m":
  193. expiresAt = date.setMonth(date.getMonth() + 3);
  194. break;
  195. case "6m":
  196. expiresAt = date.setMonth(date.getMonth() + 6);
  197. break;
  198. case "1y":
  199. expiresAt = date.setFullYear(date.getFullYear() + 1);
  200. break;
  201. case "never":
  202. expiresAt = new Date(3093527980800000);
  203. break;
  204. default:
  205. return next("Invalid expire date.");
  206. }
  207. return next();
  208. },
  209. next => {
  210. PunishmentsModule.runJob(
  211. "ADD_PUNISHMENT",
  212. {
  213. type: "banUserIp",
  214. value,
  215. reason,
  216. expiresAt,
  217. punishedBy: session.userId
  218. },
  219. this
  220. )
  221. .then(punishment => {
  222. next(null, punishment);
  223. })
  224. .catch(next);
  225. }
  226. ],
  227. async (err, punishment) => {
  228. if (err && err !== true) {
  229. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  230. this.log(
  231. "ERROR",
  232. "BAN_IP",
  233. `User ${session.userId} failed to ban IP address ${value} with the reason ${reason}. '${err}'`
  234. );
  235. cb({ status: "error", message: err });
  236. }
  237. this.log(
  238. "SUCCESS",
  239. "BAN_IP",
  240. `User ${session.userId} has successfully banned IP address ${value} with the reason ${reason}.`
  241. );
  242. CacheModule.runJob("PUB", {
  243. channel: "ip.ban",
  244. value: { ip: value, punishment }
  245. });
  246. return cb({
  247. status: "success",
  248. message: "Successfully banned IP address."
  249. });
  250. }
  251. );
  252. })
  253. };