punishments.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 === "numberLesser") {
  58. newQuery[filter.property] = { $lt: data };
  59. } else if (filterType === "numberGreater") {
  60. newQuery[filter.property] = { $gt: data };
  61. } else if (filterType === "numberEquals") {
  62. newQuery[filter.property] = { $eq: data };
  63. }
  64. return newQuery;
  65. });
  66. const queryObject = {};
  67. if (newQueries.length > 0) {
  68. if (operator === "and") queryObject.$and = newQueries;
  69. else if (operator === "or") queryObject.$or = newQueries;
  70. else if (operator === "nor") queryObject.$nor = newQueries;
  71. }
  72. next(null, queryObject);
  73. },
  74. (queryObject, next) => {
  75. punishmentModel.find(queryObject).count((err, count) => {
  76. next(err, queryObject, count);
  77. });
  78. },
  79. (queryObject, count, next) => {
  80. punishmentModel
  81. .find(queryObject)
  82. .sort(sort)
  83. .skip(pageSize * (page - 1))
  84. .limit(pageSize)
  85. .select(properties.join(" "))
  86. .exec((err, punishments) => {
  87. next(err, count, punishments);
  88. });
  89. }
  90. ],
  91. async (err, count, punishments) => {
  92. if (err && err !== true) {
  93. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  94. this.log("ERROR", "PUNISHMENTS_GET_DATA", `Failed to get data from punishments. "${err}"`);
  95. return cb({ status: "error", message: err });
  96. }
  97. this.log("SUCCESS", "PUNISHMENTS_GET_DATA", `Got data from punishments successfully.`);
  98. return cb({
  99. status: "success",
  100. message: "Successfully got data from punishments.",
  101. data: { data: punishments, count }
  102. });
  103. }
  104. );
  105. }),
  106. /**
  107. * Gets all punishments for a user
  108. *
  109. * @param {object} session - the session object automatically added by the websocket
  110. * @param {string} userId - the id of the user
  111. * @param {Function} cb - gets called with the result
  112. */
  113. getPunishmentsForUser: isAdminRequired(async function getPunishmentsForUser(session, userId, cb) {
  114. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  115. punishmentModel.find({ type: "banUserId", value: userId }, async (err, punishments) => {
  116. if (err) {
  117. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  118. this.log(
  119. "ERROR",
  120. "GET_PUNISHMENTS_FOR_USER",
  121. `Getting punishments for user ${userId} failed. "${err}"`
  122. );
  123. return cb({ status: "error", message: err });
  124. }
  125. this.log("SUCCESS", "GET_PUNISHMENTS_FOR_USER", `Got punishments for user ${userId} successful.`);
  126. return cb({ status: "success", data: { punishments } });
  127. });
  128. }),
  129. /**
  130. * Returns a punishment by id
  131. *
  132. * @param {object} session - the session object automatically added by the websocket
  133. * @param {string} punishmentId - the punishment id
  134. * @param {Function} cb - gets called with the result
  135. */
  136. findOne: isAdminRequired(async function findOne(session, punishmentId, cb) {
  137. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  138. async.waterfall([next => punishmentModel.findOne({ _id: punishmentId }, next)], async (err, punishment) => {
  139. if (err) {
  140. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  141. this.log(
  142. "ERROR",
  143. "GET_PUNISHMENT_BY_ID",
  144. `Getting punishment with id ${punishmentId} failed. "${err}"`
  145. );
  146. return cb({ status: "error", message: err });
  147. }
  148. this.log("SUCCESS", "GET_PUNISHMENT_BY_ID", `Got punishment with id ${punishmentId} successful.`);
  149. return cb({ status: "success", data: { punishment } });
  150. });
  151. }),
  152. /**
  153. * Bans an IP address
  154. *
  155. * @param {object} session - the session object automatically added by the websocket
  156. * @param {string} value - the ip address that is going to be banned
  157. * @param {string} reason - the reason for the ban
  158. * @param {string} expiresAt - the time the ban expires
  159. * @param {Function} cb - gets called with the result
  160. */
  161. banIP: isAdminRequired(function banIP(session, value, reason, expiresAt, cb) {
  162. async.waterfall(
  163. [
  164. next => {
  165. if (!value) return next("You must provide an IP address to ban.");
  166. if (!reason) return next("You must provide a reason for the ban.");
  167. return next();
  168. },
  169. next => {
  170. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  171. const date = new Date();
  172. switch (expiresAt) {
  173. case "1h":
  174. expiresAt = date.setHours(date.getHours() + 1);
  175. break;
  176. case "12h":
  177. expiresAt = date.setHours(date.getHours() + 12);
  178. break;
  179. case "1d":
  180. expiresAt = date.setDate(date.getDate() + 1);
  181. break;
  182. case "1w":
  183. expiresAt = date.setDate(date.getDate() + 7);
  184. break;
  185. case "1m":
  186. expiresAt = date.setMonth(date.getMonth() + 1);
  187. break;
  188. case "3m":
  189. expiresAt = date.setMonth(date.getMonth() + 3);
  190. break;
  191. case "6m":
  192. expiresAt = date.setMonth(date.getMonth() + 6);
  193. break;
  194. case "1y":
  195. expiresAt = date.setFullYear(date.getFullYear() + 1);
  196. break;
  197. case "never":
  198. expiresAt = new Date(3093527980800000);
  199. break;
  200. default:
  201. return next("Invalid expire date.");
  202. }
  203. return next();
  204. },
  205. next => {
  206. PunishmentsModule.runJob(
  207. "ADD_PUNISHMENT",
  208. {
  209. type: "banUserIp",
  210. value,
  211. reason,
  212. expiresAt,
  213. punishedBy: session.userId
  214. },
  215. this
  216. )
  217. .then(punishment => {
  218. next(null, punishment);
  219. })
  220. .catch(next);
  221. }
  222. ],
  223. async (err, punishment) => {
  224. if (err && err !== true) {
  225. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  226. this.log(
  227. "ERROR",
  228. "BAN_IP",
  229. `User ${session.userId} failed to ban IP address ${value} with the reason ${reason}. '${err}'`
  230. );
  231. cb({ status: "error", message: err });
  232. }
  233. this.log(
  234. "SUCCESS",
  235. "BAN_IP",
  236. `User ${session.userId} has successfully banned IP address ${value} with the reason ${reason}.`
  237. );
  238. CacheModule.runJob("PUB", {
  239. channel: "ip.ban",
  240. value: { ip: value, punishment }
  241. });
  242. return cb({
  243. status: "success",
  244. message: "Successfully banned IP address."
  245. });
  246. }
  247. );
  248. })
  249. };