users.js 77 KB

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