users.js 78 KB

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