punishments.js 7.8 KB

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