punishments.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import async from "async";
  2. import { useHasPermission } from "../hooks/hasPermission";
  3. // eslint-disable-next-line
  4. import moduleManager from "../../index";
  5. const DBModule = moduleManager.modules.db;
  6. const UtilsModule = moduleManager.modules.utils;
  7. const WSModule = moduleManager.modules.ws;
  8. const CacheModule = moduleManager.modules.cache;
  9. const PunishmentsModule = moduleManager.modules.punishments;
  10. CacheModule.runJob("SUB", {
  11. channel: "ip.ban",
  12. cb: data => {
  13. WSModule.runJob("EMIT_TO_ROOM", {
  14. room: "admin.punishments",
  15. args: ["event:admin.punishment.created", { data: { punishment: data.punishment } }]
  16. });
  17. WSModule.runJob("SOCKETS_FROM_IP", { ip: data.ip }, this).then(sockets => {
  18. sockets.forEach(socket => {
  19. socket.close();
  20. });
  21. });
  22. }
  23. });
  24. export default {
  25. /**
  26. * Gets punishments, used in the admin punishments page by the AdvancedTable component
  27. *
  28. * @param {object} session - the session object automatically added by the websocket
  29. * @param page - the page
  30. * @param pageSize - the size per page
  31. * @param properties - the properties to return for each punishment
  32. * @param sort - the sort object
  33. * @param queries - the queries array
  34. * @param operator - the operator for queries
  35. * @param cb
  36. */
  37. getData: useHasPermission(
  38. "admin.view.punishments",
  39. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  40. async.waterfall(
  41. [
  42. next => {
  43. DBModule.runJob(
  44. "GET_DATA",
  45. {
  46. page,
  47. pageSize,
  48. properties,
  49. sort,
  50. queries,
  51. operator,
  52. modelName: "punishment",
  53. blacklistedProperties: [],
  54. specialProperties: {
  55. status: [
  56. {
  57. $addFields: {
  58. status: {
  59. $cond: [
  60. { $eq: ["$active", true] },
  61. {
  62. $cond: [
  63. { $gt: [new Date(), "$expiresAt"] },
  64. "Inactive",
  65. "Active"
  66. ]
  67. },
  68. "Inactive"
  69. ]
  70. }
  71. }
  72. }
  73. ],
  74. value: [
  75. {
  76. $addFields: {
  77. valueOID: {
  78. $convert: {
  79. input: "$value",
  80. to: "objectId",
  81. onError: "unknown",
  82. onNull: "unknown"
  83. }
  84. }
  85. }
  86. },
  87. {
  88. $lookup: {
  89. from: "users",
  90. localField: "valueOID",
  91. foreignField: "_id",
  92. as: "valueUser"
  93. }
  94. },
  95. {
  96. $unwind: {
  97. path: "$valueUser",
  98. preserveNullAndEmptyArrays: true
  99. }
  100. },
  101. {
  102. $addFields: {
  103. valueUsername: {
  104. $cond: [
  105. { $eq: ["$type", "banUserId"] },
  106. { $ifNull: ["$valueUser.username", "unknown"] },
  107. null
  108. ]
  109. }
  110. }
  111. },
  112. {
  113. $project: {
  114. valueOID: 0,
  115. valueUser: 0
  116. }
  117. }
  118. ],
  119. punishedBy: [
  120. {
  121. $addFields: {
  122. punishedByOID: {
  123. $convert: {
  124. input: "$punishedBy",
  125. to: "objectId",
  126. onError: "unknown",
  127. onNull: "unknown"
  128. }
  129. }
  130. }
  131. },
  132. {
  133. $lookup: {
  134. from: "users",
  135. localField: "punishedByOID",
  136. foreignField: "_id",
  137. as: "punishedByUser"
  138. }
  139. },
  140. {
  141. $unwind: {
  142. path: "$punishedByUser",
  143. preserveNullAndEmptyArrays: true
  144. }
  145. },
  146. {
  147. $addFields: {
  148. punishedByUsername: {
  149. $ifNull: ["$punishedByUser.username", "unknown"]
  150. }
  151. }
  152. },
  153. {
  154. $project: {
  155. punishedByOID: 0,
  156. punishedByUser: 0
  157. }
  158. }
  159. ]
  160. },
  161. specialQueries: {
  162. value: newQuery => ({ $or: [newQuery, { valueUsername: newQuery.value }] }),
  163. punishedBy: newQuery => ({
  164. $or: [newQuery, { punishedByUsername: newQuery.punishedBy }]
  165. })
  166. }
  167. },
  168. this
  169. )
  170. .then(response => {
  171. next(null, response);
  172. })
  173. .catch(err => {
  174. next(err);
  175. });
  176. }
  177. ],
  178. async (err, response) => {
  179. if (err && err !== true) {
  180. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  181. this.log("ERROR", "PUNISHMENTS_GET_DATA", `Failed to get data from punishments. "${err}"`);
  182. return cb({ status: "error", message: err });
  183. }
  184. this.log("SUCCESS", "PUNISHMENTS_GET_DATA", `Got data from punishments successfully.`);
  185. return cb({
  186. status: "success",
  187. message: "Successfully got data from punishments.",
  188. data: response
  189. });
  190. }
  191. );
  192. }
  193. ),
  194. /**
  195. * Gets all punishments for a user
  196. *
  197. * @param {object} session - the session object automatically added by the websocket
  198. * @param {string} userId - the id of the user
  199. * @param {Function} cb - gets called with the result
  200. */
  201. getPunishmentsForUser: useHasPermission(
  202. "punishments.get",
  203. async function getPunishmentsForUser(session, userId, cb) {
  204. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  205. punishmentModel.find({ type: "banUserId", value: userId }, async (err, punishments) => {
  206. if (err) {
  207. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  208. this.log(
  209. "ERROR",
  210. "GET_PUNISHMENTS_FOR_USER",
  211. `Getting punishments for user ${userId} failed. "${err}"`
  212. );
  213. return cb({ status: "error", message: err });
  214. }
  215. this.log("SUCCESS", "GET_PUNISHMENTS_FOR_USER", `Got punishments for user ${userId} successful.`);
  216. return cb({ status: "success", data: { punishments } });
  217. });
  218. }
  219. ),
  220. /**
  221. * Returns a punishment by id
  222. *
  223. * @param {object} session - the session object automatically added by the websocket
  224. * @param {string} punishmentId - the punishment id
  225. * @param {Function} cb - gets called with the result
  226. */
  227. findOne: useHasPermission("punishments.get", async function findOne(session, punishmentId, cb) {
  228. const punishmentModel = await DBModule.runJob("GET_MODEL", { modelName: "punishment" }, this);
  229. async.waterfall([next => punishmentModel.findOne({ _id: punishmentId }, next)], async (err, punishment) => {
  230. if (err) {
  231. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  232. this.log(
  233. "ERROR",
  234. "GET_PUNISHMENT_BY_ID",
  235. `Getting punishment with id ${punishmentId} failed. "${err}"`
  236. );
  237. return cb({ status: "error", message: err });
  238. }
  239. this.log("SUCCESS", "GET_PUNISHMENT_BY_ID", `Got punishment with id ${punishmentId} successful.`);
  240. return cb({ status: "success", data: { punishment } });
  241. });
  242. }),
  243. /**
  244. * Bans an IP address
  245. *
  246. * @param {object} session - the session object automatically added by the websocket
  247. * @param {string} value - the ip address that is going to be banned
  248. * @param {string} reason - the reason for the ban
  249. * @param {string} expiresAt - the time the ban expires
  250. * @param {Function} cb - gets called with the result
  251. */
  252. banIP: useHasPermission("punishments.banIP", function banIP(session, value, reason, expiresAt, cb) {
  253. async.waterfall(
  254. [
  255. next => {
  256. if (!value) return next("You must provide an IP address to ban.");
  257. if (!reason) return next("You must provide a reason for the ban.");
  258. return next();
  259. },
  260. next => {
  261. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  262. const date = new Date();
  263. switch (expiresAt) {
  264. case "1h":
  265. expiresAt = date.setHours(date.getHours() + 1);
  266. break;
  267. case "12h":
  268. expiresAt = date.setHours(date.getHours() + 12);
  269. break;
  270. case "1d":
  271. expiresAt = date.setDate(date.getDate() + 1);
  272. break;
  273. case "1w":
  274. expiresAt = date.setDate(date.getDate() + 7);
  275. break;
  276. case "1m":
  277. expiresAt = date.setMonth(date.getMonth() + 1);
  278. break;
  279. case "3m":
  280. expiresAt = date.setMonth(date.getMonth() + 3);
  281. break;
  282. case "6m":
  283. expiresAt = date.setMonth(date.getMonth() + 6);
  284. break;
  285. case "1y":
  286. expiresAt = date.setFullYear(date.getFullYear() + 1);
  287. break;
  288. case "never":
  289. expiresAt = new Date(3093527980800000);
  290. break;
  291. default:
  292. return next("Invalid expire date.");
  293. }
  294. return next();
  295. },
  296. next => {
  297. PunishmentsModule.runJob(
  298. "ADD_PUNISHMENT",
  299. {
  300. type: "banUserIp",
  301. value,
  302. reason,
  303. expiresAt,
  304. punishedBy: session.userId
  305. },
  306. this
  307. )
  308. .then(punishment => {
  309. next(null, punishment);
  310. })
  311. .catch(next);
  312. }
  313. ],
  314. async (err, punishment) => {
  315. if (err && err !== true) {
  316. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  317. this.log(
  318. "ERROR",
  319. "BAN_IP",
  320. `User ${session.userId} failed to ban IP address ${value} with the reason ${reason}. '${err}'`
  321. );
  322. cb({ status: "error", message: err });
  323. }
  324. this.log(
  325. "SUCCESS",
  326. "BAN_IP",
  327. `User ${session.userId} has successfully banned IP address ${value} with the reason ${reason}.`
  328. );
  329. CacheModule.runJob("PUB", {
  330. channel: "ip.ban",
  331. value: { ip: value, punishment }
  332. });
  333. return cb({
  334. status: "success",
  335. message: "Successfully banned IP address."
  336. });
  337. }
  338. );
  339. }),
  340. /**
  341. * Deactivates a punishment
  342. *
  343. * @param {object} session - the session object automatically added by the websocket
  344. * @param {string} punishmentId - the MongoDB id of the punishment
  345. * @param {Function} cb - gets called with the result
  346. */
  347. deactivatePunishment: useHasPermission(
  348. "punishments.deactivate",
  349. function deactivatePunishment(session, punishmentId, cb) {
  350. async.waterfall(
  351. [
  352. next => {
  353. PunishmentsModule.runJob("DEACTIVATE_PUNISHMENT", { punishmentId }, this)
  354. .then(punishment => next(null, punishment._doc))
  355. .catch(next);
  356. }
  357. ],
  358. async (err, punishment) => {
  359. if (err) {
  360. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  361. this.log(
  362. "ERROR",
  363. "DEACTIVATE_PUNISHMENT",
  364. `Deactivating punishment ${punishmentId} failed. "${err}"`
  365. );
  366. return cb({ status: "error", message: err });
  367. }
  368. this.log("SUCCESS", "DEACTIVATE_PUNISHMENT", `Deactivated punishment ${punishmentId} successful.`);
  369. WSModule.runJob("EMIT_TO_ROOM", {
  370. room: `admin.punishments`,
  371. args: [
  372. "event:admin.punishment.updated",
  373. {
  374. data: {
  375. punishment: { ...punishment, status: "Inactive" }
  376. }
  377. }
  378. ]
  379. });
  380. return cb({ status: "success" });
  381. }
  382. );
  383. }
  384. )
  385. };