users.js 61 KB

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