users.js 59 KB

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