users.js 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004
  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 SongsModule = moduleManager.modules.songs;
  15. const ActivitiesModule = moduleManager.modules.activities;
  16. const PlaylistsModule = moduleManager.modules.playlists;
  17. CacheModule.runJob("SUB", {
  18. channel: "user.updatePreferences",
  19. cb: res => {
  20. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  21. sockets.forEach(socket => {
  22. socket.dispatch("keep.event:user.preferences.updated", { data: { preferences: res.preferences } });
  23. });
  24. });
  25. }
  26. });
  27. CacheModule.runJob("SUB", {
  28. channel: "user.updateOrderOfFavoriteStations",
  29. cb: res => {
  30. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  31. sockets.forEach(socket => {
  32. socket.dispatch("event:user.orderOfFavoriteStations.updated", {
  33. data: { order: res.favoriteStations }
  34. });
  35. });
  36. });
  37. }
  38. });
  39. CacheModule.runJob("SUB", {
  40. channel: "user.updateOrderOfPlaylists",
  41. cb: res => {
  42. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  43. sockets.forEach(socket => {
  44. socket.dispatch("event:user.orderOfPlaylists.updated", { data: { order: res.orderOfPlaylists } });
  45. });
  46. });
  47. WSModule.runJob("EMIT_TO_ROOM", {
  48. room: `profile.${res.userId}.playlists`,
  49. args: ["event:user.orderOfPlaylists.updated", { data: { order: res.orderOfPlaylists } }]
  50. });
  51. }
  52. });
  53. CacheModule.runJob("SUB", {
  54. channel: "user.updateUsername",
  55. cb: user => {
  56. WSModule.runJob("SOCKETS_FROM_USER", { userId: user._id }).then(sockets => {
  57. sockets.forEach(socket => {
  58. socket.dispatch("keep.event:user.username.updated", { data: { username: user.username } });
  59. });
  60. });
  61. }
  62. });
  63. CacheModule.runJob("SUB", {
  64. channel: "user.removeSessions",
  65. cb: userId => {
  66. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets =>
  67. sockets.forEach(socket => socket.dispatch("keep.event:user.session.deleted"))
  68. );
  69. }
  70. });
  71. CacheModule.runJob("SUB", {
  72. channel: "user.linkPassword",
  73. cb: userId => {
  74. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  75. sockets.forEach(socket => {
  76. socket.dispatch("event:user.password.linked");
  77. });
  78. });
  79. }
  80. });
  81. CacheModule.runJob("SUB", {
  82. channel: "user.unlinkPassword",
  83. cb: userId => {
  84. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  85. sockets.forEach(socket => {
  86. socket.dispatch("event:user.password.unlinked");
  87. });
  88. });
  89. }
  90. });
  91. CacheModule.runJob("SUB", {
  92. channel: "user.linkGithub",
  93. cb: userId => {
  94. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  95. sockets.forEach(socket => {
  96. socket.dispatch("event:user.github.linked");
  97. });
  98. });
  99. }
  100. });
  101. CacheModule.runJob("SUB", {
  102. channel: "user.unlinkGithub",
  103. cb: userId => {
  104. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  105. sockets.forEach(socket => {
  106. socket.dispatch("event:user.github.unlinked");
  107. });
  108. });
  109. }
  110. });
  111. CacheModule.runJob("SUB", {
  112. channel: "user.ban",
  113. cb: data => {
  114. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  115. sockets.forEach(socket => {
  116. socket.dispatch("keep.event:user.banned", { data: { ban: data.punishment } });
  117. socket.disconnect(true);
  118. });
  119. });
  120. }
  121. });
  122. CacheModule.runJob("SUB", {
  123. channel: "user.favoritedStation",
  124. cb: data => {
  125. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  126. sockets.forEach(socket => {
  127. socket.dispatch("event:user.station.favorited", { data: { stationId: data.stationId } });
  128. });
  129. });
  130. }
  131. });
  132. CacheModule.runJob("SUB", {
  133. channel: "user.unfavoritedStation",
  134. cb: data => {
  135. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  136. sockets.forEach(socket => {
  137. socket.dispatch("event:user.station.unfavorited", { data: { stationId: data.stationId } });
  138. });
  139. });
  140. }
  141. });
  142. CacheModule.runJob("SUB", {
  143. channel: "user.removeAccount",
  144. cb: userId => {
  145. WSModule.runJob("EMIT_TO_ROOMS", {
  146. rooms: ["admin.users", `edit-user.${userId}`],
  147. args: ["event:user.removed", { data: { userId } }]
  148. });
  149. }
  150. });
  151. CacheModule.runJob("SUB", {
  152. channel: "user.updated",
  153. cb: async data => {
  154. const userModel = await DBModule.runJob("GET_MODEL", {
  155. modelName: "user"
  156. });
  157. userModel.findOne(
  158. { _id: data.userId },
  159. [
  160. "_id",
  161. "name",
  162. "username",
  163. "avatar",
  164. "services.github.id",
  165. "role",
  166. "email.address",
  167. "email.verified",
  168. "statistics.songsRequested",
  169. "services.password.password"
  170. ],
  171. (err, user) => {
  172. const newUser = { ...user._doc, hasPassword: !!user.services.password.password };
  173. delete newUser.services.password;
  174. WSModule.runJob("EMIT_TO_ROOMS", {
  175. rooms: ["admin.users", `edit-user.${data.userId}`],
  176. args: ["event:admin.user.updated", { data: { user: newUser } }]
  177. });
  178. }
  179. );
  180. }
  181. });
  182. export default {
  183. /**
  184. * Gets users, used in the admin users page by the AdvancedTable component
  185. *
  186. * @param {object} session - the session object automatically added by the websocket
  187. * @param page - the page
  188. * @param pageSize - the size per page
  189. * @param properties - the properties to return for each user
  190. * @param sort - the sort object
  191. * @param queries - the queries array
  192. * @param operator - the operator for queries
  193. * @param cb
  194. */
  195. getData: isAdminRequired(async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  196. async.waterfall(
  197. [
  198. next => {
  199. DBModule.runJob(
  200. "GET_DATA",
  201. {
  202. page,
  203. pageSize,
  204. properties,
  205. sort,
  206. queries,
  207. operator,
  208. modelName: "user",
  209. blacklistedProperties: [
  210. "services.password.password",
  211. "services.password.reset.code",
  212. "services.password.reset.expires",
  213. "services.password.set.code",
  214. "services.password.set.expires",
  215. "services.github.access_token",
  216. "email.verificationToken"
  217. ],
  218. specialProperties: {
  219. hasPassword: [
  220. {
  221. $addFields: {
  222. hasPassword: {
  223. $cond: [
  224. { $eq: [{ $type: "$services.password.password" }, "string"] },
  225. true,
  226. false
  227. ]
  228. }
  229. }
  230. }
  231. ]
  232. },
  233. specialQueries: {}
  234. },
  235. this
  236. )
  237. .then(response => {
  238. next(null, response);
  239. })
  240. .catch(err => {
  241. next(err);
  242. });
  243. }
  244. ],
  245. async (err, response) => {
  246. if (err && err !== true) {
  247. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  248. this.log("ERROR", "USERS_GET_DATA", `Failed to get data from users. "${err}"`);
  249. return cb({ status: "error", message: err });
  250. }
  251. this.log("SUCCESS", "USERS_GET_DATA", `Got data from users successfully.`);
  252. return cb({
  253. status: "success",
  254. message: "Successfully got data from users.",
  255. data: response
  256. });
  257. }
  258. );
  259. }),
  260. /**
  261. * Removes all data held on a user, including their ability to login
  262. *
  263. * @param {object} session - the session object automatically added by the websocket
  264. * @param {Function} cb - gets called with the result
  265. */
  266. remove: isLoginRequired(async function remove(session, cb) {
  267. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  268. const dataRequestModel = await DBModule.runJob("GET_MODEL", { modelName: "dataRequest" }, this);
  269. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  270. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  271. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  272. const dataRequestEmail = await MailModule.runJob("GET_SCHEMA", { schemaName: "dataRequest" }, this);
  273. const songsToAdjustRatings = [];
  274. async.waterfall(
  275. [
  276. // activities related to the user
  277. next => {
  278. activityModel.deleteMany({ userId: session.userId }, next);
  279. },
  280. // user's stations
  281. (res, next) => {
  282. stationModel.find({ owner: session.userId }, (err, stations) => {
  283. if (err) return next(err);
  284. return async.each(
  285. stations,
  286. (station, callback) => {
  287. // delete the station
  288. stationModel.deleteOne({ _id: station._id }, err => {
  289. if (err) return callback(err);
  290. CacheModule.runJob("HDEL", { table: "stations", key: station._id });
  291. // if applicable, delete the corresponding playlist for the station
  292. if (station.playlist)
  293. return PlaylistsModule.runJob("DELETE_PLAYLIST", {
  294. playlistId: station.playlist
  295. })
  296. .then(() => callback())
  297. .catch(callback);
  298. return callback();
  299. });
  300. },
  301. err => next(err)
  302. );
  303. });
  304. },
  305. next => {
  306. playlistModel.findOne({ createdBy: session.userId, type: "user-liked" }, next);
  307. },
  308. // get all liked songs (as the global rating values for these songs will need adjusted)
  309. (playlist, next) => {
  310. if (!playlist) return next();
  311. playlist.songs.forEach(song =>
  312. songsToAdjustRatings.push({ songId: song._id, youtubeId: song.youtubeId })
  313. );
  314. return next();
  315. },
  316. next => {
  317. playlistModel.findOne({ createdBy: session.userId, type: "user-disliked" }, next);
  318. },
  319. // get all disliked songs (as the global rating values for these songs will need adjusted)
  320. (playlist, next) => {
  321. if (!playlist) return next();
  322. playlist.songs.forEach(song =>
  323. songsToAdjustRatings.push({ songId: song._id, youtubeId: song.youtubeId })
  324. );
  325. return next();
  326. },
  327. // user's playlists
  328. next => {
  329. playlistModel.deleteMany({ createdBy: session.userId }, next);
  330. },
  331. (res, next) => {
  332. async.each(
  333. songsToAdjustRatings,
  334. (song, next) => {
  335. const { songId, youtubeId } = song;
  336. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId, youtubeId })
  337. .then(() => next())
  338. .catch(next);
  339. },
  340. err => next(err)
  341. );
  342. },
  343. // user object
  344. next => {
  345. userModel.deleteMany({ _id: session.userId }, next);
  346. },
  347. // request data removal for user
  348. (res, next) => {
  349. dataRequestModel.create({ userId: session.userId, type: "remove" }, next);
  350. },
  351. (request, next) => {
  352. WSModule.runJob("EMIT_TO_ROOM", {
  353. room: "admin.users",
  354. args: ["event:admin.dataRequests.created", { data: { request } }]
  355. });
  356. return next();
  357. },
  358. next => userModel.find({ role: "admin" }, next),
  359. // send email to all admins of a data removal request
  360. (users, next) => {
  361. if (!config.get("sendDataRequestEmails")) return next();
  362. if (users.length === 0) return next();
  363. const to = [];
  364. users.forEach(user => to.push(user.email.address));
  365. return dataRequestEmail(to, session.userId, "remove", err => next(err));
  366. }
  367. ],
  368. async err => {
  369. if (err && err !== true) {
  370. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  371. this.log(
  372. "ERROR",
  373. "USER_REMOVE",
  374. `Removing data and account for user "${session.userId}" failed. "${err}"`
  375. );
  376. return cb({ status: "error", message: err });
  377. }
  378. this.log(
  379. "SUCCESS",
  380. "USER_REMOVE",
  381. `Successfully removed data and account for user "${session.userId}"`
  382. );
  383. CacheModule.runJob("PUB", {
  384. channel: "user.removeAccount",
  385. value: session.userId
  386. });
  387. return cb({
  388. status: "success",
  389. message: "Successfully removed data and account."
  390. });
  391. }
  392. );
  393. }),
  394. /**
  395. * Removes all data held on a user, including their ability to login, by userId
  396. *
  397. * @param {object} session - the session object automatically added by the websocket
  398. * @param {string} userId - the user id that is going to be banned
  399. * @param {Function} cb - gets called with the result
  400. */
  401. adminRemove: isAdminRequired(async function adminRemove(session, userId, cb) {
  402. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  403. const dataRequestModel = await DBModule.runJob("GET_MODEL", { modelName: "dataRequest" }, this);
  404. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  405. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  406. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  407. const dataRequestEmail = await MailModule.runJob("GET_SCHEMA", { schemaName: "dataRequest" }, this);
  408. const songsToAdjustRatings = [];
  409. async.waterfall(
  410. [
  411. next => {
  412. if (!userId) return next("You must provide a userId to remove.");
  413. return next();
  414. },
  415. // activities related to the user
  416. next => {
  417. activityModel.deleteMany({ userId }, next);
  418. },
  419. // user's stations
  420. (res, next) => {
  421. stationModel.find({ owner: userId }, (err, stations) => {
  422. if (err) return next(err);
  423. return async.each(
  424. stations,
  425. (station, callback) => {
  426. // delete the station
  427. stationModel.deleteOne({ _id: station._id }, err => {
  428. if (err) return callback(err);
  429. // if applicable, delete the corresponding playlist for the station
  430. if (station.playlist)
  431. return PlaylistsModule.runJob("DELETE_PLAYLIST", {
  432. playlistId: station.playlist
  433. })
  434. .then(() => callback())
  435. .catch(callback);
  436. return callback();
  437. });
  438. },
  439. err => next(err)
  440. );
  441. });
  442. },
  443. next => {
  444. playlistModel.findOne({ createdBy: userId, type: "user-liked" }, next);
  445. },
  446. // get all liked songs (as the global rating values for these songs will need adjusted)
  447. (playlist, next) => {
  448. if (!playlist) return next();
  449. playlist.songs.forEach(song =>
  450. songsToAdjustRatings.push({ songId: song._id, youtubeId: song.youtubeId })
  451. );
  452. return next();
  453. },
  454. next => {
  455. playlistModel.findOne({ createdBy: userId, type: "user-disliked" }, next);
  456. },
  457. // get all disliked songs (as the global rating values for these songs will need adjusted)
  458. (playlist, next) => {
  459. if (!playlist) return next();
  460. playlist.songs.forEach(song =>
  461. songsToAdjustRatings.push({ songId: song._id, youtubeId: song.youtubeId })
  462. );
  463. return next();
  464. },
  465. // user's playlists
  466. next => {
  467. playlistModel.deleteMany({ createdBy: userId }, next);
  468. },
  469. (res, next) => {
  470. async.each(
  471. songsToAdjustRatings,
  472. (song, next) => {
  473. const { songId, youtubeId } = song;
  474. SongsModule.runJob("RECALCULATE_SONG_RATINGS", { songId, youtubeId })
  475. .then(() => next())
  476. .catch(next);
  477. },
  478. err => next(err)
  479. );
  480. },
  481. // user object
  482. next => {
  483. userModel.deleteMany({ _id: userId }, next);
  484. },
  485. // request data removal for user
  486. (res, next) => {
  487. dataRequestModel.create({ userId, type: "remove" }, next);
  488. },
  489. (request, next) => {
  490. WSModule.runJob("EMIT_TO_ROOM", {
  491. room: "admin.users",
  492. args: ["event:admin.dataRequests.created", { data: { request } }]
  493. });
  494. return next();
  495. },
  496. next => userModel.find({ role: "admin" }, next),
  497. // send email to all admins of a data removal request
  498. (users, next) => {
  499. if (!config.get("sendDataRequestEmails")) return next();
  500. if (users.length === 0) return next();
  501. const to = [];
  502. users.forEach(user => to.push(user.email.address));
  503. return dataRequestEmail(to, userId, "remove", err => next(err));
  504. }
  505. ],
  506. async err => {
  507. if (err && err !== true) {
  508. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  509. this.log(
  510. "ERROR",
  511. "USER_ADMIN_REMOVE",
  512. `Removing data and account for user "${userId}" failed. "${err}"`
  513. );
  514. return cb({ status: "error", message: err });
  515. }
  516. this.log("SUCCESS", "USER_ADMIN_REMOVE", `Successfully removed data and account for user "${userId}"`);
  517. CacheModule.runJob("PUB", {
  518. channel: "user.removeAccount",
  519. value: userId
  520. });
  521. return cb({
  522. status: "success",
  523. message: "Successfully removed data and account."
  524. });
  525. }
  526. );
  527. }),
  528. /**
  529. * Logs user in
  530. *
  531. * @param {object} session - the session object automatically added by the websocket
  532. * @param {string} identifier - the username or email of the user
  533. * @param {string} password - the plaintext of the user
  534. * @param {Function} cb - gets called with the result
  535. */
  536. async login(session, identifier, password, cb) {
  537. identifier = identifier.toLowerCase();
  538. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  539. const sessionSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "session" }, this);
  540. async.waterfall(
  541. [
  542. // check if a user with the requested identifier exists
  543. next => {
  544. const query = {};
  545. if (identifier.indexOf("@") !== -1) query["email.address"] = identifier;
  546. else query.username = identifier;
  547. userModel.findOne(
  548. {
  549. $or: [query]
  550. },
  551. next
  552. );
  553. },
  554. // if the user doesn't exist, respond with a failure
  555. // otherwise compare the requested password and the actual users password
  556. (user, next) => {
  557. if (!user) return next("User not found");
  558. if (!user.services.password || !user.services.password.password)
  559. return next("The account you are trying to access uses GitHub to log in.");
  560. return bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  561. if (err) return next(err);
  562. if (!match) return next("Incorrect password");
  563. return next(null, user);
  564. });
  565. },
  566. (user, next) => {
  567. UtilsModule.runJob("GUID", {}, this).then(sessionId => {
  568. next(null, user, sessionId);
  569. });
  570. },
  571. (user, sessionId, next) => {
  572. CacheModule.runJob(
  573. "HSET",
  574. {
  575. table: "sessions",
  576. key: sessionId,
  577. value: sessionSchema(sessionId, user._id)
  578. },
  579. this
  580. )
  581. .then(() => next(null, sessionId))
  582. .catch(next);
  583. }
  584. ],
  585. async (err, sessionId) => {
  586. if (err && err !== true) {
  587. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  588. this.log(
  589. "ERROR",
  590. "USER_PASSWORD_LOGIN",
  591. `Login failed with password for user "${identifier}". "${err}"`
  592. );
  593. return cb({ status: "error", message: err });
  594. }
  595. this.log("SUCCESS", "USER_PASSWORD_LOGIN", `Login successful with password for user "${identifier}"`);
  596. return cb({
  597. status: "success",
  598. message: "Login successful",
  599. data: { SID: sessionId }
  600. });
  601. }
  602. );
  603. },
  604. /**
  605. * Registers a new user
  606. *
  607. * @param {object} session - the session object automatically added by the websocket
  608. * @param {string} username - the username for the new user
  609. * @param {string} email - the email for the new user
  610. * @param {string} password - the plaintext password for the new user
  611. * @param {object} recaptcha - the recaptcha data
  612. * @param {Function} cb - gets called with the result
  613. */
  614. async register(session, username, email, password, recaptcha, cb) {
  615. email = email.toLowerCase();
  616. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  617. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  618. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  619. async.waterfall(
  620. [
  621. next => {
  622. if (config.get("registrationDisabled") === true)
  623. return next("Registration is not allowed at this time.");
  624. return next();
  625. },
  626. next => {
  627. if (!DBModule.passwordValid(password))
  628. return next("Invalid password. Check if it meets all the requirements.");
  629. return next();
  630. },
  631. // verify the request with google recaptcha
  632. next => {
  633. if (config.get("apis.recaptcha.enabled") === true)
  634. axios
  635. .post("https://www.google.com/recaptcha/api/siteverify", {
  636. data: {
  637. secret: config.get("apis").recaptcha.secret,
  638. response: recaptcha
  639. }
  640. })
  641. .then(res => next(null, res.data))
  642. .catch(err => next(err));
  643. else next(null, null);
  644. },
  645. // check if the response from Google recaptcha is successful
  646. // if it is, we check if a user with the requested username already exists
  647. (body, next) => {
  648. if (config.get("apis.recaptcha.enabled") === true)
  649. if (body.success !== true) return next("Response from recaptcha was not successful.");
  650. return userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  651. },
  652. // if the user already exists, respond with that
  653. // otherwise check if a user with the requested email already exists
  654. (user, next) => {
  655. if (user) return next("A user with that username already exists.");
  656. return userModel.findOne({ "email.address": email }, next);
  657. },
  658. // if the user already exists, respond with that
  659. // otherwise, generate a salt to use with hashing the new users password
  660. (user, next) => {
  661. if (user) return next("A user with that email already exists.");
  662. return bcrypt.genSalt(10, next);
  663. },
  664. // hash the password
  665. (salt, next) => {
  666. bcrypt.hash(sha256(password), salt, next);
  667. },
  668. (hash, next) => {
  669. UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 12 }, this).then(_id => {
  670. next(null, hash, _id);
  671. });
  672. },
  673. // create the user object
  674. (hash, _id, next) => {
  675. next(null, {
  676. _id,
  677. name: username,
  678. username,
  679. email: {
  680. address: email,
  681. verificationToken
  682. },
  683. services: {
  684. password: {
  685. password: hash
  686. }
  687. }
  688. });
  689. },
  690. // generate the url for gravatar avatar
  691. (user, next) => {
  692. UtilsModule.runJob("CREATE_GRAVATAR", { email: user.email.address }, this).then(url => {
  693. const avatarColors = ["blue", "orange", "green", "purple", "teal"];
  694. user.avatar = {
  695. type: "initials",
  696. color: avatarColors[Math.floor(Math.random() * avatarColors.length)],
  697. url
  698. };
  699. next(null, user);
  700. });
  701. },
  702. // save the new user to the database
  703. (user, next) => {
  704. userModel.create(user, next);
  705. },
  706. // respond with the new user
  707. (user, next) => {
  708. verifyEmailSchema(email, username, verificationToken, err => {
  709. next(err, user._id);
  710. });
  711. },
  712. // create a liked songs playlist for the new user
  713. (userId, next) => {
  714. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  715. userId,
  716. displayName: "Liked Songs",
  717. type: "user-liked"
  718. })
  719. .then(likedSongsPlaylist => {
  720. next(null, likedSongsPlaylist, userId);
  721. })
  722. .catch(err => next(err));
  723. },
  724. // create a disliked songs playlist for the new user
  725. (likedSongsPlaylist, userId, next) => {
  726. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  727. userId,
  728. displayName: "Disliked Songs",
  729. type: "user-disliked"
  730. })
  731. .then(dislikedSongsPlaylist => {
  732. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  733. })
  734. .catch(err => next(err));
  735. },
  736. // associate liked + disliked songs playlist to the user object
  737. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  738. userModel.updateOne(
  739. { _id: userId },
  740. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  741. { runValidators: true },
  742. err => {
  743. if (err) return next(err);
  744. return next(null, userId);
  745. }
  746. );
  747. }
  748. ],
  749. async (err, userId) => {
  750. if (err && err !== true) {
  751. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  752. this.log(
  753. "ERROR",
  754. "USER_PASSWORD_REGISTER",
  755. `Register failed with password for user "${username}"."${err}"`
  756. );
  757. return cb({ status: "error", message: err });
  758. }
  759. ActivitiesModule.runJob("ADD_ACTIVITY", {
  760. userId,
  761. type: "user__joined",
  762. payload: { message: "Welcome to Musare!" }
  763. });
  764. this.log(
  765. "SUCCESS",
  766. "USER_PASSWORD_REGISTER",
  767. `Register successful with password for user "${username}".`
  768. );
  769. const res = await this.module.runJob(
  770. "RUN_ACTION2",
  771. {
  772. session,
  773. namespace: "users",
  774. action: "login",
  775. args: [email, password]
  776. },
  777. this
  778. );
  779. const obj = {
  780. status: "success",
  781. message: "Successfully registered."
  782. };
  783. if (res.status === "success") {
  784. obj.SID = res.data.SID;
  785. }
  786. return cb(obj);
  787. }
  788. );
  789. },
  790. /**
  791. * Logs out a user
  792. *
  793. * @param {object} session - the session object automatically added by the websocket
  794. * @param {Function} cb - gets called with the result
  795. */
  796. logout(session, cb) {
  797. async.waterfall(
  798. [
  799. next => {
  800. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }, this)
  801. .then(session => next(null, session))
  802. .catch(next);
  803. },
  804. (session, next) => {
  805. if (!session) return next("Session not found");
  806. return next(null, session);
  807. },
  808. (session, next) => {
  809. CacheModule.runJob("PUB", {
  810. channel: "user.removeSessions",
  811. value: session.userId
  812. });
  813. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  814. setTimeout(() => {
  815. CacheModule.runJob("HDEL", { table: "sessions", key: session.sessionId }, this)
  816. .then(() => next())
  817. .catch(next);
  818. }, 50);
  819. }
  820. ],
  821. async err => {
  822. if (err && err !== true) {
  823. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  824. this.log("ERROR", "USER_LOGOUT", `Logout failed. "${err}" `);
  825. return cb({ status: "error", message: err });
  826. }
  827. this.log("SUCCESS", "USER_LOGOUT", `Logout successful.`);
  828. return cb({
  829. status: "success",
  830. message: "Successfully logged out."
  831. });
  832. }
  833. );
  834. },
  835. /**
  836. * Checks if user's password is correct (e.g. before a sensitive action)
  837. *
  838. * @param {object} session - the session object automatically added by the websocket
  839. * @param {string} password - the password the user entered that we need to validate
  840. * @param {Function} cb - gets called with the result
  841. */
  842. confirmPasswordMatch: isLoginRequired(async function confirmPasswordMatch(session, password, cb) {
  843. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  844. return async.waterfall(
  845. [
  846. next => {
  847. if (!password || password === "") return next("Please provide a valid password.");
  848. return next();
  849. },
  850. next => {
  851. userModel.findOne({ _id: session.userId }, (err, user) =>
  852. next(err, user.services.password.password)
  853. );
  854. },
  855. (passwordHash, next) => {
  856. if (!passwordHash) return next("Your account doesn't have a password linked.");
  857. return bcrypt.compare(sha256(password), passwordHash, (err, match) => {
  858. if (err) return next(err);
  859. if (!match) return next(null, false);
  860. return next(null, true);
  861. });
  862. }
  863. ],
  864. async (err, match) => {
  865. if (err) {
  866. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  867. this.log(
  868. "ERROR",
  869. "USER_CONFIRM_PASSWORD",
  870. `Couldn't confirm password for user "${session.userId}". "${err}"`
  871. );
  872. return cb({ status: "error", message: err });
  873. }
  874. if (match) {
  875. this.log(
  876. "SUCCESS",
  877. "USER_CONFIRM_PASSWORD",
  878. `Successfully checked for password match (it matched) for user "${session.userId}".`
  879. );
  880. return cb({
  881. status: "success",
  882. message: "Your password matches."
  883. });
  884. }
  885. this.log(
  886. "SUCCESS",
  887. "USER_CONFIRM_PASSWORD",
  888. `Successfully checked for password match (it didn't match) for user "${session.userId}".`
  889. );
  890. return cb({
  891. status: "error",
  892. message: "Unfortunately your password doesn't match."
  893. });
  894. }
  895. );
  896. }),
  897. /**
  898. * Checks if user's github access token has expired or not (ie. if their github account is still linked)
  899. *
  900. * @param {object} session - the session object automatically added by the websocket
  901. * @param {Function} cb - gets called with the result
  902. */
  903. confirmGithubLink: isLoginRequired(async function confirmGithubLink(session, cb) {
  904. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  905. return async.waterfall(
  906. [
  907. next => {
  908. userModel.findOne({ _id: session.userId }, (err, user) => next(err, user));
  909. },
  910. (user, next) => {
  911. if (!user.services.github) return next("You don't have GitHub linked to your account.");
  912. return axios
  913. .get(`https://api.github.com/user/emails`, {
  914. headers: {
  915. "User-Agent": "request",
  916. Authorization: `token ${user.services.github.access_token}`
  917. }
  918. })
  919. .then(res => next(null, res))
  920. .catch(err => next(err));
  921. },
  922. (res, next) => next(null, res.status === 200)
  923. ],
  924. async (err, linked) => {
  925. if (err) {
  926. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  927. this.log(
  928. "ERROR",
  929. "USER_CONFIRM_GITHUB_LINK",
  930. `Couldn't confirm github link for user "${session.userId}". "${err}"`
  931. );
  932. return cb({ status: "error", message: err });
  933. }
  934. this.log(
  935. "SUCCESS",
  936. "USER_CONFIRM_GITHUB_LINK",
  937. `GitHub is ${linked ? "linked" : "not linked"} for user "${session.userId}".`
  938. );
  939. return cb({
  940. status: "success",
  941. data: { linked },
  942. message: "Successfully checked if GitHub accounty was linked."
  943. });
  944. }
  945. );
  946. }),
  947. /**
  948. * Removes all sessions for a user
  949. *
  950. * @param {object} session - the session object automatically added by the websocket
  951. * @param {string} userId - the id of the user we are trying to delete the sessions of
  952. * @param {Function} cb - gets called with the result
  953. */
  954. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  955. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  956. async.waterfall(
  957. [
  958. next => {
  959. userModel.findOne({ _id: session.userId }, (err, user) => {
  960. if (err) return next(err);
  961. if (user.role !== "admin" && session.userId !== userId)
  962. return next("Only admins and the owner of the account can remove their sessions.");
  963. return next();
  964. });
  965. },
  966. next => {
  967. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  968. .then(sessions => {
  969. next(null, sessions);
  970. })
  971. .catch(next);
  972. },
  973. (sessions, next) => {
  974. if (!sessions) return next("There are no sessions for this user to remove.");
  975. const keys = Object.keys(sessions);
  976. return next(null, keys, sessions);
  977. },
  978. (keys, sessions, next) => {
  979. CacheModule.runJob("PUB", {
  980. channel: "user.removeSessions",
  981. value: userId
  982. });
  983. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  984. setTimeout(
  985. () =>
  986. async.each(
  987. keys,
  988. (sessionId, callback) => {
  989. const session = sessions[sessionId];
  990. if (session.userId === userId) {
  991. // TODO Also maybe add this to this runJob
  992. CacheModule.runJob("HDEL", {
  993. table: "sessions",
  994. key: sessionId
  995. })
  996. .then(() => callback(null))
  997. .catch(callback);
  998. }
  999. },
  1000. err => {
  1001. next(err);
  1002. }
  1003. ),
  1004. 50
  1005. );
  1006. }
  1007. ],
  1008. async err => {
  1009. if (err) {
  1010. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1011. this.log(
  1012. "ERROR",
  1013. "REMOVE_SESSIONS_FOR_USER",
  1014. `Couldn't remove all sessions for user "${userId}". "${err}"`
  1015. );
  1016. return cb({ status: "error", message: err });
  1017. }
  1018. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  1019. return cb({
  1020. status: "success",
  1021. message: "Successfully removed all sessions."
  1022. });
  1023. }
  1024. );
  1025. }),
  1026. /**
  1027. * Updates the order of a user's favorite stations
  1028. *
  1029. * @param {object} session - the session object automatically added by the websocket
  1030. * @param {Array} favoriteStations - array of station ids (with a specific order)
  1031. * @param {Function} cb - gets called with the result
  1032. */
  1033. updateOrderOfFavoriteStations: isLoginRequired(async function updateOrderOfFavoriteStations(
  1034. session,
  1035. favoriteStations,
  1036. cb
  1037. ) {
  1038. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1039. async.waterfall(
  1040. [
  1041. next => {
  1042. userModel.updateOne(
  1043. { _id: session.userId },
  1044. { $set: { favoriteStations } },
  1045. { runValidators: true },
  1046. next
  1047. );
  1048. }
  1049. ],
  1050. async err => {
  1051. if (err) {
  1052. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1053. this.log(
  1054. "ERROR",
  1055. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  1056. `Couldn't update order of favorite stations for user "${session.userId}" to "${favoriteStations}". "${err}"`
  1057. );
  1058. return cb({ status: "error", message: err });
  1059. }
  1060. CacheModule.runJob("PUB", {
  1061. channel: "user.updateOrderOfFavoriteStations",
  1062. value: {
  1063. favoriteStations,
  1064. userId: session.userId
  1065. }
  1066. });
  1067. this.log(
  1068. "SUCCESS",
  1069. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  1070. `Updated order of favorite stations for user "${session.userId}" to "${favoriteStations}".`
  1071. );
  1072. return cb({
  1073. status: "success",
  1074. message: "Order of favorite stations successfully updated"
  1075. });
  1076. }
  1077. );
  1078. }),
  1079. /**
  1080. * Updates the order of a user's playlists
  1081. *
  1082. * @param {object} session - the session object automatically added by the websocket
  1083. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  1084. * @param {Function} cb - gets called with the result
  1085. */
  1086. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  1087. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1088. async.waterfall(
  1089. [
  1090. next => {
  1091. userModel.updateOne(
  1092. { _id: session.userId },
  1093. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  1094. { runValidators: true },
  1095. next
  1096. );
  1097. }
  1098. ],
  1099. async err => {
  1100. if (err) {
  1101. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1102. this.log(
  1103. "ERROR",
  1104. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1105. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  1106. );
  1107. return cb({ status: "error", message: err });
  1108. }
  1109. CacheModule.runJob("PUB", {
  1110. channel: "user.updateOrderOfPlaylists",
  1111. value: {
  1112. orderOfPlaylists,
  1113. userId: session.userId
  1114. }
  1115. });
  1116. this.log(
  1117. "SUCCESS",
  1118. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1119. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  1120. );
  1121. return cb({
  1122. status: "success",
  1123. message: "Order of playlists successfully updated"
  1124. });
  1125. }
  1126. );
  1127. }),
  1128. /**
  1129. * Updates a user's preferences
  1130. *
  1131. * @param {object} session - the session object automatically added by the websocket
  1132. * @param {object} preferences - object containing preferences
  1133. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  1134. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  1135. * @param {boolean} preferences.activityLogPublic - whether or not a user's activity log can be publicly viewed
  1136. * @param {boolean} preferences.anonymousSongRequests - whether or not a user's requested songs will be anonymous
  1137. * @param {boolean} preferences.activityWatch - whether or not a user is using the ActivityWatch integration
  1138. * @param {Function} cb - gets called with the result
  1139. */
  1140. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  1141. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1142. async.waterfall(
  1143. [
  1144. next => {
  1145. const $set = {};
  1146. Object.keys(preferences).forEach(preference => {
  1147. $set[`preferences.${preference}`] = preferences[preference];
  1148. });
  1149. return next(null, $set);
  1150. },
  1151. ($set, next) => {
  1152. userModel.findByIdAndUpdate(session.userId, { $set }, { new: false, upsert: true }, next);
  1153. }
  1154. ],
  1155. async (err, user) => {
  1156. if (err) {
  1157. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1158. this.log(
  1159. "ERROR",
  1160. "UPDATE_USER_PREFERENCES",
  1161. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  1162. preferences
  1163. )}". "${err}"`
  1164. );
  1165. return cb({ status: "error", message: err });
  1166. }
  1167. CacheModule.runJob("PUB", {
  1168. channel: "user.updatePreferences",
  1169. value: {
  1170. preferences,
  1171. userId: session.userId
  1172. }
  1173. });
  1174. if (preferences.nightmode !== undefined && preferences.nightmode !== user.preferences.nightmode)
  1175. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1176. userId: session.userId,
  1177. type: "user__toggle_nightmode",
  1178. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  1179. });
  1180. if (
  1181. preferences.autoSkipDisliked !== undefined &&
  1182. preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked
  1183. )
  1184. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1185. userId: session.userId,
  1186. type: "user__toggle_autoskip_disliked_songs",
  1187. payload: {
  1188. message: preferences.autoSkipDisliked
  1189. ? "Enabled the autoskipping of disliked songs"
  1190. : "Disabled the autoskipping of disliked songs"
  1191. }
  1192. });
  1193. if (
  1194. preferences.activityWatch !== undefined &&
  1195. preferences.activityWatch !== user.preferences.activityWatch
  1196. )
  1197. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1198. userId: session.userId,
  1199. type: "user__toggle_activity_watch",
  1200. payload: {
  1201. message: preferences.activityWatch
  1202. ? "Enabled ActivityWatch integration"
  1203. : "Disabled ActivityWatch integration"
  1204. }
  1205. });
  1206. this.log(
  1207. "SUCCESS",
  1208. "UPDATE_USER_PREFERENCES",
  1209. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  1210. );
  1211. return cb({
  1212. status: "success",
  1213. message: "Preferences successfully updated"
  1214. });
  1215. }
  1216. );
  1217. }),
  1218. /**
  1219. * Retrieves a user's preferences
  1220. *
  1221. * @param {object} session - the session object automatically added by the websocket
  1222. * @param {Function} cb - gets called with the result
  1223. */
  1224. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  1225. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1226. async.waterfall(
  1227. [
  1228. next => {
  1229. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  1230. }
  1231. ],
  1232. async (err, { preferences }) => {
  1233. if (err) {
  1234. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1235. this.log(
  1236. "ERROR",
  1237. "GET_USER_PREFERENCES",
  1238. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  1239. );
  1240. return cb({ status: "error", message: err });
  1241. }
  1242. this.log(
  1243. "SUCCESS",
  1244. "GET_USER_PREFERENCES",
  1245. `Successfully obtained preferences for user "${session.userId}".`
  1246. );
  1247. return cb({
  1248. status: "success",
  1249. message: "Preferences successfully retrieved",
  1250. data: { preferences }
  1251. });
  1252. }
  1253. );
  1254. }),
  1255. /**
  1256. * Gets user object from username (only a few properties)
  1257. *
  1258. * @param {object} session - the session object automatically added by the websocket
  1259. * @param {string} username - the username of the user we are trying to find
  1260. * @param {Function} cb - gets called with the result
  1261. */
  1262. findByUsername: async function findByUsername(session, username, cb) {
  1263. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1264. async.waterfall(
  1265. [
  1266. next => {
  1267. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  1268. },
  1269. (account, next) => {
  1270. if (!account) return next("User not found.");
  1271. return next(null, account);
  1272. }
  1273. ],
  1274. async (err, account) => {
  1275. if (err && err !== true) {
  1276. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1277. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  1278. return cb({ status: "error", message: err });
  1279. }
  1280. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  1281. return cb({
  1282. status: "success",
  1283. data: {
  1284. _id: account._id,
  1285. name: account.name,
  1286. username: account.username,
  1287. location: account.location,
  1288. bio: account.bio,
  1289. role: account.role,
  1290. avatar: account.avatar,
  1291. createdAt: account.createdAt
  1292. }
  1293. });
  1294. }
  1295. );
  1296. },
  1297. /**
  1298. * Gets a username from an userId
  1299. *
  1300. * @param {object} session - the session object automatically added by the websocket
  1301. * @param {string} userId - the userId of the person we are trying to get the username from
  1302. * @param {Function} cb - gets called with the result
  1303. */
  1304. async getUsernameFromId(session, userId, cb) {
  1305. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1306. userModel
  1307. .findById(userId)
  1308. .then(user => {
  1309. if (user) {
  1310. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  1311. return cb({
  1312. status: "success",
  1313. data: { username: user.username }
  1314. });
  1315. }
  1316. this.log(
  1317. "ERROR",
  1318. "GET_USERNAME_FROM_ID",
  1319. `Getting the username from userId "${userId}" failed. User not found.`
  1320. );
  1321. return cb({
  1322. status: "error",
  1323. message: "Couldn't find the user."
  1324. });
  1325. })
  1326. .catch(async err => {
  1327. if (err && err !== true) {
  1328. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1329. this.log(
  1330. "ERROR",
  1331. "GET_USERNAME_FROM_ID",
  1332. `Getting the username from userId "${userId}" failed. "${err}"`
  1333. );
  1334. cb({ status: "error", message: err });
  1335. }
  1336. });
  1337. },
  1338. /**
  1339. * Gets a user from a userId
  1340. *
  1341. * @param {object} session - the session object automatically added by the websocket
  1342. * @param {string} userId - the userId of the person we are trying to get the username from
  1343. * @param {Function} cb - gets called with the result
  1344. */
  1345. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  1346. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1347. userModel
  1348. .findById(userId)
  1349. .then(user => {
  1350. if (user) {
  1351. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  1352. return cb({
  1353. status: "success",
  1354. data: {
  1355. _id: user._id,
  1356. username: user.username,
  1357. role: user.role,
  1358. liked: user.liked,
  1359. disliked: user.disliked,
  1360. songsRequested: user.statistics.songsRequested,
  1361. email: {
  1362. address: user.email.address,
  1363. verified: user.email.verified
  1364. },
  1365. hasPassword: !!user.services.password,
  1366. services: { github: user.services.github }
  1367. }
  1368. });
  1369. }
  1370. this.log(
  1371. "ERROR",
  1372. "GET_USER_FROM_ID",
  1373. `Getting the user from userId "${userId}" failed. User not found.`
  1374. );
  1375. return cb({
  1376. status: "error",
  1377. message: "Couldn't find the user."
  1378. });
  1379. })
  1380. .catch(async err => {
  1381. if (err && err !== true) {
  1382. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1383. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  1384. cb({ status: "error", message: err });
  1385. }
  1386. });
  1387. }),
  1388. /**
  1389. * Gets user info from session
  1390. *
  1391. * @param {object} session - the session object automatically added by the websocket
  1392. * @param {Function} cb - gets called with the result
  1393. */
  1394. findBySession: isLoginRequired(async function findBySession(session, cb) {
  1395. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1396. async.waterfall(
  1397. [
  1398. next => {
  1399. CacheModule.runJob(
  1400. "HGET",
  1401. {
  1402. table: "sessions",
  1403. key: session.sessionId
  1404. },
  1405. this
  1406. )
  1407. .then(session => next(null, session))
  1408. .catch(next);
  1409. },
  1410. (session, next) => {
  1411. if (!session) return next("Session not found.");
  1412. return next(null, session);
  1413. },
  1414. (session, next) => {
  1415. userModel.findOne({ _id: session.userId }, next);
  1416. },
  1417. (user, next) => {
  1418. if (!user) return next("User not found.");
  1419. return next(null, user);
  1420. }
  1421. ],
  1422. async (err, user) => {
  1423. if (err && err !== true) {
  1424. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1425. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  1426. return cb({ status: "error", message: err });
  1427. }
  1428. const sanitisedUser = {
  1429. email: {
  1430. address: user.email.address
  1431. },
  1432. avatar: user.avatar,
  1433. username: user.username,
  1434. name: user.name,
  1435. location: user.location,
  1436. bio: user.bio
  1437. };
  1438. if (user.services.password && user.services.password.password) sanitisedUser.password = true;
  1439. if (user.services.github && user.services.github.id) sanitisedUser.github = true;
  1440. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  1441. return cb({
  1442. status: "success",
  1443. data: { user: sanitisedUser }
  1444. });
  1445. }
  1446. );
  1447. }),
  1448. /**
  1449. * Updates a user's username
  1450. *
  1451. * @param {object} session - the session object automatically added by the websocket
  1452. * @param {string} updatingUserId - the updating user's id
  1453. * @param {string} newUsername - the new username
  1454. * @param {Function} cb - gets called with the result
  1455. */
  1456. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  1457. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1458. async.waterfall(
  1459. [
  1460. next => {
  1461. if (updatingUserId === session.userId) return next(null, true);
  1462. return userModel.findOne({ _id: session.userId }, next);
  1463. },
  1464. (user, next) => {
  1465. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1466. return userModel.findOne({ _id: updatingUserId }, next);
  1467. },
  1468. (user, next) => {
  1469. if (!user) return next("User not found.");
  1470. if (user.username === newUsername)
  1471. return next("New username can't be the same as the old username.");
  1472. return next(null);
  1473. },
  1474. next => {
  1475. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1476. },
  1477. (user, next) => {
  1478. if (!user) return next();
  1479. if (user._id === updatingUserId) return next();
  1480. return next("That username is already in use.");
  1481. },
  1482. next => {
  1483. userModel.updateOne(
  1484. { _id: updatingUserId },
  1485. { $set: { username: newUsername } },
  1486. { runValidators: true },
  1487. next
  1488. );
  1489. }
  1490. ],
  1491. async err => {
  1492. if (err && err !== true) {
  1493. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1494. this.log(
  1495. "ERROR",
  1496. "UPDATE_USERNAME",
  1497. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1498. );
  1499. return cb({ status: "error", message: err });
  1500. }
  1501. CacheModule.runJob("PUB", {
  1502. channel: "user.updateUsername",
  1503. value: {
  1504. username: newUsername,
  1505. _id: updatingUserId
  1506. }
  1507. });
  1508. CacheModule.runJob("PUB", {
  1509. channel: "user.updated",
  1510. value: { userId: updatingUserId }
  1511. });
  1512. this.log(
  1513. "SUCCESS",
  1514. "UPDATE_USERNAME",
  1515. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1516. );
  1517. return cb({
  1518. status: "success",
  1519. message: "Username updated successfully"
  1520. });
  1521. }
  1522. );
  1523. }),
  1524. /**
  1525. * Updates a user's email
  1526. *
  1527. * @param {object} session - the session object automatically added by the websocket
  1528. * @param {string} updatingUserId - the updating user's id
  1529. * @param {string} newEmail - the new email
  1530. * @param {Function} cb - gets called with the result
  1531. */
  1532. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1533. newEmail = newEmail.toLowerCase();
  1534. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1535. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1536. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1537. async.waterfall(
  1538. [
  1539. next => {
  1540. if (updatingUserId === session.userId) return next(null, true);
  1541. return userModel.findOne({ _id: session.userId }, next);
  1542. },
  1543. (user, next) => {
  1544. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1545. return userModel.findOne({ _id: updatingUserId }, next);
  1546. },
  1547. (user, next) => {
  1548. if (!user) return next("User not found.");
  1549. if (user.email.address === newEmail)
  1550. return next("New email can't be the same as your the old email.");
  1551. return next();
  1552. },
  1553. next => {
  1554. userModel.findOne({ "email.address": newEmail }, next);
  1555. },
  1556. (user, next) => {
  1557. if (!user) return next();
  1558. if (user._id === updatingUserId) return next();
  1559. return next("That email is already in use.");
  1560. },
  1561. // regenerate the url for gravatar avatar
  1562. next => {
  1563. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1564. next(null, url);
  1565. });
  1566. },
  1567. (newAvatarUrl, next) => {
  1568. userModel.updateOne(
  1569. { _id: updatingUserId },
  1570. {
  1571. $set: {
  1572. "avatar.url": newAvatarUrl,
  1573. "email.address": newEmail,
  1574. "email.verified": false,
  1575. "email.verificationToken": verificationToken
  1576. }
  1577. },
  1578. { runValidators: true },
  1579. next
  1580. );
  1581. },
  1582. (res, next) => {
  1583. userModel.findOne({ _id: updatingUserId }, next);
  1584. },
  1585. (user, next) => {
  1586. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1587. next(err);
  1588. });
  1589. }
  1590. ],
  1591. async err => {
  1592. if (err && err !== true) {
  1593. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1594. this.log(
  1595. "ERROR",
  1596. "UPDATE_EMAIL",
  1597. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1598. );
  1599. return cb({ status: "error", message: err });
  1600. }
  1601. this.log(
  1602. "SUCCESS",
  1603. "UPDATE_EMAIL",
  1604. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1605. );
  1606. CacheModule.runJob("PUB", {
  1607. channel: "user.updated",
  1608. value: { userId: updatingUserId }
  1609. });
  1610. return cb({
  1611. status: "success",
  1612. message: "Email updated successfully."
  1613. });
  1614. }
  1615. );
  1616. }),
  1617. /**
  1618. * Updates a user's name
  1619. *
  1620. * @param {object} session - the session object automatically added by the websocket
  1621. * @param {string} updatingUserId - the updating user's id
  1622. * @param {string} newBio - the new name
  1623. * @param {Function} cb - gets called with the result
  1624. */
  1625. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1626. const userModel = await DBModule.runJob(
  1627. "GET_MODEL",
  1628. {
  1629. modelName: "user"
  1630. },
  1631. this
  1632. );
  1633. async.waterfall(
  1634. [
  1635. next => {
  1636. if (updatingUserId === session.userId) return next(null, true);
  1637. return userModel.findOne({ _id: session.userId }, next);
  1638. },
  1639. (user, next) => {
  1640. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1641. return userModel.findOne({ _id: updatingUserId }, next);
  1642. },
  1643. (user, next) => {
  1644. if (!user) return next("User not found.");
  1645. return userModel.updateOne(
  1646. { _id: updatingUserId },
  1647. { $set: { name: newName } },
  1648. { runValidators: true },
  1649. next
  1650. );
  1651. }
  1652. ],
  1653. async err => {
  1654. if (err && err !== true) {
  1655. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1656. this.log(
  1657. "ERROR",
  1658. "UPDATE_NAME",
  1659. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1660. );
  1661. return cb({ status: "error", message: err });
  1662. }
  1663. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1664. userId: updatingUserId,
  1665. type: "user__edit_name",
  1666. payload: { message: `Changed name to ${newName}` }
  1667. });
  1668. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1669. CacheModule.runJob("PUB", {
  1670. channel: "user.updated",
  1671. value: { userId: updatingUserId }
  1672. });
  1673. return cb({
  1674. status: "success",
  1675. message: "Name updated successfully"
  1676. });
  1677. }
  1678. );
  1679. }),
  1680. /**
  1681. * Updates a user's location
  1682. *
  1683. * @param {object} session - the session object automatically added by the websocket
  1684. * @param {string} updatingUserId - the updating user's id
  1685. * @param {string} newLocation - the new location
  1686. * @param {Function} cb - gets called with the result
  1687. */
  1688. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1689. const userModel = await DBModule.runJob(
  1690. "GET_MODEL",
  1691. {
  1692. modelName: "user"
  1693. },
  1694. this
  1695. );
  1696. async.waterfall(
  1697. [
  1698. next => {
  1699. if (updatingUserId === session.userId) return next(null, true);
  1700. return userModel.findOne({ _id: session.userId }, next);
  1701. },
  1702. (user, next) => {
  1703. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1704. return userModel.findOne({ _id: updatingUserId }, next);
  1705. },
  1706. (user, next) => {
  1707. if (!user) return next("User not found.");
  1708. return userModel.updateOne(
  1709. { _id: updatingUserId },
  1710. { $set: { location: newLocation } },
  1711. { runValidators: true },
  1712. next
  1713. );
  1714. }
  1715. ],
  1716. async err => {
  1717. if (err && err !== true) {
  1718. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1719. this.log(
  1720. "ERROR",
  1721. "UPDATE_LOCATION",
  1722. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1723. );
  1724. return cb({ status: "error", message: err });
  1725. }
  1726. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1727. userId: updatingUserId,
  1728. type: "user__edit_location",
  1729. payload: { message: `Changed location to ${newLocation}` }
  1730. });
  1731. this.log(
  1732. "SUCCESS",
  1733. "UPDATE_LOCATION",
  1734. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1735. );
  1736. CacheModule.runJob("PUB", {
  1737. channel: "user.updated",
  1738. value: { userId: updatingUserId }
  1739. });
  1740. return cb({
  1741. status: "success",
  1742. message: "Location updated successfully"
  1743. });
  1744. }
  1745. );
  1746. }),
  1747. /**
  1748. * Updates a user's bio
  1749. *
  1750. * @param {object} session - the session object automatically added by the websocket
  1751. * @param {string} updatingUserId - the updating user's id
  1752. * @param {string} newBio - the new bio
  1753. * @param {Function} cb - gets called with the result
  1754. */
  1755. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1756. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1757. async.waterfall(
  1758. [
  1759. next => {
  1760. if (updatingUserId === session.userId) return next(null, true);
  1761. return userModel.findOne({ _id: session.userId }, next);
  1762. },
  1763. (user, next) => {
  1764. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1765. return userModel.findOne({ _id: updatingUserId }, next);
  1766. },
  1767. (user, next) => {
  1768. if (!user) return next("User not found.");
  1769. return userModel.updateOne(
  1770. { _id: updatingUserId },
  1771. { $set: { bio: newBio } },
  1772. { runValidators: true },
  1773. next
  1774. );
  1775. }
  1776. ],
  1777. async err => {
  1778. if (err && err !== true) {
  1779. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1780. this.log(
  1781. "ERROR",
  1782. "UPDATE_BIO",
  1783. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1784. );
  1785. return cb({ status: "error", message: err });
  1786. }
  1787. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1788. userId: updatingUserId,
  1789. type: "user__edit_bio",
  1790. payload: { message: `Changed bio to ${newBio}` }
  1791. });
  1792. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1793. CacheModule.runJob("PUB", {
  1794. channel: "user.updated",
  1795. value: { userId: updatingUserId }
  1796. });
  1797. return cb({
  1798. status: "success",
  1799. message: "Bio updated successfully"
  1800. });
  1801. }
  1802. );
  1803. }),
  1804. /**
  1805. * Updates a user's avatar
  1806. *
  1807. * @param {object} session - the session object automatically added by the websocket
  1808. * @param {string} updatingUserId - the updating user's id
  1809. * @param {string} newAvatar - the new avatar object
  1810. * @param {Function} cb - gets called with the result
  1811. */
  1812. updateAvatar: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1813. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1814. async.waterfall(
  1815. [
  1816. next => {
  1817. if (updatingUserId === session.userId) return next(null, true);
  1818. return userModel.findOne({ _id: session.userId }, next);
  1819. },
  1820. (user, next) => {
  1821. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1822. return userModel.findOne({ _id: updatingUserId }, next);
  1823. },
  1824. (user, next) => {
  1825. if (!user) return next("User not found.");
  1826. return userModel.findOneAndUpdate(
  1827. { _id: updatingUserId },
  1828. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1829. { new: true, runValidators: true },
  1830. next
  1831. );
  1832. }
  1833. ],
  1834. async err => {
  1835. if (err && err !== true) {
  1836. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1837. this.log(
  1838. "ERROR",
  1839. "UPDATE_AVATAR",
  1840. `Couldn't update avatar for user "${updatingUserId}" to type "${newAvatar.type}" and color "${newAvatar.color}". "${err}"`
  1841. );
  1842. return cb({ status: "error", message: err });
  1843. }
  1844. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1845. userId: updatingUserId,
  1846. type: "user__edit_avatar",
  1847. payload: { message: `Changed avatar to use ${newAvatar.type} and ${newAvatar.color}` }
  1848. });
  1849. this.log(
  1850. "SUCCESS",
  1851. "UPDATE_AVATAR",
  1852. `Updated avatar for user "${updatingUserId}" to type "${newAvatar.type} and color ${newAvatar.color}".`
  1853. );
  1854. CacheModule.runJob("PUB", {
  1855. channel: "user.updated",
  1856. value: { userId: updatingUserId }
  1857. });
  1858. return cb({
  1859. status: "success",
  1860. message: "Avatar updated successfully"
  1861. });
  1862. }
  1863. );
  1864. }),
  1865. /**
  1866. * Updates a user's role
  1867. *
  1868. * @param {object} session - the session object automatically added by the websocket
  1869. * @param {string} updatingUserId - the updating user's id
  1870. * @param {string} newRole - the new role
  1871. * @param {Function} cb - gets called with the result
  1872. */
  1873. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1874. newRole = newRole.toLowerCase();
  1875. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1876. async.waterfall(
  1877. [
  1878. next => {
  1879. userModel.findOne({ _id: updatingUserId }, next);
  1880. },
  1881. (user, next) => {
  1882. if (!user) return next("User not found.");
  1883. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1884. return next();
  1885. },
  1886. next => {
  1887. userModel.updateOne(
  1888. { _id: updatingUserId },
  1889. { $set: { role: newRole } },
  1890. { runValidators: true },
  1891. next
  1892. );
  1893. }
  1894. ],
  1895. async err => {
  1896. if (err && err !== true) {
  1897. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1898. this.log(
  1899. "ERROR",
  1900. "UPDATE_ROLE",
  1901. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1902. );
  1903. return cb({ status: "error", message: err });
  1904. }
  1905. this.log(
  1906. "SUCCESS",
  1907. "UPDATE_ROLE",
  1908. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1909. );
  1910. CacheModule.runJob("PUB", {
  1911. channel: "user.updated",
  1912. value: { userId: updatingUserId }
  1913. });
  1914. return cb({
  1915. status: "success",
  1916. message: "Role successfully updated."
  1917. });
  1918. }
  1919. );
  1920. }),
  1921. /**
  1922. * Updates a user's password
  1923. *
  1924. * @param {object} session - the session object automatically added by the websocket
  1925. * @param {string} previousPassword - the previous password
  1926. * @param {string} newPassword - the new password
  1927. * @param {Function} cb - gets called with the result
  1928. */
  1929. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1930. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1931. async.waterfall(
  1932. [
  1933. next => {
  1934. userModel.findOne({ _id: session.userId }, next);
  1935. },
  1936. (user, next) => {
  1937. if (!user.services.password) return next("This account does not have a password set.");
  1938. return next(null, user.services.password.password);
  1939. },
  1940. (storedPassword, next) => {
  1941. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1942. if (res) return next();
  1943. return next("Please enter the correct previous password.");
  1944. });
  1945. },
  1946. next => {
  1947. if (!DBModule.passwordValid(newPassword))
  1948. return next("Invalid new password. Check if it meets all the requirements.");
  1949. return next();
  1950. },
  1951. next => {
  1952. bcrypt.genSalt(10, next);
  1953. },
  1954. // hash the password
  1955. (salt, next) => {
  1956. bcrypt.hash(sha256(newPassword), salt, next);
  1957. },
  1958. (hashedPassword, next) => {
  1959. userModel.updateOne(
  1960. { _id: session.userId },
  1961. {
  1962. $set: {
  1963. "services.password.password": hashedPassword
  1964. }
  1965. },
  1966. next
  1967. );
  1968. }
  1969. ],
  1970. async err => {
  1971. if (err) {
  1972. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1973. this.log(
  1974. "ERROR",
  1975. "UPDATE_PASSWORD",
  1976. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1977. );
  1978. return cb({ status: "error", message: err });
  1979. }
  1980. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1981. return cb({
  1982. status: "success",
  1983. message: "Password successfully updated."
  1984. });
  1985. }
  1986. );
  1987. }),
  1988. /**
  1989. * Requests a password for a session
  1990. *
  1991. * @param {object} session - the session object automatically added by the websocket
  1992. * @param {string} email - the email of the user that requests a password reset
  1993. * @param {Function} cb - gets called with the result
  1994. */
  1995. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1996. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1997. const passwordRequestSchema = await MailModule.runJob(
  1998. "GET_SCHEMA",
  1999. {
  2000. schemaName: "passwordRequest"
  2001. },
  2002. this
  2003. );
  2004. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2005. async.waterfall(
  2006. [
  2007. next => {
  2008. userModel.findOne({ _id: session.userId }, next);
  2009. },
  2010. (user, next) => {
  2011. if (!user) return next("User not found.");
  2012. if (user.services.password && user.services.password.password)
  2013. return next("You already have a password set.");
  2014. return next(null, user);
  2015. },
  2016. (user, next) => {
  2017. const expires = new Date();
  2018. expires.setDate(expires.getDate() + 1);
  2019. userModel.findOneAndUpdate(
  2020. { "email.address": user.email.address },
  2021. {
  2022. $set: {
  2023. "services.password": {
  2024. set: { code, expires }
  2025. }
  2026. }
  2027. },
  2028. { runValidators: true },
  2029. next
  2030. );
  2031. },
  2032. (user, next) => {
  2033. passwordRequestSchema(user.email.address, user.username, code, next);
  2034. }
  2035. ],
  2036. async err => {
  2037. if (err && err !== true) {
  2038. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2039. this.log(
  2040. "ERROR",
  2041. "REQUEST_PASSWORD",
  2042. `UserId '${session.userId}' failed to request password. '${err}'`
  2043. );
  2044. return cb({ status: "error", message: err });
  2045. }
  2046. this.log(
  2047. "SUCCESS",
  2048. "REQUEST_PASSWORD",
  2049. `UserId '${session.userId}' successfully requested a password.`
  2050. );
  2051. return cb({
  2052. status: "success",
  2053. message: "Successfully requested password."
  2054. });
  2055. }
  2056. );
  2057. }),
  2058. /**
  2059. * Verifies a password code
  2060. *
  2061. * @param {object} session - the session object automatically added by the websocket
  2062. * @param {string} code - the password code
  2063. * @param {Function} cb - gets called with the result
  2064. */
  2065. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  2066. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2067. async.waterfall(
  2068. [
  2069. next => {
  2070. if (!code || typeof code !== "string") return next("Invalid code.");
  2071. return userModel.findOne(
  2072. {
  2073. "services.password.set.code": code,
  2074. _id: session.userId
  2075. },
  2076. next
  2077. );
  2078. },
  2079. (user, next) => {
  2080. if (!user) return next("Invalid code.");
  2081. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  2082. return next(null);
  2083. }
  2084. ],
  2085. async err => {
  2086. if (err && err !== true) {
  2087. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2088. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  2089. cb({ status: "error", message: err });
  2090. } else {
  2091. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  2092. cb({
  2093. status: "success",
  2094. message: "Successfully verified password code."
  2095. });
  2096. }
  2097. }
  2098. );
  2099. }),
  2100. /**
  2101. * Adds a password to a user with a code
  2102. *
  2103. * @param {object} session - the session object automatically added by the websocket
  2104. * @param {string} code - the password code
  2105. * @param {string} newPassword - the new password code
  2106. * @param {Function} cb - gets called with the result
  2107. */
  2108. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  2109. const userModel = await DBModule.runJob(
  2110. "GET_MODEL",
  2111. {
  2112. modelName: "user"
  2113. },
  2114. this
  2115. );
  2116. async.waterfall(
  2117. [
  2118. next => {
  2119. if (!code || typeof code !== "string") return next("Invalid code.");
  2120. return userModel.findOne({ "services.password.set.code": code }, next);
  2121. },
  2122. (user, next) => {
  2123. if (!user) return next("Invalid code.");
  2124. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  2125. return next();
  2126. },
  2127. next => {
  2128. if (!DBModule.passwordValid(newPassword))
  2129. return next("Invalid password. Check if it meets all the requirements.");
  2130. return next();
  2131. },
  2132. next => {
  2133. bcrypt.genSalt(10, next);
  2134. },
  2135. // hash the password
  2136. (salt, next) => {
  2137. bcrypt.hash(sha256(newPassword), salt, next);
  2138. },
  2139. (hashedPassword, next) => {
  2140. userModel.updateOne(
  2141. { "services.password.set.code": code },
  2142. {
  2143. $set: {
  2144. "services.password.password": hashedPassword
  2145. },
  2146. $unset: { "services.password.set": "" }
  2147. },
  2148. { runValidators: true },
  2149. next
  2150. );
  2151. }
  2152. ],
  2153. async err => {
  2154. if (err && err !== true) {
  2155. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2156. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  2157. return cb({ status: "error", message: err });
  2158. }
  2159. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  2160. CacheModule.runJob("PUB", {
  2161. channel: "user.linkPassword",
  2162. value: session.userId
  2163. });
  2164. CacheModule.runJob("PUB", {
  2165. channel: "user.updated",
  2166. value: { userId: session.userId }
  2167. });
  2168. return cb({
  2169. status: "success",
  2170. message: "Successfully added password."
  2171. });
  2172. }
  2173. );
  2174. }),
  2175. /**
  2176. * Unlinks password from user
  2177. *
  2178. * @param {object} session - the session object automatically added by the websocket
  2179. * @param {Function} cb - gets called with the result
  2180. */
  2181. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  2182. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2183. async.waterfall(
  2184. [
  2185. next => {
  2186. userModel.findOne({ _id: session.userId }, next);
  2187. },
  2188. (user, next) => {
  2189. if (!user) return next("Not logged in.");
  2190. if (!user.services.github || !user.services.github.id)
  2191. return next("You can't remove password login without having GitHub login.");
  2192. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  2193. }
  2194. ],
  2195. async err => {
  2196. if (err && err !== true) {
  2197. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2198. this.log(
  2199. "ERROR",
  2200. "UNLINK_PASSWORD",
  2201. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  2202. );
  2203. return cb({ status: "error", message: err });
  2204. }
  2205. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  2206. CacheModule.runJob("PUB", {
  2207. channel: "user.unlinkPassword",
  2208. value: session.userId
  2209. });
  2210. CacheModule.runJob("PUB", {
  2211. channel: "user.updated",
  2212. value: { userId: session.userId }
  2213. });
  2214. return cb({
  2215. status: "success",
  2216. message: "Successfully unlinked password."
  2217. });
  2218. }
  2219. );
  2220. }),
  2221. /**
  2222. * Unlinks GitHub from user
  2223. *
  2224. * @param {object} session - the session object automatically added by the websocket
  2225. * @param {Function} cb - gets called with the result
  2226. */
  2227. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  2228. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2229. async.waterfall(
  2230. [
  2231. next => {
  2232. userModel.findOne({ _id: session.userId }, next);
  2233. },
  2234. (user, next) => {
  2235. if (!user) return next("Not logged in.");
  2236. if (!user.services.password || !user.services.password.password)
  2237. return next("You can't remove GitHub login without having password login.");
  2238. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  2239. }
  2240. ],
  2241. async err => {
  2242. if (err && err !== true) {
  2243. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2244. this.log(
  2245. "ERROR",
  2246. "UNLINK_GITHUB",
  2247. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  2248. );
  2249. return cb({ status: "error", message: err });
  2250. }
  2251. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  2252. CacheModule.runJob("PUB", {
  2253. channel: "user.unlinkGithub",
  2254. value: session.userId
  2255. });
  2256. CacheModule.runJob("PUB", {
  2257. channel: "user.updated",
  2258. value: { userId: session.userId }
  2259. });
  2260. return cb({
  2261. status: "success",
  2262. message: "Successfully unlinked GitHub."
  2263. });
  2264. }
  2265. );
  2266. }),
  2267. /**
  2268. * Requests a password reset for an email
  2269. *
  2270. * @param {object} session - the session object automatically added by the websocket
  2271. * @param {string} email - the email of the user that requests a password reset
  2272. * @param {Function} cb - gets called with the result
  2273. */
  2274. async requestPasswordReset(session, email, cb) {
  2275. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2276. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2277. const resetPasswordRequestSchema = await MailModule.runJob(
  2278. "GET_SCHEMA",
  2279. { schemaName: "resetPasswordRequest" },
  2280. this
  2281. );
  2282. async.waterfall(
  2283. [
  2284. next => {
  2285. if (!email || typeof email !== "string") return next("Invalid email.");
  2286. email = email.toLowerCase();
  2287. return userModel.findOne({ "email.address": email }, next);
  2288. },
  2289. (user, next) => {
  2290. if (!user) return next("User not found.");
  2291. if (!user.services.password || !user.services.password.password)
  2292. return next("User does not have a password set, and probably uses GitHub to log in.");
  2293. return next(null, user);
  2294. },
  2295. (user, next) => {
  2296. const expires = new Date();
  2297. expires.setDate(expires.getDate() + 1);
  2298. userModel.findOneAndUpdate(
  2299. { "email.address": email },
  2300. {
  2301. $set: {
  2302. "services.password.reset": {
  2303. code,
  2304. expires
  2305. }
  2306. }
  2307. },
  2308. { runValidators: true },
  2309. next
  2310. );
  2311. },
  2312. (user, next) => {
  2313. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2314. }
  2315. ],
  2316. async err => {
  2317. if (err && err !== true) {
  2318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2319. this.log(
  2320. "ERROR",
  2321. "REQUEST_PASSWORD_RESET",
  2322. `Email '${email}' failed to request password reset. '${err}'`
  2323. );
  2324. return cb({ status: "error", message: err });
  2325. }
  2326. this.log(
  2327. "SUCCESS",
  2328. "REQUEST_PASSWORD_RESET",
  2329. `Email '${email}' successfully requested a password reset.`
  2330. );
  2331. return cb({
  2332. status: "success",
  2333. message: "Successfully requested password reset."
  2334. });
  2335. }
  2336. );
  2337. },
  2338. /**
  2339. * Requests a password reset for a a user as an admin
  2340. *
  2341. * @param {object} session - the session object automatically added by the websocket
  2342. * @param {string} email - the email of the user for which the password reset is intended
  2343. * @param {Function} cb - gets called with the result
  2344. */
  2345. adminRequestPasswordReset: isAdminRequired(async function adminRequestPasswordReset(session, userId, cb) {
  2346. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2347. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2348. const resetPasswordRequestSchema = await MailModule.runJob(
  2349. "GET_SCHEMA",
  2350. { schemaName: "resetPasswordRequest" },
  2351. this
  2352. );
  2353. async.waterfall(
  2354. [
  2355. next => userModel.findOne({ _id: userId }, next),
  2356. (user, next) => {
  2357. if (!user) return next("User not found.");
  2358. if (!user.services.password || !user.services.password.password)
  2359. return next("User does not have a password set, and probably uses GitHub to log in.");
  2360. return next();
  2361. },
  2362. next => {
  2363. const expires = new Date();
  2364. expires.setDate(expires.getDate() + 1);
  2365. userModel.findOneAndUpdate(
  2366. { _id: userId },
  2367. {
  2368. $set: {
  2369. "services.password.reset": {
  2370. code,
  2371. expires
  2372. }
  2373. }
  2374. },
  2375. { runValidators: true },
  2376. next
  2377. );
  2378. },
  2379. (user, next) => {
  2380. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2381. }
  2382. ],
  2383. async err => {
  2384. if (err && err !== true) {
  2385. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2386. this.log(
  2387. "ERROR",
  2388. "ADMINREQUEST_PASSWORD_RESET",
  2389. `User '${userId}' failed to get a password reset. '${err}'`
  2390. );
  2391. return cb({ status: "error", message: err });
  2392. }
  2393. this.log(
  2394. "SUCCESS",
  2395. "ADMIN_REQUEST_PASSWORD_RESET",
  2396. `User '${userId}' successfully got sent a password reset.`
  2397. );
  2398. return cb({
  2399. status: "success",
  2400. message: "Successfully requested password reset for user."
  2401. });
  2402. }
  2403. );
  2404. }),
  2405. /**
  2406. * Verifies a reset code
  2407. *
  2408. * @param {object} session - the session object automatically added by the websocket
  2409. * @param {string} code - the password reset code
  2410. * @param {Function} cb - gets called with the result
  2411. */
  2412. async verifyPasswordResetCode(session, code, cb) {
  2413. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2414. async.waterfall(
  2415. [
  2416. next => {
  2417. if (!code || typeof code !== "string") return next("Invalid code.");
  2418. return userModel.findOne({ "services.password.reset.code": code }, next);
  2419. },
  2420. (user, next) => {
  2421. if (!user) return next("Invalid code.");
  2422. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2423. return next(null);
  2424. }
  2425. ],
  2426. async err => {
  2427. if (err && err !== true) {
  2428. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2429. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  2430. return cb({ status: "error", message: err });
  2431. }
  2432. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  2433. return cb({
  2434. status: "success",
  2435. message: "Successfully verified password reset code."
  2436. });
  2437. }
  2438. );
  2439. },
  2440. /**
  2441. * Changes a user's password with a reset code
  2442. *
  2443. * @param {object} session - the session object automatically added by the websocket
  2444. * @param {string} code - the password reset code
  2445. * @param {string} newPassword - the new password reset code
  2446. * @param {Function} cb - gets called with the result
  2447. */
  2448. async changePasswordWithResetCode(session, code, newPassword, cb) {
  2449. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2450. async.waterfall(
  2451. [
  2452. next => {
  2453. if (!code || typeof code !== "string") return next("Invalid code.");
  2454. return userModel.findOne({ "services.password.reset.code": code }, next);
  2455. },
  2456. (user, next) => {
  2457. if (!user) return next("Invalid code.");
  2458. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2459. return next();
  2460. },
  2461. next => {
  2462. if (!DBModule.passwordValid(newPassword))
  2463. return next("Invalid password. Check if it meets all the requirements.");
  2464. return next();
  2465. },
  2466. next => {
  2467. bcrypt.genSalt(10, next);
  2468. },
  2469. // hash the password
  2470. (salt, next) => {
  2471. bcrypt.hash(sha256(newPassword), salt, next);
  2472. },
  2473. (hashedPassword, next) => {
  2474. userModel.updateOne(
  2475. { "services.password.reset.code": code },
  2476. {
  2477. $set: {
  2478. "services.password.password": hashedPassword
  2479. },
  2480. $unset: { "services.password.reset": "" }
  2481. },
  2482. { runValidators: true },
  2483. next
  2484. );
  2485. }
  2486. ],
  2487. async err => {
  2488. if (err && err !== true) {
  2489. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2490. this.log(
  2491. "ERROR",
  2492. "CHANGE_PASSWORD_WITH_RESET_CODE",
  2493. `Code '${code}' failed to change password. '${err}'`
  2494. );
  2495. return cb({ status: "error", message: err });
  2496. }
  2497. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  2498. return cb({
  2499. status: "success",
  2500. message: "Successfully changed password."
  2501. });
  2502. }
  2503. );
  2504. },
  2505. /**
  2506. * Resends the verify email email
  2507. *
  2508. * @param {object} session - the session object automatically added by the websocket
  2509. * @param {string} userId - the user id of the person to resend the email to
  2510. * @param {Function} cb - gets called with the result
  2511. */
  2512. resendVerifyEmail: isAdminRequired(async function resendVerifyEmail(session, userId, cb) {
  2513. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2514. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  2515. async.waterfall(
  2516. [
  2517. next => userModel.findOne({ _id: userId }, next),
  2518. (user, next) => {
  2519. if (!user) return next("User not found.");
  2520. if (user.email.verified) return next("The user's email is already verified.");
  2521. return next(null, user);
  2522. },
  2523. (user, next) => {
  2524. verifyEmailSchema(user.email.address, user.username, user.email.verificationToken, err => {
  2525. next(err);
  2526. });
  2527. }
  2528. ],
  2529. async err => {
  2530. if (err && err !== true) {
  2531. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2532. this.log(
  2533. "ERROR",
  2534. "RESEND_VERIFY_EMAIL",
  2535. `Couldn't resend verify email for user "${userId}". '${err}'`
  2536. );
  2537. return cb({ status: "error", message: err });
  2538. }
  2539. this.log("SUCCESS", "RESEND_VERIFY_EMAIL", `Resent verify email for user "${userId}".`);
  2540. return cb({
  2541. status: "success",
  2542. message: "Email resent successfully."
  2543. });
  2544. }
  2545. );
  2546. }),
  2547. /**
  2548. * Bans a user by userId
  2549. *
  2550. * @param {object} session - the session object automatically added by the websocket
  2551. * @param {string} value - the user id that is going to be banned
  2552. * @param {string} reason - the reason for the ban
  2553. * @param {string} expiresAt - the time the ban expires
  2554. * @param {Function} cb - gets called with the result
  2555. */
  2556. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  2557. async.waterfall(
  2558. [
  2559. next => {
  2560. if (!userId) return next("You must provide a userId to ban.");
  2561. if (!reason) return next("You must provide a reason for the ban.");
  2562. return next();
  2563. },
  2564. next => {
  2565. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  2566. const date = new Date();
  2567. switch (expiresAt) {
  2568. case "1h":
  2569. expiresAt = date.setHours(date.getHours() + 1);
  2570. break;
  2571. case "12h":
  2572. expiresAt = date.setHours(date.getHours() + 12);
  2573. break;
  2574. case "1d":
  2575. expiresAt = date.setDate(date.getDate() + 1);
  2576. break;
  2577. case "1w":
  2578. expiresAt = date.setDate(date.getDate() + 7);
  2579. break;
  2580. case "1m":
  2581. expiresAt = date.setMonth(date.getMonth() + 1);
  2582. break;
  2583. case "3m":
  2584. expiresAt = date.setMonth(date.getMonth() + 3);
  2585. break;
  2586. case "6m":
  2587. expiresAt = date.setMonth(date.getMonth() + 6);
  2588. break;
  2589. case "1y":
  2590. expiresAt = date.setFullYear(date.getFullYear() + 1);
  2591. break;
  2592. case "never":
  2593. expiresAt = new Date(3093527980800000);
  2594. break;
  2595. default:
  2596. return next("Invalid expire date.");
  2597. }
  2598. return next();
  2599. },
  2600. next => {
  2601. PunishmentsModule.runJob(
  2602. "ADD_PUNISHMENT",
  2603. {
  2604. type: "banUserId",
  2605. value: userId,
  2606. reason,
  2607. expiresAt,
  2608. punishedBy: session.userId
  2609. },
  2610. this
  2611. )
  2612. .then(punishment => next(null, punishment))
  2613. .catch(next);
  2614. },
  2615. (punishment, next) => {
  2616. CacheModule.runJob("PUB", {
  2617. channel: "user.ban",
  2618. value: { userId, punishment }
  2619. });
  2620. next();
  2621. }
  2622. ],
  2623. async err => {
  2624. if (err && err !== true) {
  2625. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2626. this.log(
  2627. "ERROR",
  2628. "BAN_USER_BY_ID",
  2629. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2630. );
  2631. return cb({ status: "error", message: err });
  2632. }
  2633. this.log(
  2634. "SUCCESS",
  2635. "BAN_USER_BY_ID",
  2636. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2637. );
  2638. return cb({
  2639. status: "success",
  2640. message: "Successfully banned user."
  2641. });
  2642. }
  2643. );
  2644. })
  2645. };