users.js 54 KB

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