users.js 57 KB

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