users.js 81 KB

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