users.js 49 KB

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