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