users.js 64 KB

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