users.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  1. import config from "config";
  2. import async from "async";
  3. import axios from "axios";
  4. import bcrypt from "bcrypt";
  5. import sha256 from "sha256";
  6. import { isAdminRequired, isLoginRequired } from "./hooks";
  7. import moduleManager from "../../index";
  8. const DBModule = moduleManager.modules.db;
  9. const UtilsModule = moduleManager.modules.utils;
  10. const IOModule = moduleManager.modules.io;
  11. const CacheModule = moduleManager.modules.cache;
  12. const MailModule = moduleManager.modules.mail;
  13. const PunishmentsModule = moduleManager.modules.punishments;
  14. const ActivitiesModule = moduleManager.modules.activities;
  15. const PlaylistsModule = moduleManager.modules.playlists;
  16. CacheModule.runJob("SUB", {
  17. channel: "user.updatePreferences",
  18. cb: res => {
  19. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }).then(response => {
  20. response.sockets.forEach(socket => {
  21. socket.emit("keep.event:user.preferences.changed", res.preferences);
  22. });
  23. });
  24. }
  25. });
  26. CacheModule.runJob("SUB", {
  27. channel: "user.updateOrderOfPlaylists",
  28. cb: res => {
  29. IOModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(response => {
  30. response.sockets.forEach(socket => {
  31. socket.emit("event:user.orderOfPlaylists.changed", res.orderOfPlaylists);
  32. });
  33. });
  34. IOModule.runJob("EMIT_TO_ROOM", {
  35. room: `profile-${res.userId}`,
  36. args: ["event:user.orderOfPlaylists.changed", res.orderOfPlaylists]
  37. });
  38. }
  39. });
  40. CacheModule.runJob("SUB", {
  41. channel: "user.updateUsername",
  42. cb: user => {
  43. IOModule.runJob("SOCKETS_FROM_USER", { userId: user._id }).then(response => {
  44. response.sockets.forEach(socket => {
  45. socket.emit("event:user.username.changed", user.username);
  46. });
  47. });
  48. }
  49. });
  50. CacheModule.runJob("SUB", {
  51. channel: "user.removeSessions",
  52. cb: userId => {
  53. IOModule.runJob("SOCKETS_FROM_USER_WITHOUT_CACHE", { userId }).then(response => {
  54. response.sockets.forEach(socket => {
  55. socket.emit("keep.event:user.session.removed");
  56. });
  57. });
  58. }
  59. });
  60. CacheModule.runJob("SUB", {
  61. channel: "user.linkPassword",
  62. cb: userId => {
  63. IOModule.runJob("SOCKETS_FROM_USER", { userId }).then(response => {
  64. response.sockets.forEach(socket => {
  65. socket.emit("event:user.linkPassword");
  66. });
  67. });
  68. }
  69. });
  70. CacheModule.runJob("SUB", {
  71. channel: "user.unlinkPassword",
  72. cb: userId => {
  73. IOModule.runJob("SOCKETS_FROM_USER", { userId }).then(response => {
  74. response.sockets.forEach(socket => {
  75. socket.emit("event:user.unlinkPassword");
  76. });
  77. });
  78. }
  79. });
  80. CacheModule.runJob("SUB", {
  81. channel: "user.linkGithub",
  82. cb: userId => {
  83. IOModule.runJob("SOCKETS_FROM_USER", { userId }).then(response => {
  84. response.sockets.forEach(socket => {
  85. socket.emit("event:user.linkGithub");
  86. });
  87. });
  88. }
  89. });
  90. CacheModule.runJob("SUB", {
  91. channel: "user.unlinkGithub",
  92. cb: userId => {
  93. IOModule.runJob("SOCKETS_FROM_USER", { userId }).then(response => {
  94. response.sockets.forEach(socket => {
  95. socket.emit("event:user.unlinkGithub");
  96. });
  97. });
  98. }
  99. });
  100. CacheModule.runJob("SUB", {
  101. channel: "user.ban",
  102. cb: data => {
  103. IOModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(response => {
  104. response.sockets.forEach(socket => {
  105. socket.emit("keep.event:banned", data.punishment);
  106. socket.disconnect(true);
  107. });
  108. });
  109. }
  110. });
  111. CacheModule.runJob("SUB", {
  112. channel: "user.favoritedStation",
  113. cb: data => {
  114. IOModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(response => {
  115. response.sockets.forEach(socket => {
  116. socket.emit("event:user.favoritedStation", data.stationId);
  117. });
  118. });
  119. }
  120. });
  121. CacheModule.runJob("SUB", {
  122. channel: "user.unfavoritedStation",
  123. cb: data => {
  124. IOModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(response => {
  125. response.sockets.forEach(socket => {
  126. socket.emit("event:user.unfavoritedStation", data.stationId);
  127. });
  128. });
  129. }
  130. });
  131. export default {
  132. /**
  133. * Lists all Users
  134. *
  135. * @param {object} session - the session object automatically added by socket.io
  136. * @param {Function} cb - gets called with the result
  137. */
  138. index: isAdminRequired(async function index(session, cb) {
  139. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  140. async.waterfall(
  141. [
  142. next => {
  143. userModel.find({}).exec(next);
  144. }
  145. ],
  146. async (err, users) => {
  147. if (err) {
  148. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  149. this.log("ERROR", "USER_INDEX", `Indexing users failed. "${err}"`);
  150. return cb({ status: "failure", message: err });
  151. }
  152. this.log("SUCCESS", "USER_INDEX", `Indexing users successful.`);
  153. const filteredUsers = [];
  154. users.forEach(user => {
  155. filteredUsers.push({
  156. _id: user._id,
  157. name: user.name,
  158. username: user.username,
  159. role: user.role,
  160. liked: user.liked,
  161. disliked: user.disliked,
  162. songsRequested: user.statistics.songsRequested,
  163. email: {
  164. address: user.email.address,
  165. verified: user.email.verified
  166. },
  167. avatar: {
  168. type: user.avatar.type,
  169. url: user.avatar.url,
  170. color: user.avatar.color
  171. },
  172. hasPassword: !!user.services.password,
  173. services: { github: user.services.github }
  174. });
  175. });
  176. return cb({ status: "success", data: filteredUsers });
  177. }
  178. );
  179. }),
  180. /**
  181. * Logs user in
  182. *
  183. * @param {object} session - the session object automatically added by socket.io
  184. * @param {string} identifier - the email of the user
  185. * @param {string} password - the plaintext of the user
  186. * @param {Function} cb - gets called with the result
  187. */
  188. async login(session, identifier, password, cb) {
  189. identifier = identifier.toLowerCase();
  190. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  191. const sessionSchema = await CacheModule.runJob(
  192. "GET_SCHEMA",
  193. {
  194. schemaName: "session"
  195. },
  196. this
  197. );
  198. async.waterfall(
  199. [
  200. // check if a user with the requested identifier exists
  201. next => {
  202. userModel.findOne(
  203. {
  204. $or: [{ "email.address": identifier }]
  205. },
  206. next
  207. );
  208. },
  209. // if the user doesn't exist, respond with a failure
  210. // otherwise compare the requested password and the actual users password
  211. (user, next) => {
  212. if (!user) return next("User not found");
  213. if (!user.services.password || !user.services.password.password)
  214. return next("The account you are trying to access uses GitHub to log in.");
  215. return bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  216. if (err) return next(err);
  217. if (!match) return next("Incorrect password");
  218. return next(null, user);
  219. });
  220. },
  221. (user, next) => {
  222. UtilsModule.runJob("GUID", {}, this).then(sessionId => {
  223. next(null, user, sessionId);
  224. });
  225. },
  226. (user, sessionId, next) => {
  227. CacheModule.runJob(
  228. "HSET",
  229. {
  230. table: "sessions",
  231. key: sessionId,
  232. value: sessionSchema(sessionId, user._id)
  233. },
  234. this
  235. )
  236. .then(() => {
  237. next(null, sessionId);
  238. })
  239. .catch(next);
  240. }
  241. ],
  242. async (err, sessionId) => {
  243. if (err && err !== true) {
  244. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  245. this.log(
  246. "ERROR",
  247. "USER_PASSWORD_LOGIN",
  248. `Login failed with password for user "${identifier}". "${err}"`
  249. );
  250. return cb({ status: "failure", message: err });
  251. }
  252. this.log("SUCCESS", "USER_PASSWORD_LOGIN", `Login successful with password for user "${identifier}"`);
  253. return cb({
  254. status: "success",
  255. message: "Login successful",
  256. user: {},
  257. SID: sessionId
  258. });
  259. }
  260. );
  261. },
  262. /**
  263. * Registers a new user
  264. *
  265. * @param {object} session - the session object automatically added by socket.io
  266. * @param {string} username - the username for the new user
  267. * @param {string} email - the email for the new user
  268. * @param {string} password - the plaintext password for the new user
  269. * @param {object} recaptcha - the recaptcha data
  270. * @param {Function} cb - gets called with the result
  271. */
  272. async register(session, username, email, password, recaptcha, cb) {
  273. email = email.toLowerCase();
  274. const verificationToken = await UtilsModule.runJob(
  275. "GENERATE_RANDOM_STRING",
  276. {
  277. length: 64
  278. },
  279. this
  280. );
  281. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  282. const verifyEmailSchema = await MailModule.runJob(
  283. "GET_SCHEMA",
  284. {
  285. schemaName: "verifyEmail"
  286. },
  287. this
  288. );
  289. async.waterfall(
  290. [
  291. next => {
  292. if (config.get("registrationDisabled") === true)
  293. return next("Registration is not allowed at this time.");
  294. return next();
  295. },
  296. next => {
  297. if (!DBModule.passwordValid(password))
  298. return next("Invalid password. Check if it meets all the requirements.");
  299. return next();
  300. },
  301. // verify the request with google recaptcha
  302. next => {
  303. if (config.get("apis.recaptcha.enabled") === true)
  304. axios
  305. .post("https://www.google.com/recaptcha/api/siteverify", {
  306. data: {
  307. secret: config.get("apis").recaptcha.secret,
  308. response: recaptcha
  309. }
  310. })
  311. .then(res => next(null, res.data))
  312. .catch(err => next(err));
  313. else next(null, null, null);
  314. },
  315. // check if the response from Google recaptcha is successful
  316. // if it is, we check if a user with the requested username already exists
  317. (body, next) => {
  318. if (config.get("apis.recaptcha.enabled") === true)
  319. if (body.success !== true) return next("Response from recaptcha was not successful.");
  320. return userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  321. },
  322. // if the user already exists, respond with that
  323. // otherwise check if a user with the requested email already exists
  324. (user, next) => {
  325. if (user) return next("A user with that username already exists.");
  326. return userModel.findOne({ "email.address": email }, next);
  327. },
  328. // if the user already exists, respond with that
  329. // otherwise, generate a salt to use with hashing the new users password
  330. (user, next) => {
  331. if (user) return next("A user with that email already exists.");
  332. return bcrypt.genSalt(10, next);
  333. },
  334. // hash the password
  335. (salt, next) => {
  336. bcrypt.hash(sha256(password), salt, next);
  337. },
  338. (hash, next) => {
  339. UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 12 }, this).then(_id => {
  340. next(null, hash, _id);
  341. });
  342. },
  343. // create the user object
  344. (hash, _id, next) => {
  345. next(null, {
  346. _id,
  347. username,
  348. email: {
  349. address: email,
  350. verificationToken
  351. },
  352. services: {
  353. password: {
  354. password: hash
  355. }
  356. }
  357. });
  358. },
  359. // generate the url for gravatar avatar
  360. (user, next) => {
  361. UtilsModule.runJob(
  362. "CREATE_GRAVATAR",
  363. {
  364. email: user.email.address
  365. },
  366. this
  367. ).then(url => {
  368. user.avatar = {
  369. type: "gravatar",
  370. url
  371. };
  372. next(null, user);
  373. });
  374. },
  375. // save the new user to the database
  376. (user, next) => {
  377. userModel.create(user, next);
  378. },
  379. // respond with the new user
  380. (user, next) => {
  381. verifyEmailSchema(email, username, verificationToken, err => {
  382. next(err, user._id);
  383. });
  384. },
  385. // create a liked songs playlist for the new user
  386. (userId, next) => {
  387. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  388. userId,
  389. displayName: "Liked Songs",
  390. type: "user"
  391. })
  392. .then(likedSongsPlaylist => {
  393. next(null, likedSongsPlaylist, userId);
  394. })
  395. .catch(err => next(err));
  396. },
  397. // create a disliked songs playlist for the new user
  398. (likedSongsPlaylist, userId, next) => {
  399. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  400. userId,
  401. displayName: "Disliked Songs",
  402. type: "user"
  403. })
  404. .then(dislikedSongsPlaylist => {
  405. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  406. })
  407. .catch(err => next(err));
  408. },
  409. // associate liked + disliked songs playlist to the user object
  410. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  411. userModel.updateOne(
  412. { _id: userId },
  413. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  414. { runValidators: true },
  415. err => {
  416. if (err) return next(err);
  417. return next(null, userId);
  418. }
  419. );
  420. }
  421. ],
  422. async (err, user) => {
  423. if (err && err !== true) {
  424. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  425. this.log(
  426. "ERROR",
  427. "USER_PASSWORD_REGISTER",
  428. `Register failed with password for user "${username}"."${err}"`
  429. );
  430. return cb({ status: "failure", message: err });
  431. }
  432. ActivitiesModule.runJob("ADD_ACTIVITY", {
  433. userId: user._id,
  434. activityType: "created_account"
  435. });
  436. this.log(
  437. "SUCCESS",
  438. "USER_PASSWORD_REGISTER",
  439. `Register successful with password for user "${username}".`
  440. );
  441. const result = await this.module.runJob(
  442. "RUN_ACTION2",
  443. {
  444. session,
  445. namespace: "users",
  446. action: "login",
  447. args: [email, password]
  448. },
  449. this
  450. );
  451. const obj = {
  452. status: "success",
  453. message: "Successfully registered."
  454. };
  455. if (result.status === "success") {
  456. obj.SID = result.SID;
  457. }
  458. return cb(obj);
  459. }
  460. );
  461. },
  462. /**
  463. * Logs out a user
  464. *
  465. * @param {object} session - the session object automatically added by socket.io
  466. * @param {Function} cb - gets called with the result
  467. */
  468. logout(session, cb) {
  469. async.waterfall(
  470. [
  471. next => {
  472. CacheModule.runJob(
  473. "HGET",
  474. {
  475. table: "sessions",
  476. key: session.sessionId
  477. },
  478. this
  479. )
  480. .then(session => {
  481. next(null, session);
  482. })
  483. .catch(next);
  484. },
  485. (session, next) => {
  486. if (!session) return next("Session not found");
  487. return next(null, session);
  488. },
  489. (session, next) => {
  490. CacheModule.runJob(
  491. "HDEL",
  492. {
  493. table: "sessions",
  494. key: session.sessionId
  495. },
  496. this
  497. )
  498. .then(() => {
  499. next();
  500. })
  501. .catch(next);
  502. }
  503. ],
  504. async err => {
  505. if (err && err !== true) {
  506. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  507. this.log("ERROR", "USER_LOGOUT", `Logout failed. "${err}" `);
  508. cb({ status: "failure", message: err });
  509. } else {
  510. this.log("SUCCESS", "USER_LOGOUT", `Logout successful.`);
  511. cb({
  512. status: "success",
  513. message: "Successfully logged out."
  514. });
  515. }
  516. }
  517. );
  518. },
  519. /**
  520. * Removes all sessions for a user
  521. *
  522. * @param {object} session - the session object automatically added by socket.io
  523. * @param {string} userId - the id of the user we are trying to delete the sessions of
  524. * @param {Function} cb - gets called with the result
  525. */
  526. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  527. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  528. async.waterfall(
  529. [
  530. next => {
  531. userModel.findOne({ _id: session.userId }, (err, user) => {
  532. if (err) return next(err);
  533. if (user.role !== "admin" && session.userId !== userId)
  534. return next("Only admins and the owner of the account can remove their sessions.");
  535. return next();
  536. });
  537. },
  538. next => {
  539. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  540. .then(sessions => {
  541. next(null, sessions);
  542. })
  543. .catch(next);
  544. },
  545. (sessions, next) => {
  546. if (!sessions) return next("There are no sessions for this user to remove.");
  547. const keys = Object.keys(sessions);
  548. return next(null, keys, sessions);
  549. },
  550. (keys, sessions, next) => {
  551. CacheModule.runJob("PUB", {
  552. channel: "user.removeSessions",
  553. value: userId
  554. });
  555. async.each(
  556. keys,
  557. (sessionId, callback) => {
  558. const session = sessions[sessionId];
  559. if (session.userId === userId) {
  560. // TODO Also maybe add this to this runJob
  561. CacheModule.runJob("HDEL", {
  562. channel: "sessions",
  563. key: sessionId
  564. })
  565. .then(() => {
  566. callback(null);
  567. })
  568. .catch(next);
  569. }
  570. },
  571. err => {
  572. next(err);
  573. }
  574. );
  575. }
  576. ],
  577. async err => {
  578. if (err) {
  579. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  580. this.log(
  581. "ERROR",
  582. "REMOVE_SESSIONS_FOR_USER",
  583. `Couldn't remove all sessions for user "${userId}". "${err}"`
  584. );
  585. return cb({ status: "failure", message: err });
  586. }
  587. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  588. return cb({
  589. status: "success",
  590. message: "Successfully removed all sessions."
  591. });
  592. }
  593. );
  594. }),
  595. /**
  596. * Updates the order of a user's playlists
  597. *
  598. * @param {object} session - the session object automatically added by socket.io
  599. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  600. * @param {Function} cb - gets called with the result
  601. */
  602. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  603. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  604. async.waterfall(
  605. [
  606. next => {
  607. userModel.updateOne(
  608. { _id: session.userId },
  609. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  610. { runValidators: true },
  611. next
  612. );
  613. }
  614. ],
  615. async err => {
  616. if (err) {
  617. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  618. this.log(
  619. "ERROR",
  620. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  621. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  622. );
  623. return cb({ status: "failure", message: err });
  624. }
  625. CacheModule.runJob("PUB", {
  626. channel: "user.updateOrderOfPlaylists",
  627. value: {
  628. orderOfPlaylists,
  629. userId: session.userId
  630. }
  631. });
  632. this.log(
  633. "SUCCESS",
  634. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  635. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  636. );
  637. return cb({
  638. status: "success",
  639. message: "Order of playlists successfully updated"
  640. });
  641. }
  642. );
  643. }),
  644. /**
  645. * Updates a user's preferences
  646. *
  647. * @param {object} session - the session object automatically added by socket.io
  648. * @param {object} preferences - object containing preferences
  649. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  650. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  651. * @param {Function} cb - gets called with the result
  652. */
  653. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  654. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  655. async.waterfall(
  656. [
  657. next => {
  658. userModel.updateOne(
  659. { _id: session.userId },
  660. {
  661. $set: {
  662. preferences: {
  663. nightmode: preferences.nightmode,
  664. autoSkipDisliked: preferences.autoSkipDisliked
  665. }
  666. }
  667. },
  668. { runValidators: true },
  669. next
  670. );
  671. }
  672. ],
  673. async err => {
  674. if (err) {
  675. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  676. this.log(
  677. "ERROR",
  678. "UPDATE_USER_PREFERENCES",
  679. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  680. preferences
  681. )}". "${err}"`
  682. );
  683. return cb({ status: "failure", message: err });
  684. }
  685. CacheModule.runJob("PUB", {
  686. channel: "user.updatePreferences",
  687. value: {
  688. preferences,
  689. userId: session.userId
  690. }
  691. });
  692. this.log(
  693. "SUCCESS",
  694. "UPDATE_USER_PREFERENCES",
  695. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  696. );
  697. return cb({
  698. status: "success",
  699. message: "Preferences successfully updated"
  700. });
  701. }
  702. );
  703. }),
  704. /**
  705. * Retrieves a user's preferences
  706. *
  707. * @param {object} session - the session object automatically added by socket.io
  708. * @param {Function} cb - gets called with the result
  709. */
  710. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  711. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  712. async.waterfall(
  713. [
  714. next => {
  715. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  716. }
  717. ],
  718. async (err, { preferences }) => {
  719. if (err) {
  720. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  721. this.log(
  722. "ERROR",
  723. "GET_USER_PREFERENCES",
  724. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  725. );
  726. return cb({ status: "failure", message: err });
  727. }
  728. this.log(
  729. "SUCCESS",
  730. "GET_USER_PREFERENCES",
  731. `Successfully obtained preferences for user "${session.userId}".`
  732. );
  733. return cb({
  734. status: "success",
  735. message: "Preferences successfully retrieved",
  736. data: preferences
  737. });
  738. }
  739. );
  740. }),
  741. /**
  742. * Gets user object from username (only a few properties)
  743. *
  744. * @param {object} session - the session object automatically added by socket.io
  745. * @param {string} username - the username of the user we are trying to find
  746. * @param {Function} cb - gets called with the result
  747. */
  748. findByUsername: async function findByUsername(session, username, cb) {
  749. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  750. async.waterfall(
  751. [
  752. next => {
  753. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  754. },
  755. (account, next) => {
  756. if (!account) return next("User not found.");
  757. return next(null, account);
  758. }
  759. ],
  760. async (err, account) => {
  761. if (err && err !== true) {
  762. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  763. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  764. return cb({ status: "failure", message: err });
  765. }
  766. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  767. return cb({
  768. status: "success",
  769. data: {
  770. _id: account._id,
  771. name: account.name,
  772. username: account.username,
  773. location: account.location,
  774. bio: account.bio,
  775. role: account.role,
  776. avatar: account.avatar,
  777. createdAt: account.createdAt
  778. }
  779. });
  780. }
  781. );
  782. },
  783. /**
  784. * Gets a username from an userId
  785. *
  786. * @param {object} session - the session object automatically added by socket.io
  787. * @param {string} userId - the userId of the person we are trying to get the username from
  788. * @param {Function} cb - gets called with the result
  789. */
  790. async getUsernameFromId(session, userId, cb) {
  791. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  792. userModel
  793. .findById(userId)
  794. .then(user => {
  795. if (user) {
  796. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  797. return cb({
  798. status: "success",
  799. data: user.username
  800. });
  801. }
  802. this.log(
  803. "ERROR",
  804. "GET_USERNAME_FROM_ID",
  805. `Getting the username from userId "${userId}" failed. User not found.`
  806. );
  807. return cb({
  808. status: "failure",
  809. message: "Couldn't find the user."
  810. });
  811. })
  812. .catch(async err => {
  813. if (err && err !== true) {
  814. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  815. this.log(
  816. "ERROR",
  817. "GET_USERNAME_FROM_ID",
  818. `Getting the username from userId "${userId}" failed. "${err}"`
  819. );
  820. cb({ status: "failure", message: err });
  821. }
  822. });
  823. },
  824. /**
  825. * Gets a user from a userId
  826. *
  827. * @param {object} session - the session object automatically added by socket.io
  828. * @param {string} userId - the userId of the person we are trying to get the username from
  829. * @param {Function} cb - gets called with the result
  830. */
  831. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  832. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  833. userModel
  834. .findById(userId)
  835. .then(user => {
  836. if (user) {
  837. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  838. return cb({
  839. status: "success",
  840. data: {
  841. _id: user._id,
  842. username: user.username,
  843. role: user.role,
  844. liked: user.liked,
  845. disliked: user.disliked,
  846. songsRequested: user.statistics.songsRequested,
  847. email: {
  848. address: user.email.address,
  849. verified: user.email.verified
  850. },
  851. hasPassword: !!user.services.password,
  852. services: { github: user.services.github }
  853. }
  854. });
  855. }
  856. this.log(
  857. "ERROR",
  858. "GET_USER_FROM_ID",
  859. `Getting the user from userId "${userId}" failed. User not found.`
  860. );
  861. return cb({
  862. status: "failure",
  863. message: "Couldn't find the user."
  864. });
  865. })
  866. .catch(async err => {
  867. if (err && err !== true) {
  868. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  869. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  870. cb({ status: "failure", message: err });
  871. }
  872. });
  873. }),
  874. // TODO Fix security issues
  875. /**
  876. * Gets user info from session
  877. *
  878. * @param {object} session - the session object automatically added by socket.io
  879. * @param {Function} cb - gets called with the result
  880. */
  881. async findBySession(session, cb) {
  882. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  883. async.waterfall(
  884. [
  885. next => {
  886. CacheModule.runJob(
  887. "HGET",
  888. {
  889. table: "sessions",
  890. key: session.sessionId
  891. },
  892. this
  893. )
  894. .then(session => {
  895. next(null, session);
  896. })
  897. .catch(next);
  898. },
  899. (session, next) => {
  900. if (!session) return next("Session not found.");
  901. return next(null, session);
  902. },
  903. (session, next) => {
  904. userModel.findOne({ _id: session.userId }, next);
  905. },
  906. (user, next) => {
  907. if (!user) return next("User not found.");
  908. return next(null, user);
  909. }
  910. ],
  911. async (err, user) => {
  912. if (err && err !== true) {
  913. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  914. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  915. return cb({ status: "failure", message: err });
  916. }
  917. const data = {
  918. email: {
  919. address: user.email.address
  920. },
  921. avatar: user.avatar,
  922. username: user.username,
  923. name: user.name,
  924. location: user.location,
  925. bio: user.bio
  926. };
  927. if (user.services.password && user.services.password.password) data.password = true;
  928. if (user.services.github && user.services.github.id) data.github = true;
  929. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  930. return cb({
  931. status: "success",
  932. data
  933. });
  934. }
  935. );
  936. },
  937. /**
  938. * Updates a user's username
  939. *
  940. * @param {object} session - the session object automatically added by socket.io
  941. * @param {string} updatingUserId - the updating user's id
  942. * @param {string} newUsername - the new username
  943. * @param {Function} cb - gets called with the result
  944. */
  945. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  946. const userModel = await DBModule.runJob(
  947. "GET_MODEL",
  948. {
  949. modelName: "user"
  950. },
  951. this
  952. );
  953. async.waterfall(
  954. [
  955. next => {
  956. if (updatingUserId === session.userId) return next(null, true);
  957. return userModel.findOne({ _id: session.userId }, next);
  958. },
  959. (user, next) => {
  960. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  961. return userModel.findOne({ _id: updatingUserId }, next);
  962. },
  963. (user, next) => {
  964. if (!user) return next("User not found.");
  965. if (user.username === newUsername)
  966. return next("New username can't be the same as the old username.");
  967. return next(null);
  968. },
  969. next => {
  970. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  971. },
  972. (user, next) => {
  973. if (!user) return next();
  974. if (user._id === updatingUserId) return next();
  975. return next("That username is already in use.");
  976. },
  977. next => {
  978. userModel.updateOne(
  979. { _id: updatingUserId },
  980. { $set: { username: newUsername } },
  981. { runValidators: true },
  982. next
  983. );
  984. }
  985. ],
  986. async err => {
  987. if (err && err !== true) {
  988. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  989. this.log(
  990. "ERROR",
  991. "UPDATE_USERNAME",
  992. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  993. );
  994. return cb({ status: "failure", message: err });
  995. }
  996. CacheModule.runJob("PUB", {
  997. channel: "user.updateUsername",
  998. value: {
  999. username: newUsername,
  1000. _id: updatingUserId
  1001. }
  1002. });
  1003. this.log(
  1004. "SUCCESS",
  1005. "UPDATE_USERNAME",
  1006. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1007. );
  1008. return cb({
  1009. status: "success",
  1010. message: "Username updated successfully"
  1011. });
  1012. }
  1013. );
  1014. }),
  1015. /**
  1016. * Updates a user's email
  1017. *
  1018. * @param {object} session - the session object automatically added by socket.io
  1019. * @param {string} updatingUserId - the updating user's id
  1020. * @param {string} newEmail - the new email
  1021. * @param {Function} cb - gets called with the result
  1022. */
  1023. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1024. newEmail = newEmail.toLowerCase();
  1025. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1026. const userModel = await DBModule.runJob(
  1027. "GET_MODEL",
  1028. {
  1029. modelName: "user"
  1030. },
  1031. this
  1032. );
  1033. const verifyEmailSchema = await MailModule.runJob(
  1034. "GET_SCHEMA",
  1035. {
  1036. schemaName: "verifyEmail"
  1037. },
  1038. this
  1039. );
  1040. async.waterfall(
  1041. [
  1042. next => {
  1043. if (updatingUserId === session.userId) return next(null, true);
  1044. return userModel.findOne({ _id: session.userId }, next);
  1045. },
  1046. (user, next) => {
  1047. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1048. return userModel.findOne({ _id: updatingUserId }, next);
  1049. },
  1050. (user, next) => {
  1051. if (!user) return next("User not found.");
  1052. if (user.email.address === newEmail)
  1053. return next("New email can't be the same as your the old email.");
  1054. return next();
  1055. },
  1056. next => {
  1057. userModel.findOne({ "email.address": newEmail }, next);
  1058. },
  1059. (user, next) => {
  1060. if (!user) return next();
  1061. if (user._id === updatingUserId) return next();
  1062. return next("That email is already in use.");
  1063. },
  1064. // regenerate the url for gravatar avatar
  1065. next => {
  1066. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1067. next(null, url);
  1068. });
  1069. },
  1070. (newAvatarUrl, next) => {
  1071. userModel.updateOne(
  1072. { _id: updatingUserId },
  1073. {
  1074. $set: {
  1075. "avatar.url": newAvatarUrl,
  1076. "email.address": newEmail,
  1077. "email.verified": false,
  1078. "email.verificationToken": verificationToken
  1079. }
  1080. },
  1081. { runValidators: true },
  1082. next
  1083. );
  1084. },
  1085. (res, next) => {
  1086. userModel.findOne({ _id: updatingUserId }, next);
  1087. },
  1088. (user, next) => {
  1089. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1090. next(err);
  1091. });
  1092. }
  1093. ],
  1094. async err => {
  1095. if (err && err !== true) {
  1096. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1097. this.log(
  1098. "ERROR",
  1099. "UPDATE_EMAIL",
  1100. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1101. );
  1102. return cb({ status: "failure", message: err });
  1103. }
  1104. this.log(
  1105. "SUCCESS",
  1106. "UPDATE_EMAIL",
  1107. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1108. );
  1109. return cb({
  1110. status: "success",
  1111. message: "Email updated successfully."
  1112. });
  1113. }
  1114. );
  1115. }),
  1116. /**
  1117. * Updates a user's name
  1118. *
  1119. * @param {object} session - the session object automatically added by socket.io
  1120. * @param {string} updatingUserId - the updating user's id
  1121. * @param {string} newBio - the new name
  1122. * @param {Function} cb - gets called with the result
  1123. */
  1124. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1125. const userModel = await DBModule.runJob(
  1126. "GET_MODEL",
  1127. {
  1128. modelName: "user"
  1129. },
  1130. this
  1131. );
  1132. async.waterfall(
  1133. [
  1134. next => {
  1135. if (updatingUserId === session.userId) return next(null, true);
  1136. return userModel.findOne({ _id: session.userId }, next);
  1137. },
  1138. (user, next) => {
  1139. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1140. return userModel.findOne({ _id: updatingUserId }, next);
  1141. },
  1142. (user, next) => {
  1143. if (!user) return next("User not found.");
  1144. return userModel.updateOne(
  1145. { _id: updatingUserId },
  1146. { $set: { name: newName } },
  1147. { runValidators: true },
  1148. next
  1149. );
  1150. }
  1151. ],
  1152. async err => {
  1153. if (err && err !== true) {
  1154. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1155. this.log(
  1156. "ERROR",
  1157. "UPDATE_NAME",
  1158. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1159. );
  1160. cb({ status: "failure", message: err });
  1161. } else {
  1162. this.log(
  1163. "SUCCESS",
  1164. "UPDATE_NAME",
  1165. `Updated name for user "${updatingUserId}" to name "${newName}".`
  1166. );
  1167. cb({
  1168. status: "success",
  1169. message: "Name updated successfully"
  1170. });
  1171. }
  1172. }
  1173. );
  1174. }),
  1175. /**
  1176. * Updates a user's location
  1177. *
  1178. * @param {object} session - the session object automatically added by socket.io
  1179. * @param {string} updatingUserId - the updating user's id
  1180. * @param {string} newLocation - the new location
  1181. * @param {Function} cb - gets called with the result
  1182. */
  1183. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1184. const userModel = await DBModule.runJob(
  1185. "GET_MODEL",
  1186. {
  1187. modelName: "user"
  1188. },
  1189. this
  1190. );
  1191. async.waterfall(
  1192. [
  1193. next => {
  1194. if (updatingUserId === session.userId) return next(null, true);
  1195. return userModel.findOne({ _id: session.userId }, next);
  1196. },
  1197. (user, next) => {
  1198. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1199. return userModel.findOne({ _id: updatingUserId }, next);
  1200. },
  1201. (user, next) => {
  1202. if (!user) return next("User not found.");
  1203. return userModel.updateOne(
  1204. { _id: updatingUserId },
  1205. { $set: { location: newLocation } },
  1206. { runValidators: true },
  1207. next
  1208. );
  1209. }
  1210. ],
  1211. async err => {
  1212. if (err && err !== true) {
  1213. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1214. this.log(
  1215. "ERROR",
  1216. "UPDATE_LOCATION",
  1217. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1218. );
  1219. return cb({ status: "failure", message: err });
  1220. }
  1221. this.log(
  1222. "SUCCESS",
  1223. "UPDATE_LOCATION",
  1224. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1225. );
  1226. return cb({
  1227. status: "success",
  1228. message: "Location updated successfully"
  1229. });
  1230. }
  1231. );
  1232. }),
  1233. /**
  1234. * Updates a user's bio
  1235. *
  1236. * @param {object} session - the session object automatically added by socket.io
  1237. * @param {string} updatingUserId - the updating user's id
  1238. * @param {string} newBio - the new bio
  1239. * @param {Function} cb - gets called with the result
  1240. */
  1241. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1242. const userModel = await DBModule.runJob(
  1243. "GET_MODEL",
  1244. {
  1245. modelName: "user"
  1246. },
  1247. this
  1248. );
  1249. async.waterfall(
  1250. [
  1251. next => {
  1252. if (updatingUserId === session.userId) return next(null, true);
  1253. return userModel.findOne({ _id: session.userId }, next);
  1254. },
  1255. (user, next) => {
  1256. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1257. return userModel.findOne({ _id: updatingUserId }, next);
  1258. },
  1259. (user, next) => {
  1260. if (!user) return next("User not found.");
  1261. return userModel.updateOne(
  1262. { _id: updatingUserId },
  1263. { $set: { bio: newBio } },
  1264. { runValidators: true },
  1265. next
  1266. );
  1267. }
  1268. ],
  1269. async err => {
  1270. if (err && err !== true) {
  1271. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1272. this.log(
  1273. "ERROR",
  1274. "UPDATE_BIO",
  1275. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1276. );
  1277. cb({ status: "failure", message: err });
  1278. } else {
  1279. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1280. cb({
  1281. status: "success",
  1282. message: "Bio updated successfully"
  1283. });
  1284. }
  1285. }
  1286. );
  1287. }),
  1288. /**
  1289. * Updates the type of a user's avatar
  1290. *
  1291. * @param {object} session - the session object automatically added by socket.io
  1292. * @param {string} updatingUserId - the updating user's id
  1293. * @param {string} newType - the new type
  1294. * @param {Function} cb - gets called with the result
  1295. */
  1296. updateAvatarType: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1297. const userModel = await DBModule.runJob(
  1298. "GET_MODEL",
  1299. {
  1300. modelName: "user"
  1301. },
  1302. this
  1303. );
  1304. async.waterfall(
  1305. [
  1306. next => {
  1307. if (updatingUserId === session.userId) return next(null, true);
  1308. return userModel.findOne({ _id: session.userId }, next);
  1309. },
  1310. (user, next) => {
  1311. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1312. return userModel.findOne({ _id: updatingUserId }, next);
  1313. },
  1314. (user, next) => {
  1315. if (!user) return next("User not found.");
  1316. return userModel.findOneAndUpdate(
  1317. { _id: updatingUserId },
  1318. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1319. { new: true, runValidators: true },
  1320. next
  1321. );
  1322. }
  1323. ],
  1324. async err => {
  1325. if (err && err !== true) {
  1326. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1327. this.log(
  1328. "ERROR",
  1329. "UPDATE_AVATAR_TYPE",
  1330. `Couldn't update avatar type for user "${updatingUserId}" to type "${newAvatar.type}". "${err}"`
  1331. );
  1332. return cb({ status: "failure", message: err });
  1333. }
  1334. this.log(
  1335. "SUCCESS",
  1336. "UPDATE_AVATAR_TYPE",
  1337. `Updated avatar type for user "${updatingUserId}" to type "${newAvatar.type}".`
  1338. );
  1339. return cb({
  1340. status: "success",
  1341. message: "Avatar type updated successfully"
  1342. });
  1343. }
  1344. );
  1345. }),
  1346. /**
  1347. * Updates a user's role
  1348. *
  1349. * @param {object} session - the session object automatically added by socket.io
  1350. * @param {string} updatingUserId - the updating user's id
  1351. * @param {string} newRole - the new role
  1352. * @param {Function} cb - gets called with the result
  1353. */
  1354. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1355. newRole = newRole.toLowerCase();
  1356. const userModel = await DBModule.runJob(
  1357. "GET_MODEL",
  1358. {
  1359. modelName: "user"
  1360. },
  1361. this
  1362. );
  1363. async.waterfall(
  1364. [
  1365. next => {
  1366. userModel.findOne({ _id: updatingUserId }, next);
  1367. },
  1368. (user, next) => {
  1369. if (!user) return next("User not found.");
  1370. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1371. return next();
  1372. },
  1373. next => {
  1374. userModel.updateOne(
  1375. { _id: updatingUserId },
  1376. { $set: { role: newRole } },
  1377. { runValidators: true },
  1378. next
  1379. );
  1380. }
  1381. ],
  1382. async err => {
  1383. if (err && err !== true) {
  1384. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1385. this.log(
  1386. "ERROR",
  1387. "UPDATE_ROLE",
  1388. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1389. );
  1390. return cb({ status: "failure", message: err });
  1391. }
  1392. this.log(
  1393. "SUCCESS",
  1394. "UPDATE_ROLE",
  1395. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1396. );
  1397. return cb({
  1398. status: "success",
  1399. message: "Role successfully updated."
  1400. });
  1401. }
  1402. );
  1403. }),
  1404. /**
  1405. * Updates a user's password
  1406. *
  1407. * @param {object} session - the session object automatically added by socket.io
  1408. * @param {string} previousPassword - the previous password
  1409. * @param {string} newPassword - the new password
  1410. * @param {Function} cb - gets called with the result
  1411. */
  1412. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1413. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1414. async.waterfall(
  1415. [
  1416. next => {
  1417. userModel.findOne({ _id: session.userId }, next);
  1418. },
  1419. (user, next) => {
  1420. if (!user.services.password) return next("This account does not have a password set.");
  1421. return next(null, user.services.password.password);
  1422. },
  1423. (storedPassword, next) => {
  1424. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1425. if (res) return next();
  1426. return next("Please enter the correct previous password.");
  1427. });
  1428. },
  1429. next => {
  1430. if (!DBModule.passwordValid(newPassword))
  1431. return next("Invalid new password. Check if it meets all the requirements.");
  1432. return next();
  1433. },
  1434. next => {
  1435. bcrypt.genSalt(10, next);
  1436. },
  1437. // hash the password
  1438. (salt, next) => {
  1439. bcrypt.hash(sha256(newPassword), salt, next);
  1440. },
  1441. (hashedPassword, next) => {
  1442. userModel.updateOne(
  1443. { _id: session.userId },
  1444. {
  1445. $set: {
  1446. "services.password.password": hashedPassword
  1447. }
  1448. },
  1449. next
  1450. );
  1451. }
  1452. ],
  1453. async err => {
  1454. if (err) {
  1455. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1456. this.log(
  1457. "ERROR",
  1458. "UPDATE_PASSWORD",
  1459. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1460. );
  1461. return cb({ status: "failure", message: err });
  1462. }
  1463. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1464. return cb({
  1465. status: "success",
  1466. message: "Password successfully updated."
  1467. });
  1468. }
  1469. );
  1470. }),
  1471. /**
  1472. * Requests a password for a session
  1473. *
  1474. * @param {object} session - the session object automatically added by socket.io
  1475. * @param {string} email - the email of the user that requests a password reset
  1476. * @param {Function} cb - gets called with the result
  1477. */
  1478. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1479. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1480. const passwordRequestSchema = await MailModule.runJob(
  1481. "GET_SCHEMA",
  1482. {
  1483. schemaName: "passwordRequest"
  1484. },
  1485. this
  1486. );
  1487. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1488. async.waterfall(
  1489. [
  1490. next => {
  1491. userModel.findOne({ _id: session.userId }, next);
  1492. },
  1493. (user, next) => {
  1494. if (!user) return next("User not found.");
  1495. if (user.services.password && user.services.password.password)
  1496. return next("You already have a password set.");
  1497. return next(null, user);
  1498. },
  1499. (user, next) => {
  1500. const expires = new Date();
  1501. expires.setDate(expires.getDate() + 1);
  1502. userModel.findOneAndUpdate(
  1503. { "email.address": user.email.address },
  1504. {
  1505. $set: {
  1506. "services.password": {
  1507. set: { code, expires }
  1508. }
  1509. }
  1510. },
  1511. { runValidators: true },
  1512. next
  1513. );
  1514. },
  1515. (user, next) => {
  1516. passwordRequestSchema(user.email.address, user.username, code, next);
  1517. }
  1518. ],
  1519. async err => {
  1520. if (err && err !== true) {
  1521. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1522. this.log(
  1523. "ERROR",
  1524. "REQUEST_PASSWORD",
  1525. `UserId '${session.userId}' failed to request password. '${err}'`
  1526. );
  1527. return cb({ status: "failure", message: err });
  1528. }
  1529. this.log(
  1530. "SUCCESS",
  1531. "REQUEST_PASSWORD",
  1532. `UserId '${session.userId}' successfully requested a password.`
  1533. );
  1534. return cb({
  1535. status: "success",
  1536. message: "Successfully requested password."
  1537. });
  1538. }
  1539. );
  1540. }),
  1541. /**
  1542. * Verifies a password code
  1543. *
  1544. * @param {object} session - the session object automatically added by socket.io
  1545. * @param {string} code - the password code
  1546. * @param {Function} cb - gets called with the result
  1547. */
  1548. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1549. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1550. async.waterfall(
  1551. [
  1552. next => {
  1553. if (!code || typeof code !== "string") return next("Invalid code.");
  1554. return userModel.findOne(
  1555. {
  1556. "services.password.set.code": code,
  1557. _id: session.userId
  1558. },
  1559. next
  1560. );
  1561. },
  1562. (user, next) => {
  1563. if (!user) return next("Invalid code.");
  1564. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1565. return next(null);
  1566. }
  1567. ],
  1568. async err => {
  1569. if (err && err !== true) {
  1570. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1571. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1572. cb({ status: "failure", message: err });
  1573. } else {
  1574. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1575. cb({
  1576. status: "success",
  1577. message: "Successfully verified password code."
  1578. });
  1579. }
  1580. }
  1581. );
  1582. }),
  1583. /**
  1584. * Adds a password to a user with a code
  1585. *
  1586. * @param {object} session - the session object automatically added by socket.io
  1587. * @param {string} code - the password code
  1588. * @param {string} newPassword - the new password code
  1589. * @param {Function} cb - gets called with the result
  1590. */
  1591. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1592. const userModel = await DBModule.runJob(
  1593. "GET_MODEL",
  1594. {
  1595. modelName: "user"
  1596. },
  1597. this
  1598. );
  1599. async.waterfall(
  1600. [
  1601. next => {
  1602. if (!code || typeof code !== "string") return next("Invalid code.");
  1603. return userModel.findOne({ "services.password.set.code": code }, next);
  1604. },
  1605. (user, next) => {
  1606. if (!user) return next("Invalid code.");
  1607. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1608. return next();
  1609. },
  1610. next => {
  1611. if (!DBModule.passwordValid(newPassword))
  1612. return next("Invalid password. Check if it meets all the requirements.");
  1613. return next();
  1614. },
  1615. next => {
  1616. bcrypt.genSalt(10, next);
  1617. },
  1618. // hash the password
  1619. (salt, next) => {
  1620. bcrypt.hash(sha256(newPassword), salt, next);
  1621. },
  1622. (hashedPassword, next) => {
  1623. userModel.updateOne(
  1624. { "services.password.set.code": code },
  1625. {
  1626. $set: {
  1627. "services.password.password": hashedPassword
  1628. },
  1629. $unset: { "services.password.set": "" }
  1630. },
  1631. { runValidators: true },
  1632. next
  1633. );
  1634. }
  1635. ],
  1636. async err => {
  1637. if (err && err !== true) {
  1638. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1639. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1640. cb({ status: "failure", message: err });
  1641. } else {
  1642. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1643. CacheModule.runJob("PUB", {
  1644. channel: "user.linkPassword",
  1645. value: session.userId
  1646. });
  1647. cb({
  1648. status: "success",
  1649. message: "Successfully added password."
  1650. });
  1651. }
  1652. }
  1653. );
  1654. }),
  1655. /**
  1656. * Unlinks password from user
  1657. *
  1658. * @param {object} session - the session object automatically added by socket.io
  1659. * @param {Function} cb - gets called with the result
  1660. */
  1661. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1662. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1663. async.waterfall(
  1664. [
  1665. next => {
  1666. userModel.findOne({ _id: session.userId }, next);
  1667. },
  1668. (user, next) => {
  1669. if (!user) return next("Not logged in.");
  1670. if (!user.services.github || !user.services.github.id)
  1671. return next("You can't remove password login without having GitHub login.");
  1672. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1673. }
  1674. ],
  1675. async err => {
  1676. if (err && err !== true) {
  1677. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1678. this.log(
  1679. "ERROR",
  1680. "UNLINK_PASSWORD",
  1681. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1682. );
  1683. cb({ status: "failure", message: err });
  1684. } else {
  1685. this.log(
  1686. "SUCCESS",
  1687. "UNLINK_PASSWORD",
  1688. `Unlinking password successful for userId '${session.userId}'.`
  1689. );
  1690. CacheModule.runJob("PUB", {
  1691. channel: "user.unlinkPassword",
  1692. value: session.userId
  1693. });
  1694. cb({
  1695. status: "success",
  1696. message: "Successfully unlinked password."
  1697. });
  1698. }
  1699. }
  1700. );
  1701. }),
  1702. /**
  1703. * Unlinks GitHub from user
  1704. *
  1705. * @param {object} session - the session object automatically added by socket.io
  1706. * @param {Function} cb - gets called with the result
  1707. */
  1708. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1709. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1710. async.waterfall(
  1711. [
  1712. next => {
  1713. userModel.findOne({ _id: session.userId }, next);
  1714. },
  1715. (user, next) => {
  1716. if (!user) return next("Not logged in.");
  1717. if (!user.services.password || !user.services.password.password)
  1718. return next("You can't remove GitHub login without having password login.");
  1719. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1720. }
  1721. ],
  1722. async err => {
  1723. if (err && err !== true) {
  1724. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1725. this.log(
  1726. "ERROR",
  1727. "UNLINK_GITHUB",
  1728. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  1729. );
  1730. cb({ status: "failure", message: err });
  1731. } else {
  1732. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  1733. CacheModule.runJob("PUB", {
  1734. channel: "user.unlinkGithub",
  1735. value: session.userId
  1736. });
  1737. cb({
  1738. status: "success",
  1739. message: "Successfully unlinked GitHub."
  1740. });
  1741. }
  1742. }
  1743. );
  1744. }),
  1745. /**
  1746. * Requests a password reset for an email
  1747. *
  1748. * @param {object} session - the session object automatically added by socket.io
  1749. * @param {string} email - the email of the user that requests a password reset
  1750. * @param {Function} cb - gets called with the result
  1751. */
  1752. async requestPasswordReset(session, email, cb) {
  1753. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1754. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1755. const resetPasswordRequestSchema = await MailModule.runJob(
  1756. "GET_SCHEMA",
  1757. {
  1758. schemaName: "resetPasswordRequest"
  1759. },
  1760. this
  1761. );
  1762. async.waterfall(
  1763. [
  1764. next => {
  1765. if (!email || typeof email !== "string") return next("Invalid email.");
  1766. email = email.toLowerCase();
  1767. return userModel.findOne({ "email.address": email }, next);
  1768. },
  1769. (user, next) => {
  1770. if (!user) return next("User not found.");
  1771. if (!user.services.password || !user.services.password.password)
  1772. return next("User does not have a password set, and probably uses GitHub to log in.");
  1773. return next(null, user);
  1774. },
  1775. (user, next) => {
  1776. const expires = new Date();
  1777. expires.setDate(expires.getDate() + 1);
  1778. userModel.findOneAndUpdate(
  1779. { "email.address": email },
  1780. {
  1781. $set: {
  1782. "services.password.reset": {
  1783. code,
  1784. expires
  1785. }
  1786. }
  1787. },
  1788. { runValidators: true },
  1789. next
  1790. );
  1791. },
  1792. (user, next) => {
  1793. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  1794. }
  1795. ],
  1796. async err => {
  1797. if (err && err !== true) {
  1798. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1799. this.log(
  1800. "ERROR",
  1801. "REQUEST_PASSWORD_RESET",
  1802. `Email '${email}' failed to request password reset. '${err}'`
  1803. );
  1804. cb({ status: "failure", message: err });
  1805. } else {
  1806. this.log(
  1807. "SUCCESS",
  1808. "REQUEST_PASSWORD_RESET",
  1809. `Email '${email}' successfully requested a password reset.`
  1810. );
  1811. cb({
  1812. status: "success",
  1813. message: "Successfully requested password reset."
  1814. });
  1815. }
  1816. }
  1817. );
  1818. },
  1819. /**
  1820. * Verifies a reset code
  1821. *
  1822. * @param {object} session - the session object automatically added by socket.io
  1823. * @param {string} code - the password reset code
  1824. * @param {Function} cb - gets called with the result
  1825. */
  1826. async verifyPasswordResetCode(session, code, cb) {
  1827. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1828. async.waterfall(
  1829. [
  1830. next => {
  1831. if (!code || typeof code !== "string") return next("Invalid code.");
  1832. return userModel.findOne({ "services.password.reset.code": code }, next);
  1833. },
  1834. (user, next) => {
  1835. if (!user) return next("Invalid code.");
  1836. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1837. return next(null);
  1838. }
  1839. ],
  1840. async err => {
  1841. if (err && err !== true) {
  1842. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1843. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  1844. cb({ status: "failure", message: err });
  1845. } else {
  1846. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  1847. cb({
  1848. status: "success",
  1849. message: "Successfully verified password reset code."
  1850. });
  1851. }
  1852. }
  1853. );
  1854. },
  1855. /**
  1856. * Changes a user's password with a reset code
  1857. *
  1858. * @param {object} session - the session object automatically added by socket.io
  1859. * @param {string} code - the password reset code
  1860. * @param {string} newPassword - the new password reset code
  1861. * @param {Function} cb - gets called with the result
  1862. */
  1863. async changePasswordWithResetCode(session, code, newPassword, cb) {
  1864. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1865. async.waterfall(
  1866. [
  1867. next => {
  1868. if (!code || typeof code !== "string") return next("Invalid code.");
  1869. return userModel.findOne({ "services.password.reset.code": code }, next);
  1870. },
  1871. (user, next) => {
  1872. if (!user) return next("Invalid code.");
  1873. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1874. return next();
  1875. },
  1876. next => {
  1877. if (!DBModule.passwordValid(newPassword))
  1878. return next("Invalid password. Check if it meets all the requirements.");
  1879. return next();
  1880. },
  1881. next => {
  1882. bcrypt.genSalt(10, next);
  1883. },
  1884. // hash the password
  1885. (salt, next) => {
  1886. bcrypt.hash(sha256(newPassword), salt, next);
  1887. },
  1888. (hashedPassword, next) => {
  1889. userModel.updateOne(
  1890. { "services.password.reset.code": code },
  1891. {
  1892. $set: {
  1893. "services.password.password": hashedPassword
  1894. },
  1895. $unset: { "services.password.reset": "" }
  1896. },
  1897. { runValidators: true },
  1898. next
  1899. );
  1900. }
  1901. ],
  1902. async err => {
  1903. if (err && err !== true) {
  1904. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1905. this.log(
  1906. "ERROR",
  1907. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1908. `Code '${code}' failed to change password. '${err}'`
  1909. );
  1910. cb({ status: "failure", message: err });
  1911. } else {
  1912. this.log(
  1913. "SUCCESS",
  1914. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1915. `Code '${code}' successfully changed password.`
  1916. );
  1917. cb({
  1918. status: "success",
  1919. message: "Successfully changed password."
  1920. });
  1921. }
  1922. }
  1923. );
  1924. },
  1925. /**
  1926. * Bans a user by userId
  1927. *
  1928. * @param {object} session - the session object automatically added by socket.io
  1929. * @param {string} value - the user id that is going to be banned
  1930. * @param {string} reason - the reason for the ban
  1931. * @param {string} expiresAt - the time the ban expires
  1932. * @param {Function} cb - gets called with the result
  1933. */
  1934. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  1935. async.waterfall(
  1936. [
  1937. next => {
  1938. if (!userId) return next("You must provide a userId to ban.");
  1939. if (!reason) return next("You must provide a reason for the ban.");
  1940. return next();
  1941. },
  1942. next => {
  1943. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  1944. const date = new Date();
  1945. switch (expiresAt) {
  1946. case "1h":
  1947. expiresAt = date.setHours(date.getHours() + 1);
  1948. break;
  1949. case "12h":
  1950. expiresAt = date.setHours(date.getHours() + 12);
  1951. break;
  1952. case "1d":
  1953. expiresAt = date.setDate(date.getDate() + 1);
  1954. break;
  1955. case "1w":
  1956. expiresAt = date.setDate(date.getDate() + 7);
  1957. break;
  1958. case "1m":
  1959. expiresAt = date.setMonth(date.getMonth() + 1);
  1960. break;
  1961. case "3m":
  1962. expiresAt = date.setMonth(date.getMonth() + 3);
  1963. break;
  1964. case "6m":
  1965. expiresAt = date.setMonth(date.getMonth() + 6);
  1966. break;
  1967. case "1y":
  1968. expiresAt = date.setFullYear(date.getFullYear() + 1);
  1969. break;
  1970. case "never":
  1971. expiresAt = new Date(3093527980800000);
  1972. break;
  1973. default:
  1974. return next("Invalid expire date.");
  1975. }
  1976. return next();
  1977. },
  1978. next => {
  1979. PunishmentsModule.runJob(
  1980. "ADD_PUNISHMENT",
  1981. {
  1982. type: "banUserId",
  1983. value: userId,
  1984. reason,
  1985. expiresAt,
  1986. punishedBy: "" // needs changed
  1987. },
  1988. this
  1989. )
  1990. .then(punishment => next(null, punishment))
  1991. .catch(next);
  1992. },
  1993. (punishment, next) => {
  1994. CacheModule.runJob("PUB", {
  1995. channel: "user.ban",
  1996. value: { userId, punishment }
  1997. });
  1998. next();
  1999. }
  2000. ],
  2001. async err => {
  2002. if (err && err !== true) {
  2003. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2004. this.log(
  2005. "ERROR",
  2006. "BAN_USER_BY_ID",
  2007. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2008. );
  2009. cb({ status: "failure", message: err });
  2010. } else {
  2011. this.log(
  2012. "SUCCESS",
  2013. "BAN_USER_BY_ID",
  2014. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2015. );
  2016. cb({
  2017. status: "success",
  2018. message: "Successfully banned user."
  2019. });
  2020. }
  2021. }
  2022. );
  2023. })
  2024. };