users.js 51 KB

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