punishments.js 11 KB

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