users.js 86 KB

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