punishments.js 8.0 KB

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