users.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  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. /**
  651. * Gets a user from a userId
  652. *
  653. * @param {object} session - the session object automatically added by socket.io
  654. * @param {string} userId - the userId of the person we are trying to get the username from
  655. * @param {Function} cb - gets called with the result
  656. */
  657. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  658. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  659. userModel
  660. .findById(userId)
  661. .then(user => {
  662. if (user) {
  663. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  664. return cb({
  665. status: "success",
  666. data: {
  667. _id: user._id,
  668. username: user.username,
  669. role: user.role,
  670. liked: user.liked,
  671. disliked: user.disliked,
  672. songsRequested: user.statistics.songsRequested,
  673. email: {
  674. address: user.email.address,
  675. verified: user.email.verified
  676. },
  677. hasPassword: !!user.services.password,
  678. services: { github: user.services.github }
  679. }
  680. });
  681. }
  682. this.log(
  683. "ERROR",
  684. "GET_USER_FROM_ID",
  685. `Getting the user from userId "${userId}" failed. User not found.`
  686. );
  687. return cb({
  688. status: "failure",
  689. message: "Couldn't find the user."
  690. });
  691. })
  692. .catch(async err => {
  693. if (err && err !== true) {
  694. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  695. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  696. cb({ status: "failure", message: err });
  697. }
  698. });
  699. }),
  700. // TODO Fix security issues
  701. /**
  702. * Gets user info from session
  703. *
  704. * @param {object} session - the session object automatically added by socket.io
  705. * @param {Function} cb - gets called with the result
  706. */
  707. async findBySession(session, cb) {
  708. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  709. async.waterfall(
  710. [
  711. next => {
  712. CacheModule.runJob(
  713. "HGET",
  714. {
  715. table: "sessions",
  716. key: session.sessionId
  717. },
  718. this
  719. )
  720. .then(session => {
  721. next(null, session);
  722. })
  723. .catch(next);
  724. },
  725. (session, next) => {
  726. if (!session) return next("Session not found.");
  727. return next(null, session);
  728. },
  729. (session, next) => {
  730. userModel.findOne({ _id: session.userId }, next);
  731. },
  732. (user, next) => {
  733. if (!user) return next("User not found.");
  734. return next(null, user);
  735. }
  736. ],
  737. async (err, user) => {
  738. if (err && err !== true) {
  739. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  740. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  741. return cb({ status: "failure", message: err });
  742. }
  743. const data = {
  744. email: {
  745. address: user.email.address
  746. },
  747. avatar: user.avatar,
  748. username: user.username,
  749. name: user.name,
  750. location: user.location,
  751. bio: user.bio
  752. };
  753. if (user.services.password && user.services.password.password) data.password = true;
  754. if (user.services.github && user.services.github.id) data.github = true;
  755. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  756. return cb({
  757. status: "success",
  758. data
  759. });
  760. }
  761. );
  762. },
  763. /**
  764. * Updates a user's username
  765. *
  766. * @param {object} session - the session object automatically added by socket.io
  767. * @param {string} updatingUserId - the updating user's id
  768. * @param {string} newUsername - the new username
  769. * @param {Function} cb - gets called with the result
  770. */
  771. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  772. const userModel = await DBModule.runJob(
  773. "GET_MODEL",
  774. {
  775. modelName: "user"
  776. },
  777. this
  778. );
  779. async.waterfall(
  780. [
  781. next => {
  782. if (updatingUserId === session.userId) return next(null, true);
  783. return userModel.findOne({ _id: session.userId }, next);
  784. },
  785. (user, next) => {
  786. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  787. return userModel.findOne({ _id: updatingUserId }, next);
  788. },
  789. (user, next) => {
  790. if (!user) return next("User not found.");
  791. if (user.username === newUsername)
  792. return next("New username can't be the same as the old username.");
  793. return next(null);
  794. },
  795. next => {
  796. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  797. },
  798. (user, next) => {
  799. if (!user) return next();
  800. if (user._id === updatingUserId) return next();
  801. return next("That username is already in use.");
  802. },
  803. next => {
  804. userModel.updateOne(
  805. { _id: updatingUserId },
  806. { $set: { username: newUsername } },
  807. { runValidators: true },
  808. next
  809. );
  810. }
  811. ],
  812. async err => {
  813. if (err && err !== true) {
  814. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  815. this.log(
  816. "ERROR",
  817. "UPDATE_USERNAME",
  818. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  819. );
  820. return cb({ status: "failure", message: err });
  821. }
  822. CacheModule.runJob("PUB", {
  823. channel: "user.updateUsername",
  824. value: {
  825. username: newUsername,
  826. _id: updatingUserId
  827. }
  828. });
  829. this.log(
  830. "SUCCESS",
  831. "UPDATE_USERNAME",
  832. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  833. );
  834. return cb({
  835. status: "success",
  836. message: "Username updated successfully"
  837. });
  838. }
  839. );
  840. }),
  841. /**
  842. * Updates a user's email
  843. *
  844. * @param {object} session - the session object automatically added by socket.io
  845. * @param {string} updatingUserId - the updating user's id
  846. * @param {string} newEmail - the new email
  847. * @param {Function} cb - gets called with the result
  848. */
  849. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  850. newEmail = newEmail.toLowerCase();
  851. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  852. const userModel = await DBModule.runJob(
  853. "GET_MODEL",
  854. {
  855. modelName: "user"
  856. },
  857. this
  858. );
  859. const verifyEmailSchema = await MailModule.runJob(
  860. "GET_SCHEMA",
  861. {
  862. schemaName: "verifyEmail"
  863. },
  864. this
  865. );
  866. async.waterfall(
  867. [
  868. next => {
  869. if (updatingUserId === session.userId) return next(null, true);
  870. return userModel.findOne({ _id: session.userId }, next);
  871. },
  872. (user, next) => {
  873. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  874. return userModel.findOne({ _id: updatingUserId }, next);
  875. },
  876. (user, next) => {
  877. if (!user) return next("User not found.");
  878. if (user.email.address === newEmail)
  879. return next("New email can't be the same as your the old email.");
  880. return next();
  881. },
  882. next => {
  883. userModel.findOne({ "email.address": newEmail }, next);
  884. },
  885. (user, next) => {
  886. if (!user) return next();
  887. if (user._id === updatingUserId) return next();
  888. return next("That email is already in use.");
  889. },
  890. // regenerate the url for gravatar avatar
  891. next => {
  892. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  893. next(null, url);
  894. });
  895. },
  896. (newAvatarUrl, next) => {
  897. userModel.updateOne(
  898. { _id: updatingUserId },
  899. {
  900. $set: {
  901. "avatar.url": newAvatarUrl,
  902. "email.address": newEmail,
  903. "email.verified": false,
  904. "email.verificationToken": verificationToken
  905. }
  906. },
  907. { runValidators: true },
  908. next
  909. );
  910. },
  911. (res, next) => {
  912. userModel.findOne({ _id: updatingUserId }, next);
  913. },
  914. (user, next) => {
  915. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  916. next(err);
  917. });
  918. }
  919. ],
  920. async err => {
  921. if (err && err !== true) {
  922. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  923. this.log(
  924. "ERROR",
  925. "UPDATE_EMAIL",
  926. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  927. );
  928. return cb({ status: "failure", message: err });
  929. }
  930. this.log(
  931. "SUCCESS",
  932. "UPDATE_EMAIL",
  933. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  934. );
  935. return cb({
  936. status: "success",
  937. message: "Email updated successfully."
  938. });
  939. }
  940. );
  941. }),
  942. /**
  943. * Updates a user's name
  944. *
  945. * @param {object} session - the session object automatically added by socket.io
  946. * @param {string} updatingUserId - the updating user's id
  947. * @param {string} newBio - the new name
  948. * @param {Function} cb - gets called with the result
  949. */
  950. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  951. const userModel = await DBModule.runJob(
  952. "GET_MODEL",
  953. {
  954. modelName: "user"
  955. },
  956. this
  957. );
  958. async.waterfall(
  959. [
  960. next => {
  961. if (updatingUserId === session.userId) return next(null, true);
  962. return userModel.findOne({ _id: session.userId }, next);
  963. },
  964. (user, next) => {
  965. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  966. return userModel.findOne({ _id: updatingUserId }, next);
  967. },
  968. (user, next) => {
  969. if (!user) return next("User not found.");
  970. return userModel.updateOne(
  971. { _id: updatingUserId },
  972. { $set: { name: newName } },
  973. { runValidators: true },
  974. next
  975. );
  976. }
  977. ],
  978. async err => {
  979. if (err && err !== true) {
  980. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  981. this.log(
  982. "ERROR",
  983. "UPDATE_NAME",
  984. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  985. );
  986. cb({ status: "failure", message: err });
  987. } else {
  988. this.log(
  989. "SUCCESS",
  990. "UPDATE_NAME",
  991. `Updated name for user "${updatingUserId}" to name "${newName}".`
  992. );
  993. cb({
  994. status: "success",
  995. message: "Name updated successfully"
  996. });
  997. }
  998. }
  999. );
  1000. }),
  1001. /**
  1002. * Updates a user's location
  1003. *
  1004. * @param {object} session - the session object automatically added by socket.io
  1005. * @param {string} updatingUserId - the updating user's id
  1006. * @param {string} newLocation - the new location
  1007. * @param {Function} cb - gets called with the result
  1008. */
  1009. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1010. const userModel = await DBModule.runJob(
  1011. "GET_MODEL",
  1012. {
  1013. modelName: "user"
  1014. },
  1015. this
  1016. );
  1017. async.waterfall(
  1018. [
  1019. next => {
  1020. if (updatingUserId === session.userId) return next(null, true);
  1021. return userModel.findOne({ _id: session.userId }, next);
  1022. },
  1023. (user, next) => {
  1024. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1025. return userModel.findOne({ _id: updatingUserId }, next);
  1026. },
  1027. (user, next) => {
  1028. if (!user) return next("User not found.");
  1029. return userModel.updateOne(
  1030. { _id: updatingUserId },
  1031. { $set: { location: newLocation } },
  1032. { runValidators: true },
  1033. next
  1034. );
  1035. }
  1036. ],
  1037. async err => {
  1038. if (err && err !== true) {
  1039. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1040. this.log(
  1041. "ERROR",
  1042. "UPDATE_LOCATION",
  1043. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1044. );
  1045. return cb({ status: "failure", message: err });
  1046. }
  1047. this.log(
  1048. "SUCCESS",
  1049. "UPDATE_LOCATION",
  1050. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1051. );
  1052. return cb({
  1053. status: "success",
  1054. message: "Location updated successfully"
  1055. });
  1056. }
  1057. );
  1058. }),
  1059. /**
  1060. * Updates a user's bio
  1061. *
  1062. * @param {object} session - the session object automatically added by socket.io
  1063. * @param {string} updatingUserId - the updating user's id
  1064. * @param {string} newBio - the new bio
  1065. * @param {Function} cb - gets called with the result
  1066. */
  1067. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1068. const userModel = await DBModule.runJob(
  1069. "GET_MODEL",
  1070. {
  1071. modelName: "user"
  1072. },
  1073. this
  1074. );
  1075. async.waterfall(
  1076. [
  1077. next => {
  1078. if (updatingUserId === session.userId) return next(null, true);
  1079. return userModel.findOne({ _id: session.userId }, next);
  1080. },
  1081. (user, next) => {
  1082. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1083. return userModel.findOne({ _id: updatingUserId }, next);
  1084. },
  1085. (user, next) => {
  1086. if (!user) return next("User not found.");
  1087. return userModel.updateOne(
  1088. { _id: updatingUserId },
  1089. { $set: { bio: newBio } },
  1090. { runValidators: true },
  1091. next
  1092. );
  1093. }
  1094. ],
  1095. async err => {
  1096. if (err && err !== true) {
  1097. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1098. this.log(
  1099. "ERROR",
  1100. "UPDATE_BIO",
  1101. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1102. );
  1103. cb({ status: "failure", message: err });
  1104. } else {
  1105. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1106. cb({
  1107. status: "success",
  1108. message: "Bio updated successfully"
  1109. });
  1110. }
  1111. }
  1112. );
  1113. }),
  1114. /**
  1115. * Updates the type of a user's avatar
  1116. *
  1117. * @param {object} session - the session object automatically added by socket.io
  1118. * @param {string} updatingUserId - the updating user's id
  1119. * @param {string} newType - the new type
  1120. * @param {Function} cb - gets called with the result
  1121. */
  1122. updateAvatarType: isLoginRequired(async function updateAvatarType(session, updatingUserId, newType, cb) {
  1123. const userModel = await DBModule.runJob(
  1124. "GET_MODEL",
  1125. {
  1126. modelName: "user"
  1127. },
  1128. this
  1129. );
  1130. async.waterfall(
  1131. [
  1132. next => {
  1133. if (updatingUserId === session.userId) return next(null, true);
  1134. return userModel.findOne({ _id: session.userId }, next);
  1135. },
  1136. (user, next) => {
  1137. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1138. return userModel.findOne({ _id: updatingUserId }, next);
  1139. },
  1140. (user, next) => {
  1141. if (!user) return next("User not found.");
  1142. return userModel.findOneAndUpdate(
  1143. { _id: updatingUserId },
  1144. { $set: { "avatar.type": newType } },
  1145. { new: true, runValidators: true },
  1146. next
  1147. );
  1148. }
  1149. ],
  1150. async err => {
  1151. if (err && err !== true) {
  1152. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1153. this.log(
  1154. "ERROR",
  1155. "UPDATE_AVATAR_TYPE",
  1156. `Couldn't update avatar type for user "${updatingUserId}" to type "${newType}". "${err}"`
  1157. );
  1158. return cb({ status: "failure", message: err });
  1159. }
  1160. this.log(
  1161. "SUCCESS",
  1162. "UPDATE_AVATAR_TYPE",
  1163. `Updated avatar type for user "${updatingUserId}" to type "${newType}".`
  1164. );
  1165. return cb({
  1166. status: "success",
  1167. message: "Avatar type updated successfully"
  1168. });
  1169. }
  1170. );
  1171. }),
  1172. /**
  1173. * Updates a user's role
  1174. *
  1175. * @param {object} session - the session object automatically added by socket.io
  1176. * @param {string} updatingUserId - the updating user's id
  1177. * @param {string} newRole - the new role
  1178. * @param {Function} cb - gets called with the result
  1179. */
  1180. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1181. newRole = newRole.toLowerCase();
  1182. const userModel = await DBModule.runJob(
  1183. "GET_MODEL",
  1184. {
  1185. modelName: "user"
  1186. },
  1187. this
  1188. );
  1189. async.waterfall(
  1190. [
  1191. next => {
  1192. userModel.findOne({ _id: updatingUserId }, next);
  1193. },
  1194. (user, next) => {
  1195. if (!user) return next("User not found.");
  1196. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1197. return next();
  1198. },
  1199. next => {
  1200. userModel.updateOne(
  1201. { _id: updatingUserId },
  1202. { $set: { role: newRole } },
  1203. { runValidators: true },
  1204. next
  1205. );
  1206. }
  1207. ],
  1208. async err => {
  1209. if (err && err !== true) {
  1210. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1211. this.log(
  1212. "ERROR",
  1213. "UPDATE_ROLE",
  1214. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1215. );
  1216. return cb({ status: "failure", message: err });
  1217. }
  1218. this.log(
  1219. "SUCCESS",
  1220. "UPDATE_ROLE",
  1221. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1222. );
  1223. return cb({
  1224. status: "success",
  1225. message: "Role successfully updated."
  1226. });
  1227. }
  1228. );
  1229. }),
  1230. /**
  1231. * Updates a user's password
  1232. *
  1233. * @param {object} session - the session object automatically added by socket.io
  1234. * @param {string} previousPassword - the previous password
  1235. * @param {string} newPassword - the new password
  1236. * @param {Function} cb - gets called with the result
  1237. */
  1238. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1239. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1240. async.waterfall(
  1241. [
  1242. next => {
  1243. userModel.findOne({ _id: session.userId }, next);
  1244. },
  1245. (user, next) => {
  1246. if (!user.services.password) return next("This account does not have a password set.");
  1247. return next(null, user.services.password.password);
  1248. },
  1249. (storedPassword, next) => {
  1250. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1251. if (res) return next();
  1252. return next("Please enter the correct previous password.");
  1253. });
  1254. },
  1255. next => {
  1256. if (!DBModule.passwordValid(newPassword))
  1257. return next("Invalid new password. Check if it meets all the requirements.");
  1258. return next();
  1259. },
  1260. next => {
  1261. bcrypt.genSalt(10, next);
  1262. },
  1263. // hash the password
  1264. (salt, next) => {
  1265. bcrypt.hash(sha256(newPassword), salt, next);
  1266. },
  1267. (hashedPassword, next) => {
  1268. userModel.updateOne(
  1269. { _id: session.userId },
  1270. {
  1271. $set: {
  1272. "services.password.password": hashedPassword
  1273. }
  1274. },
  1275. next
  1276. );
  1277. }
  1278. ],
  1279. async err => {
  1280. if (err) {
  1281. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1282. this.log(
  1283. "ERROR",
  1284. "UPDATE_PASSWORD",
  1285. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1286. );
  1287. return cb({ status: "failure", message: err });
  1288. }
  1289. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1290. return cb({
  1291. status: "success",
  1292. message: "Password successfully updated."
  1293. });
  1294. }
  1295. );
  1296. }),
  1297. /**
  1298. * Requests a password for a session
  1299. *
  1300. * @param {object} session - the session object automatically added by socket.io
  1301. * @param {string} email - the email of the user that requests a password reset
  1302. * @param {Function} cb - gets called with the result
  1303. */
  1304. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1305. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1306. const passwordRequestSchema = await MailModule.runJob(
  1307. "GET_SCHEMA",
  1308. {
  1309. schemaName: "passwordRequest"
  1310. },
  1311. this
  1312. );
  1313. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1314. async.waterfall(
  1315. [
  1316. next => {
  1317. userModel.findOne({ _id: session.userId }, next);
  1318. },
  1319. (user, next) => {
  1320. if (!user) return next("User not found.");
  1321. if (user.services.password && user.services.password.password)
  1322. return next("You already have a password set.");
  1323. return next(null, user);
  1324. },
  1325. (user, next) => {
  1326. const expires = new Date();
  1327. expires.setDate(expires.getDate() + 1);
  1328. userModel.findOneAndUpdate(
  1329. { "email.address": user.email.address },
  1330. {
  1331. $set: {
  1332. "services.password": {
  1333. set: { code, expires }
  1334. }
  1335. }
  1336. },
  1337. { runValidators: true },
  1338. next
  1339. );
  1340. },
  1341. (user, next) => {
  1342. passwordRequestSchema(user.email.address, user.username, code, next);
  1343. }
  1344. ],
  1345. async err => {
  1346. if (err && err !== true) {
  1347. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1348. this.log(
  1349. "ERROR",
  1350. "REQUEST_PASSWORD",
  1351. `UserId '${session.userId}' failed to request password. '${err}'`
  1352. );
  1353. return cb({ status: "failure", message: err });
  1354. }
  1355. this.log(
  1356. "SUCCESS",
  1357. "REQUEST_PASSWORD",
  1358. `UserId '${session.userId}' successfully requested a password.`
  1359. );
  1360. return cb({
  1361. status: "success",
  1362. message: "Successfully requested password."
  1363. });
  1364. }
  1365. );
  1366. }),
  1367. /**
  1368. * Verifies a password code
  1369. *
  1370. * @param {object} session - the session object automatically added by socket.io
  1371. * @param {string} code - the password code
  1372. * @param {Function} cb - gets called with the result
  1373. */
  1374. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1375. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1376. async.waterfall(
  1377. [
  1378. next => {
  1379. if (!code || typeof code !== "string") return next("Invalid code.");
  1380. return userModel.findOne(
  1381. {
  1382. "services.password.set.code": code,
  1383. _id: session.userId
  1384. },
  1385. next
  1386. );
  1387. },
  1388. (user, next) => {
  1389. if (!user) return next("Invalid code.");
  1390. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1391. return next(null);
  1392. }
  1393. ],
  1394. async err => {
  1395. if (err && err !== true) {
  1396. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1397. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1398. cb({ status: "failure", message: err });
  1399. } else {
  1400. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1401. cb({
  1402. status: "success",
  1403. message: "Successfully verified password code."
  1404. });
  1405. }
  1406. }
  1407. );
  1408. }),
  1409. /**
  1410. * Adds a password to a user with a code
  1411. *
  1412. * @param {object} session - the session object automatically added by socket.io
  1413. * @param {string} code - the password code
  1414. * @param {string} newPassword - the new password code
  1415. * @param {Function} cb - gets called with the result
  1416. */
  1417. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1418. const userModel = await DBModule.runJob(
  1419. "GET_MODEL",
  1420. {
  1421. modelName: "user"
  1422. },
  1423. this
  1424. );
  1425. async.waterfall(
  1426. [
  1427. next => {
  1428. if (!code || typeof code !== "string") return next("Invalid code.");
  1429. return userModel.findOne({ "services.password.set.code": code }, next);
  1430. },
  1431. (user, next) => {
  1432. if (!user) return next("Invalid code.");
  1433. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1434. return next();
  1435. },
  1436. next => {
  1437. if (!DBModule.passwordValid(newPassword))
  1438. return next("Invalid password. Check if it meets all the requirements.");
  1439. return next();
  1440. },
  1441. next => {
  1442. bcrypt.genSalt(10, next);
  1443. },
  1444. // hash the password
  1445. (salt, next) => {
  1446. bcrypt.hash(sha256(newPassword), salt, next);
  1447. },
  1448. (hashedPassword, next) => {
  1449. userModel.updateOne(
  1450. { "services.password.set.code": code },
  1451. {
  1452. $set: {
  1453. "services.password.password": hashedPassword
  1454. },
  1455. $unset: { "services.password.set": "" }
  1456. },
  1457. { runValidators: true },
  1458. next
  1459. );
  1460. }
  1461. ],
  1462. async err => {
  1463. if (err && err !== true) {
  1464. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1465. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1466. cb({ status: "failure", message: err });
  1467. } else {
  1468. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1469. CacheModule.runJob("PUB", {
  1470. channel: "user.linkPassword",
  1471. value: session.userId
  1472. });
  1473. cb({
  1474. status: "success",
  1475. message: "Successfully added password."
  1476. });
  1477. }
  1478. }
  1479. );
  1480. }),
  1481. /**
  1482. * Unlinks password from user
  1483. *
  1484. * @param {object} session - the session object automatically added by socket.io
  1485. * @param {Function} cb - gets called with the result
  1486. */
  1487. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1488. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1489. async.waterfall(
  1490. [
  1491. next => {
  1492. userModel.findOne({ _id: session.userId }, next);
  1493. },
  1494. (user, next) => {
  1495. if (!user) return next("Not logged in.");
  1496. if (!user.services.github || !user.services.github.id)
  1497. return next("You can't remove password login without having GitHub login.");
  1498. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1499. }
  1500. ],
  1501. async err => {
  1502. if (err && err !== true) {
  1503. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1504. this.log(
  1505. "ERROR",
  1506. "UNLINK_PASSWORD",
  1507. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1508. );
  1509. cb({ status: "failure", message: err });
  1510. } else {
  1511. this.log(
  1512. "SUCCESS",
  1513. "UNLINK_PASSWORD",
  1514. `Unlinking password successful for userId '${session.userId}'.`
  1515. );
  1516. CacheModule.runJob("PUB", {
  1517. channel: "user.unlinkPassword",
  1518. value: session.userId
  1519. });
  1520. cb({
  1521. status: "success",
  1522. message: "Successfully unlinked password."
  1523. });
  1524. }
  1525. }
  1526. );
  1527. }),
  1528. /**
  1529. * Unlinks GitHub from user
  1530. *
  1531. * @param {object} session - the session object automatically added by socket.io
  1532. * @param {Function} cb - gets called with the result
  1533. */
  1534. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1535. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1536. async.waterfall(
  1537. [
  1538. next => {
  1539. userModel.findOne({ _id: session.userId }, next);
  1540. },
  1541. (user, next) => {
  1542. if (!user) return next("Not logged in.");
  1543. if (!user.services.password || !user.services.password.password)
  1544. return next("You can't remove GitHub login without having password login.");
  1545. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1546. }
  1547. ],
  1548. async err => {
  1549. if (err && err !== true) {
  1550. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1551. this.log(
  1552. "ERROR",
  1553. "UNLINK_GITHUB",
  1554. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  1555. );
  1556. cb({ status: "failure", message: err });
  1557. } else {
  1558. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  1559. CacheModule.runJob("PUB", {
  1560. channel: "user.unlinkGithub",
  1561. value: session.userId
  1562. });
  1563. cb({
  1564. status: "success",
  1565. message: "Successfully unlinked GitHub."
  1566. });
  1567. }
  1568. }
  1569. );
  1570. }),
  1571. /**
  1572. * Requests a password reset for an email
  1573. *
  1574. * @param {object} session - the session object automatically added by socket.io
  1575. * @param {string} email - the email of the user that requests a password reset
  1576. * @param {Function} cb - gets called with the result
  1577. */
  1578. async requestPasswordReset(session, email, cb) {
  1579. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1580. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1581. const resetPasswordRequestSchema = await MailModule.runJob(
  1582. "GET_SCHEMA",
  1583. {
  1584. schemaName: "resetPasswordRequest"
  1585. },
  1586. this
  1587. );
  1588. async.waterfall(
  1589. [
  1590. next => {
  1591. if (!email || typeof email !== "string") return next("Invalid email.");
  1592. email = email.toLowerCase();
  1593. return userModel.findOne({ "email.address": email }, next);
  1594. },
  1595. (user, next) => {
  1596. if (!user) return next("User not found.");
  1597. if (!user.services.password || !user.services.password.password)
  1598. return next("User does not have a password set, and probably uses GitHub to log in.");
  1599. return next(null, user);
  1600. },
  1601. (user, next) => {
  1602. const expires = new Date();
  1603. expires.setDate(expires.getDate() + 1);
  1604. userModel.findOneAndUpdate(
  1605. { "email.address": email },
  1606. {
  1607. $set: {
  1608. "services.password.reset": {
  1609. code,
  1610. expires
  1611. }
  1612. }
  1613. },
  1614. { runValidators: true },
  1615. next
  1616. );
  1617. },
  1618. (user, next) => {
  1619. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  1620. }
  1621. ],
  1622. async err => {
  1623. if (err && err !== true) {
  1624. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1625. this.log(
  1626. "ERROR",
  1627. "REQUEST_PASSWORD_RESET",
  1628. `Email '${email}' failed to request password reset. '${err}'`
  1629. );
  1630. cb({ status: "failure", message: err });
  1631. } else {
  1632. this.log(
  1633. "SUCCESS",
  1634. "REQUEST_PASSWORD_RESET",
  1635. `Email '${email}' successfully requested a password reset.`
  1636. );
  1637. cb({
  1638. status: "success",
  1639. message: "Successfully requested password reset."
  1640. });
  1641. }
  1642. }
  1643. );
  1644. },
  1645. /**
  1646. * Verifies a reset code
  1647. *
  1648. * @param {object} session - the session object automatically added by socket.io
  1649. * @param {string} code - the password reset code
  1650. * @param {Function} cb - gets called with the result
  1651. */
  1652. async verifyPasswordResetCode(session, code, cb) {
  1653. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1654. async.waterfall(
  1655. [
  1656. next => {
  1657. if (!code || typeof code !== "string") return next("Invalid code.");
  1658. return userModel.findOne({ "services.password.reset.code": code }, next);
  1659. },
  1660. (user, next) => {
  1661. if (!user) return next("Invalid code.");
  1662. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1663. return next(null);
  1664. }
  1665. ],
  1666. async err => {
  1667. if (err && err !== true) {
  1668. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1669. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  1670. cb({ status: "failure", message: err });
  1671. } else {
  1672. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  1673. cb({
  1674. status: "success",
  1675. message: "Successfully verified password reset code."
  1676. });
  1677. }
  1678. }
  1679. );
  1680. },
  1681. /**
  1682. * Changes a user's password with a reset code
  1683. *
  1684. * @param {object} session - the session object automatically added by socket.io
  1685. * @param {string} code - the password reset code
  1686. * @param {string} newPassword - the new password reset code
  1687. * @param {Function} cb - gets called with the result
  1688. */
  1689. async changePasswordWithResetCode(session, code, newPassword, cb) {
  1690. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1691. async.waterfall(
  1692. [
  1693. next => {
  1694. if (!code || typeof code !== "string") return next("Invalid code.");
  1695. return userModel.findOne({ "services.password.reset.code": code }, next);
  1696. },
  1697. (user, next) => {
  1698. if (!user) return next("Invalid code.");
  1699. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1700. return next();
  1701. },
  1702. next => {
  1703. if (!DBModule.passwordValid(newPassword))
  1704. return next("Invalid password. Check if it meets all the requirements.");
  1705. return next();
  1706. },
  1707. next => {
  1708. bcrypt.genSalt(10, next);
  1709. },
  1710. // hash the password
  1711. (salt, next) => {
  1712. bcrypt.hash(sha256(newPassword), salt, next);
  1713. },
  1714. (hashedPassword, next) => {
  1715. userModel.updateOne(
  1716. { "services.password.reset.code": code },
  1717. {
  1718. $set: {
  1719. "services.password.password": hashedPassword
  1720. },
  1721. $unset: { "services.password.reset": "" }
  1722. },
  1723. { runValidators: true },
  1724. next
  1725. );
  1726. }
  1727. ],
  1728. async err => {
  1729. if (err && err !== true) {
  1730. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1731. this.log(
  1732. "ERROR",
  1733. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1734. `Code '${code}' failed to change password. '${err}'`
  1735. );
  1736. cb({ status: "failure", message: err });
  1737. } else {
  1738. this.log(
  1739. "SUCCESS",
  1740. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1741. `Code '${code}' successfully changed password.`
  1742. );
  1743. cb({
  1744. status: "success",
  1745. message: "Successfully changed password."
  1746. });
  1747. }
  1748. }
  1749. );
  1750. },
  1751. /**
  1752. * Bans a user by userId
  1753. *
  1754. * @param {object} session - the session object automatically added by socket.io
  1755. * @param {string} value - the user id that is going to be banned
  1756. * @param {string} reason - the reason for the ban
  1757. * @param {string} expiresAt - the time the ban expires
  1758. * @param {Function} cb - gets called with the result
  1759. */
  1760. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  1761. async.waterfall(
  1762. [
  1763. next => {
  1764. if (!userId) return next("You must provide a userId to ban.");
  1765. if (!reason) return next("You must provide a reason for the ban.");
  1766. return next();
  1767. },
  1768. next => {
  1769. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  1770. const date = new Date();
  1771. switch (expiresAt) {
  1772. case "1h":
  1773. expiresAt = date.setHours(date.getHours() + 1);
  1774. break;
  1775. case "12h":
  1776. expiresAt = date.setHours(date.getHours() + 12);
  1777. break;
  1778. case "1d":
  1779. expiresAt = date.setDate(date.getDate() + 1);
  1780. break;
  1781. case "1w":
  1782. expiresAt = date.setDate(date.getDate() + 7);
  1783. break;
  1784. case "1m":
  1785. expiresAt = date.setMonth(date.getMonth() + 1);
  1786. break;
  1787. case "3m":
  1788. expiresAt = date.setMonth(date.getMonth() + 3);
  1789. break;
  1790. case "6m":
  1791. expiresAt = date.setMonth(date.getMonth() + 6);
  1792. break;
  1793. case "1y":
  1794. expiresAt = date.setFullYear(date.getFullYear() + 1);
  1795. break;
  1796. case "never":
  1797. expiresAt = new Date(3093527980800000);
  1798. break;
  1799. default:
  1800. return next("Invalid expire date.");
  1801. }
  1802. return next();
  1803. },
  1804. next => {
  1805. PunishmentsModule.runJob(
  1806. "ADD_PUNISHMENT",
  1807. {
  1808. type: "banUserId",
  1809. value: userId,
  1810. reason,
  1811. expiresAt,
  1812. punishedBy: "" // needs changed
  1813. },
  1814. this
  1815. )
  1816. .then(punishment => next(null, punishment))
  1817. .catch(next);
  1818. },
  1819. (punishment, next) => {
  1820. CacheModule.runJob("PUB", {
  1821. channel: "user.ban",
  1822. value: { userId, punishment }
  1823. });
  1824. next();
  1825. }
  1826. ],
  1827. async err => {
  1828. if (err && err !== true) {
  1829. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1830. this.log(
  1831. "ERROR",
  1832. "BAN_USER_BY_ID",
  1833. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  1834. );
  1835. cb({ status: "failure", message: err });
  1836. } else {
  1837. this.log(
  1838. "SUCCESS",
  1839. "BAN_USER_BY_ID",
  1840. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  1841. );
  1842. cb({
  1843. status: "success",
  1844. message: "Successfully banned user."
  1845. });
  1846. }
  1847. }
  1848. );
  1849. })
  1850. };