users.js 77 KB

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