users.js 51 KB

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