users.js 49 KB

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