users.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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 = {
  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 module.exports.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. (avatar, next) => {
  771. userModel.updateOne(
  772. { _id: updatingUserId },
  773. {
  774. $set: {
  775. avatar,
  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. };