users.js 84 KB

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