users.js 58 KB

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