users.js 63 KB

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