users.js 91 KB

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