users.js 50 KB

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