users.js 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427
  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, mediaSource: song.mediaSource })
  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({ mediaSource: song.mediaSource }));
  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 { mediaSource } = song;
  382. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource })
  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, mediaSource: song.mediaSource })
  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({ mediaSource: song.mediaSource }));
  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 { mediaSource } = song;
  575. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource })
  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().trim();
  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. if (
  773. config.has("experimental.registration_email_whitelist") &&
  774. config.get("experimental.registration_email_whitelist")
  775. ) {
  776. const experimentalRegistrationEmailWhitelist = config.get(
  777. "experimental.registration_email_whitelist"
  778. );
  779. if (!Array.isArray(experimentalRegistrationEmailWhitelist)) return next();
  780. let anyPassed = false;
  781. experimentalRegistrationEmailWhitelist.forEach(regex => {
  782. const newRegex = new RegExp(regex);
  783. if (newRegex.test(email)) anyPassed = true;
  784. });
  785. if (!anyPassed) next("Your email is not allowed to register.");
  786. }
  787. return next();
  788. },
  789. next => {
  790. if (!DBModule.passwordValid(password))
  791. return next("Invalid password. Check if it meets all the requirements.");
  792. return next();
  793. },
  794. // verify the request with google recaptcha
  795. next => {
  796. if (config.get("apis.recaptcha.enabled") === true)
  797. axios
  798. .post("https://www.google.com/recaptcha/api/siteverify", {
  799. data: {
  800. secret: config.get("apis").recaptcha.secret,
  801. response: recaptcha
  802. }
  803. })
  804. .then(res => next(null, res.data))
  805. .catch(err => next(err));
  806. else next(null, null);
  807. },
  808. // check if the response from Google recaptcha is successful
  809. // if it is, we check if a user with the requested username already exists
  810. (body, next) => {
  811. if (config.get("apis.recaptcha.enabled") === true)
  812. if (body.success !== true) return next("Response from recaptcha was not successful.");
  813. return userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  814. },
  815. // if the user already exists, respond with that
  816. // otherwise check if a user with the requested email already exists
  817. (user, next) => {
  818. if (user) return next("A user with that username already exists.");
  819. return userModel.findOne({ "email.address": email }, next);
  820. },
  821. // if the user already exists, respond with that
  822. // otherwise, generate a salt to use with hashing the new users password
  823. (user, next) => {
  824. if (user) return next("A user with that email already exists.");
  825. return bcrypt.genSalt(10, next);
  826. },
  827. // hash the password
  828. (salt, next) => {
  829. bcrypt.hash(sha256(password), salt, next);
  830. },
  831. (hash, next) => {
  832. UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 12 }, this).then(_id => {
  833. next(null, hash, _id);
  834. });
  835. },
  836. // create the user object
  837. (hash, _id, next) => {
  838. next(null, {
  839. _id,
  840. name: username,
  841. username,
  842. email: {
  843. address: email,
  844. verificationToken
  845. },
  846. services: {
  847. password: {
  848. password: hash
  849. }
  850. }
  851. });
  852. },
  853. // generate the url for gravatar avatar
  854. (user, next) => {
  855. UtilsModule.runJob("CREATE_GRAVATAR", { email: user.email.address }, this).then(url => {
  856. const avatarColors = ["blue", "orange", "green", "purple", "teal"];
  857. user.avatar = {
  858. type: "initials",
  859. color: avatarColors[Math.floor(Math.random() * avatarColors.length)],
  860. url
  861. };
  862. next(null, user);
  863. });
  864. },
  865. // save the new user to the database
  866. (user, next) => {
  867. userModel.create(user, next);
  868. },
  869. // respond with the new user
  870. (user, next) => {
  871. verifyEmailSchema(email, username, verificationToken, err => {
  872. next(err, user._id);
  873. });
  874. },
  875. // create a liked songs playlist for the new user
  876. (userId, next) => {
  877. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  878. userId,
  879. displayName: "Liked Songs",
  880. type: "user-liked"
  881. })
  882. .then(likedSongsPlaylist => {
  883. next(null, likedSongsPlaylist, userId);
  884. })
  885. .catch(err => next(err));
  886. },
  887. // create a disliked songs playlist for the new user
  888. (likedSongsPlaylist, userId, next) => {
  889. PlaylistsModule.runJob("CREATE_USER_PLAYLIST", {
  890. userId,
  891. displayName: "Disliked Songs",
  892. type: "user-disliked"
  893. })
  894. .then(dislikedSongsPlaylist => {
  895. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  896. })
  897. .catch(err => next(err));
  898. },
  899. // associate liked + disliked songs playlist to the user object
  900. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  901. userModel.updateOne(
  902. { _id: userId },
  903. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  904. { runValidators: true },
  905. err => {
  906. if (err) return next(err);
  907. return next(null, userId);
  908. }
  909. );
  910. }
  911. ],
  912. async (err, userId) => {
  913. if (err && err !== true) {
  914. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  915. this.log(
  916. "ERROR",
  917. "USER_PASSWORD_REGISTER",
  918. `Register failed with password for user "${username}"."${err}"`
  919. );
  920. return cb({ status: "error", message: err });
  921. }
  922. ActivitiesModule.runJob("ADD_ACTIVITY", {
  923. userId,
  924. type: "user__joined",
  925. payload: { message: "Welcome to Musare!" }
  926. });
  927. this.log(
  928. "SUCCESS",
  929. "USER_PASSWORD_REGISTER",
  930. `Register successful with password for user "${username}".`
  931. );
  932. const res = await this.module.runJob(
  933. "RUN_ACTION2",
  934. {
  935. session,
  936. namespace: "users",
  937. action: "login",
  938. args: [email, password]
  939. },
  940. this
  941. );
  942. const obj = {
  943. status: "success",
  944. message: "Successfully registered."
  945. };
  946. if (res.status === "success") {
  947. obj.SID = res.data.SID;
  948. }
  949. return cb(obj);
  950. }
  951. );
  952. },
  953. /**
  954. * Logs out a user
  955. *
  956. * @param {object} session - the session object automatically added by the websocket
  957. * @param {Function} cb - gets called with the result
  958. */
  959. logout(session, cb) {
  960. async.waterfall(
  961. [
  962. next => {
  963. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }, this)
  964. .then(session => next(null, session))
  965. .catch(next);
  966. },
  967. (session, next) => {
  968. if (!session) return next("Session not found");
  969. return next(null, session);
  970. },
  971. (session, next) => {
  972. CacheModule.runJob("PUB", {
  973. channel: "user.removeSessions",
  974. value: session.userId
  975. });
  976. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  977. setTimeout(() => {
  978. CacheModule.runJob("HDEL", { table: "sessions", key: session.sessionId }, this)
  979. .then(() => next())
  980. .catch(next);
  981. }, 50);
  982. }
  983. ],
  984. async err => {
  985. if (err && err !== true) {
  986. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  987. this.log("ERROR", "USER_LOGOUT", `Logout failed. "${err}" `);
  988. return cb({ status: "error", message: err });
  989. }
  990. this.log("SUCCESS", "USER_LOGOUT", `Logout successful.`);
  991. return cb({
  992. status: "success",
  993. message: "Successfully logged out."
  994. });
  995. }
  996. );
  997. },
  998. /**
  999. * Checks if user's password is correct (e.g. before a sensitive action)
  1000. *
  1001. * @param {object} session - the session object automatically added by the websocket
  1002. * @param {string} password - the password the user entered that we need to validate
  1003. * @param {Function} cb - gets called with the result
  1004. */
  1005. confirmPasswordMatch: isLoginRequired(async function confirmPasswordMatch(session, password, cb) {
  1006. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1007. return async.waterfall(
  1008. [
  1009. next => {
  1010. if (!password || password === "") return next("Please provide a valid password.");
  1011. return next();
  1012. },
  1013. next => {
  1014. userModel.findOne({ _id: session.userId }, (err, user) =>
  1015. next(err, user.services.password.password)
  1016. );
  1017. },
  1018. (passwordHash, next) => {
  1019. if (!passwordHash) return next("Your account doesn't have a password linked.");
  1020. return bcrypt.compare(sha256(password), passwordHash, (err, match) => {
  1021. if (err) return next(err);
  1022. if (!match) return next(null, false);
  1023. return next(null, true);
  1024. });
  1025. }
  1026. ],
  1027. async (err, match) => {
  1028. if (err) {
  1029. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1030. this.log(
  1031. "ERROR",
  1032. "USER_CONFIRM_PASSWORD",
  1033. `Couldn't confirm password for user "${session.userId}". "${err}"`
  1034. );
  1035. return cb({ status: "error", message: err });
  1036. }
  1037. if (match) {
  1038. this.log(
  1039. "SUCCESS",
  1040. "USER_CONFIRM_PASSWORD",
  1041. `Successfully checked for password match (it matched) for user "${session.userId}".`
  1042. );
  1043. return cb({
  1044. status: "success",
  1045. message: "Your password matches."
  1046. });
  1047. }
  1048. this.log(
  1049. "SUCCESS",
  1050. "USER_CONFIRM_PASSWORD",
  1051. `Successfully checked for password match (it didn't match) for user "${session.userId}".`
  1052. );
  1053. return cb({
  1054. status: "error",
  1055. message: "Unfortunately your password doesn't match."
  1056. });
  1057. }
  1058. );
  1059. }),
  1060. /**
  1061. * Checks if user's github access token has expired or not (ie. if their github account is still linked)
  1062. *
  1063. * @param {object} session - the session object automatically added by the websocket
  1064. * @param {Function} cb - gets called with the result
  1065. */
  1066. confirmGithubLink: isLoginRequired(async function confirmGithubLink(session, cb) {
  1067. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1068. return async.waterfall(
  1069. [
  1070. next => {
  1071. if (!config.get("apis.github.enabled")) return next("GitHub authentication is disabled.");
  1072. return userModel.findOne({ _id: session.userId }, (err, user) => next(err, user));
  1073. },
  1074. (user, next) => {
  1075. if (!user.services.github) return next("You don't have GitHub linked to your account.");
  1076. return axios
  1077. .get(`https://api.github.com/user/emails`, {
  1078. headers: {
  1079. "User-Agent": "request",
  1080. Authorization: `token ${user.services.github.access_token}`
  1081. }
  1082. })
  1083. .then(res => next(null, res))
  1084. .catch(err => next(err));
  1085. },
  1086. (res, next) => next(null, res.status === 200)
  1087. ],
  1088. async (err, linked) => {
  1089. if (err) {
  1090. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1091. this.log(
  1092. "ERROR",
  1093. "USER_CONFIRM_GITHUB_LINK",
  1094. `Couldn't confirm github link for user "${session.userId}". "${err}"`
  1095. );
  1096. return cb({ status: "error", message: err });
  1097. }
  1098. this.log(
  1099. "SUCCESS",
  1100. "USER_CONFIRM_GITHUB_LINK",
  1101. `GitHub is ${linked ? "linked" : "not linked"} for user "${session.userId}".`
  1102. );
  1103. return cb({
  1104. status: "success",
  1105. data: { linked },
  1106. message: "Successfully checked if GitHub accounty was linked."
  1107. });
  1108. }
  1109. );
  1110. }),
  1111. /**
  1112. * Removes all sessions for a user
  1113. *
  1114. * @param {object} session - the session object automatically added by the websocket
  1115. * @param {string} userId - the id of the user we are trying to delete the sessions of
  1116. * @param {Function} cb - gets called with the result
  1117. */
  1118. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  1119. async.waterfall(
  1120. [
  1121. next => {
  1122. if (session.userId === userId) return next();
  1123. return hasPermission("users.remove.sessions", session)
  1124. .then(() => next())
  1125. .catch(() => next("Only admins and the owner of the account can remove their sessions."));
  1126. },
  1127. next => {
  1128. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  1129. .then(sessions => {
  1130. next(null, sessions);
  1131. })
  1132. .catch(next);
  1133. },
  1134. (sessions, next) => {
  1135. if (!sessions) return next("There are no sessions for this user to remove.");
  1136. const keys = Object.keys(sessions);
  1137. return next(null, keys, sessions);
  1138. },
  1139. (keys, sessions, next) => {
  1140. CacheModule.runJob("PUB", {
  1141. channel: "user.removeSessions",
  1142. value: userId
  1143. });
  1144. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  1145. setTimeout(
  1146. () =>
  1147. async.each(
  1148. keys,
  1149. (sessionId, callback) => {
  1150. const session = sessions[sessionId];
  1151. if (session && session.userId === userId) {
  1152. // TODO Also maybe add this to this runJob
  1153. CacheModule.runJob("HDEL", {
  1154. table: "sessions",
  1155. key: sessionId
  1156. })
  1157. .then(() => callback(null))
  1158. .catch(callback);
  1159. } else callback();
  1160. },
  1161. err => {
  1162. next(err);
  1163. }
  1164. ),
  1165. 50
  1166. );
  1167. }
  1168. ],
  1169. async err => {
  1170. if (err) {
  1171. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1172. this.log(
  1173. "ERROR",
  1174. "REMOVE_SESSIONS_FOR_USER",
  1175. `Couldn't remove all sessions for user "${userId}". "${err}"`
  1176. );
  1177. return cb({ status: "error", message: err });
  1178. }
  1179. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  1180. return cb({
  1181. status: "success",
  1182. message: "Successfully removed all sessions."
  1183. });
  1184. }
  1185. );
  1186. }),
  1187. /**
  1188. * Updates the order of a user's favorite stations
  1189. *
  1190. * @param {object} session - the session object automatically added by the websocket
  1191. * @param {Array} favoriteStations - array of station ids (with a specific order)
  1192. * @param {Function} cb - gets called with the result
  1193. */
  1194. updateOrderOfFavoriteStations: isLoginRequired(async function updateOrderOfFavoriteStations(
  1195. session,
  1196. favoriteStations,
  1197. cb
  1198. ) {
  1199. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1200. async.waterfall(
  1201. [
  1202. next => {
  1203. userModel.updateOne(
  1204. { _id: session.userId },
  1205. { $set: { favoriteStations } },
  1206. { runValidators: true },
  1207. next
  1208. );
  1209. }
  1210. ],
  1211. async err => {
  1212. if (err) {
  1213. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1214. this.log(
  1215. "ERROR",
  1216. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  1217. `Couldn't update order of favorite stations for user "${session.userId}" to "${favoriteStations}". "${err}"`
  1218. );
  1219. return cb({ status: "error", message: err });
  1220. }
  1221. CacheModule.runJob("PUB", {
  1222. channel: "user.updateOrderOfFavoriteStations",
  1223. value: {
  1224. favoriteStations,
  1225. userId: session.userId
  1226. }
  1227. });
  1228. this.log(
  1229. "SUCCESS",
  1230. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  1231. `Updated order of favorite stations for user "${session.userId}" to "${favoriteStations}".`
  1232. );
  1233. return cb({
  1234. status: "success",
  1235. message: "Order of favorite stations successfully updated"
  1236. });
  1237. }
  1238. );
  1239. }),
  1240. /**
  1241. * Updates the order of a user's playlists
  1242. *
  1243. * @param {object} session - the session object automatically added by the websocket
  1244. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  1245. * @param {Function} cb - gets called with the result
  1246. */
  1247. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  1248. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1249. async.waterfall(
  1250. [
  1251. next => {
  1252. userModel.updateOne(
  1253. { _id: session.userId },
  1254. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  1255. { runValidators: true },
  1256. next
  1257. );
  1258. }
  1259. ],
  1260. async err => {
  1261. if (err) {
  1262. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1263. this.log(
  1264. "ERROR",
  1265. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1266. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  1267. );
  1268. return cb({ status: "error", message: err });
  1269. }
  1270. CacheModule.runJob("PUB", {
  1271. channel: "user.updateOrderOfPlaylists",
  1272. value: {
  1273. orderOfPlaylists,
  1274. userId: session.userId
  1275. }
  1276. });
  1277. this.log(
  1278. "SUCCESS",
  1279. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1280. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  1281. );
  1282. return cb({
  1283. status: "success",
  1284. message: "Order of playlists successfully updated"
  1285. });
  1286. }
  1287. );
  1288. }),
  1289. /**
  1290. * Updates a user's preferences
  1291. *
  1292. * @param {object} session - the session object automatically added by the websocket
  1293. * @param {object} preferences - object containing preferences
  1294. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  1295. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  1296. * @param {boolean} preferences.activityLogPublic - whether or not a user's activity log can be publicly viewed
  1297. * @param {boolean} preferences.anonymousSongRequests - whether or not a user's requested songs will be anonymous
  1298. * @param {boolean} preferences.activityWatch - whether or not a user is using the ActivityWatch integration
  1299. * @param {Function} cb - gets called with the result
  1300. */
  1301. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  1302. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1303. async.waterfall(
  1304. [
  1305. next => {
  1306. const $set = {};
  1307. Object.keys(preferences).forEach(preference => {
  1308. $set[`preferences.${preference}`] = preferences[preference];
  1309. });
  1310. return next(null, $set);
  1311. },
  1312. ($set, next) => {
  1313. userModel.findByIdAndUpdate(session.userId, { $set }, { new: false, upsert: true }, next);
  1314. }
  1315. ],
  1316. async err => {
  1317. if (err) {
  1318. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1319. this.log(
  1320. "ERROR",
  1321. "UPDATE_USER_PREFERENCES",
  1322. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  1323. preferences
  1324. )}". "${err}"`
  1325. );
  1326. return cb({ status: "error", message: err });
  1327. }
  1328. CacheModule.runJob("PUB", {
  1329. channel: "user.updatePreferences",
  1330. value: {
  1331. preferences,
  1332. userId: session.userId
  1333. }
  1334. });
  1335. // if (preferences.nightmode !== undefined && preferences.nightmode !== user.preferences.nightmode)
  1336. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1337. // userId: session.userId,
  1338. // type: "user__toggle_nightmode",
  1339. // payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  1340. // });
  1341. // if (
  1342. // preferences.autoSkipDisliked !== undefined &&
  1343. // preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked
  1344. // )
  1345. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1346. // userId: session.userId,
  1347. // type: "user__toggle_autoskip_disliked_songs",
  1348. // payload: {
  1349. // message: preferences.autoSkipDisliked
  1350. // ? "Enabled the autoskipping of disliked songs"
  1351. // : "Disabled the autoskipping of disliked songs"
  1352. // }
  1353. // });
  1354. // if (
  1355. // preferences.activityWatch !== undefined &&
  1356. // preferences.activityWatch !== user.preferences.activityWatch
  1357. // )
  1358. // ActivitiesModule.runJob("ADD_ACTIVITY", {
  1359. // userId: session.userId,
  1360. // type: "user__toggle_activity_watch",
  1361. // payload: {
  1362. // message: preferences.activityWatch
  1363. // ? "Enabled ActivityWatch integration"
  1364. // : "Disabled ActivityWatch integration"
  1365. // }
  1366. // });
  1367. this.log(
  1368. "SUCCESS",
  1369. "UPDATE_USER_PREFERENCES",
  1370. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  1371. );
  1372. return cb({
  1373. status: "success",
  1374. message: "Preferences successfully updated"
  1375. });
  1376. }
  1377. );
  1378. }),
  1379. /**
  1380. * Retrieves a user's preferences
  1381. *
  1382. * @param {object} session - the session object automatically added by the websocket
  1383. * @param {Function} cb - gets called with the result
  1384. */
  1385. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  1386. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1387. async.waterfall(
  1388. [
  1389. next => {
  1390. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  1391. },
  1392. (user, next) => {
  1393. if (!user) next("User not found");
  1394. else next(null, user);
  1395. }
  1396. ],
  1397. async (err, user) => {
  1398. if (err) {
  1399. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1400. this.log(
  1401. "ERROR",
  1402. "GET_USER_PREFERENCES",
  1403. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  1404. );
  1405. return cb({ status: "error", message: err });
  1406. }
  1407. this.log(
  1408. "SUCCESS",
  1409. "GET_USER_PREFERENCES",
  1410. `Successfully obtained preferences for user "${session.userId}".`
  1411. );
  1412. return cb({
  1413. status: "success",
  1414. message: "Preferences successfully retrieved",
  1415. data: { preferences: user.preferences }
  1416. });
  1417. }
  1418. );
  1419. }),
  1420. /**
  1421. * Gets user object from ObjectId or username (only a few properties)
  1422. *
  1423. * @param {object} session - the session object automatically added by the websocket
  1424. * @param {string} identifier - the ObjectId or username of the user we are trying to find
  1425. * @param {Function} cb - gets called with the result
  1426. */
  1427. getBasicUser: async function getBasicUser(session, identifier, cb) {
  1428. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1429. async.waterfall(
  1430. [
  1431. next => {
  1432. if (mongoose.Types.ObjectId.isValid(identifier)) userModel.findOne({ _id: identifier }, next);
  1433. else userModel.findOne({ username: new RegExp(`^${identifier}$`, "i") }, next);
  1434. },
  1435. (account, next) => {
  1436. if (!account) return next("User not found.");
  1437. return next(null, account);
  1438. }
  1439. ],
  1440. async (err, account) => {
  1441. if (err && err !== true) {
  1442. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1443. this.log("ERROR", "GET_BASIC_USER", `User not found for "${identifier}". "${err}"`);
  1444. return cb({ status: "error", message: err });
  1445. }
  1446. this.log("SUCCESS", "GET_BASIC_USER", `User found for "${identifier}".`);
  1447. return cb({
  1448. status: "success",
  1449. data: {
  1450. _id: account._id,
  1451. name: account.name,
  1452. username: account.username,
  1453. location: account.location,
  1454. bio: account.bio,
  1455. role: account.role,
  1456. avatar: account.avatar,
  1457. createdAt: account.createdAt
  1458. }
  1459. });
  1460. }
  1461. );
  1462. },
  1463. /**
  1464. * Gets a list of long jobs, including onprogress events when those long jobs have progress
  1465. *
  1466. * @param {object} session - the session object automatically added by the websocket
  1467. * @param {Function} cb - gets called with the result
  1468. */
  1469. getLongJobs: isLoginRequired(async function getLongJobs(session, cb) {
  1470. async.waterfall(
  1471. [
  1472. next => {
  1473. CacheModule.runJob(
  1474. "LRANGE",
  1475. {
  1476. key: `longJobs.${session.userId}`
  1477. },
  1478. this
  1479. )
  1480. .then(longJobUuids => next(null, longJobUuids))
  1481. .catch(next);
  1482. },
  1483. (longJobUuids, next) => {
  1484. next(
  1485. null,
  1486. longJobUuids
  1487. .map(longJobUuid => moduleManager.jobManager.getJob(longJobUuid))
  1488. .filter(longJob => !!longJob)
  1489. );
  1490. },
  1491. (longJobs, next) => {
  1492. longJobs.forEach(longJob => {
  1493. if (longJob.onProgress)
  1494. longJob.onProgress.on("progress", data => {
  1495. this.publishProgress(
  1496. {
  1497. id: longJob.toString(),
  1498. ...data
  1499. },
  1500. true
  1501. );
  1502. });
  1503. });
  1504. next(
  1505. null,
  1506. longJobs.map(longJob => ({
  1507. id: longJob.toString(),
  1508. name: longJob.longJobTitle,
  1509. status: longJob.lastProgressData.status,
  1510. message: longJob.lastProgressData.message
  1511. }))
  1512. );
  1513. }
  1514. ],
  1515. async (err, longJobs) => {
  1516. if (err) {
  1517. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1518. this.log("ERROR", "GET_LONG_JOBS", `Couldn't get long jobs for user "${session.userId}". "${err}"`);
  1519. return cb({ status: "error", message: err });
  1520. }
  1521. this.log("SUCCESS", "GET_LONG_JOBS", `Got long jobs for user "${session.userId}".`);
  1522. return cb({
  1523. status: "success",
  1524. data: {
  1525. longJobs
  1526. }
  1527. });
  1528. }
  1529. );
  1530. }),
  1531. /**
  1532. * Gets a specific long job, including onprogress events when that long job has progress
  1533. *
  1534. * @param {object} session - the session object automatically added by the websocket
  1535. * @param {string} jobId - the if id the long job
  1536. * @param {Function} cb - gets called with the result
  1537. */
  1538. getLongJob: isLoginRequired(async function getLongJobs(session, jobId, cb) {
  1539. async.waterfall(
  1540. [
  1541. next => {
  1542. CacheModule.runJob(
  1543. "LRANGE",
  1544. {
  1545. key: `longJobs.${session.userId}`
  1546. },
  1547. this
  1548. )
  1549. .then(longJobUuids => next(null, longJobUuids))
  1550. .catch(next);
  1551. },
  1552. (longJobUuids, next) => {
  1553. if (longJobUuids.indexOf(jobId) === -1) return next("Long job not found.");
  1554. const longJob = moduleManager.jobManager.getJob(jobId);
  1555. if (!longJob) return next("Long job not found.");
  1556. return next(null, longJob);
  1557. },
  1558. (longJob, next) => {
  1559. if (longJob.onProgress)
  1560. longJob.onProgress.on("progress", data => {
  1561. this.publishProgress(
  1562. {
  1563. id: longJob.toString(),
  1564. ...data
  1565. },
  1566. true
  1567. );
  1568. });
  1569. next(null, {
  1570. id: longJob.toString(),
  1571. name: longJob.longJobTitle,
  1572. status: longJob.lastProgressData.status,
  1573. message: longJob.lastProgressData.message
  1574. });
  1575. }
  1576. ],
  1577. async (err, longJob) => {
  1578. if (err) {
  1579. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1580. this.log(
  1581. "ERROR",
  1582. "GET_LONG_JOB",
  1583. `Couldn't get long job for user "${session.userId}" with id "${jobId}". "${err}"`
  1584. );
  1585. return cb({ status: "error", message: err });
  1586. }
  1587. this.log("SUCCESS", "GET_LONG_JOB", `Got long job for user "${session.userId}" with id "${jobId}".`);
  1588. return cb({
  1589. status: "success",
  1590. data: {
  1591. longJob
  1592. }
  1593. });
  1594. }
  1595. );
  1596. }),
  1597. /**
  1598. * Removes active long job for a user
  1599. *
  1600. * @param {object} session - the session object automatically added by the websocket
  1601. * @param {string} jobId - array of playlist ids (with a specific order)
  1602. * @param {Function} cb - gets called with the result
  1603. */
  1604. removeLongJob: isLoginRequired(async function removeLongJob(session, jobId, cb) {
  1605. async.waterfall(
  1606. [
  1607. next => {
  1608. CacheModule.runJob(
  1609. "LREM",
  1610. {
  1611. key: `longJobs.${session.userId}`,
  1612. value: jobId
  1613. },
  1614. this
  1615. )
  1616. .then(() => next())
  1617. .catch(next);
  1618. },
  1619. next => {
  1620. const job = moduleManager.jobManager.getJob(jobId);
  1621. if (job && job.status === "FINISHED") job.forgetLongJob();
  1622. next();
  1623. }
  1624. ],
  1625. async err => {
  1626. if (err) {
  1627. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1628. this.log(
  1629. "ERROR",
  1630. "REMOVE_LONG_JOB",
  1631. `Couldn't remove long job for user "${session.userId}" with id ${jobId}. "${err}"`
  1632. );
  1633. return cb({ status: "error", message: err });
  1634. }
  1635. this.log(
  1636. "SUCCESS",
  1637. "REMOVE_LONG_JOB",
  1638. `Removed long job for user "${session.userId}" with id ${jobId}.`
  1639. );
  1640. CacheModule.runJob("PUB", {
  1641. channel: "longJob.removed",
  1642. value: { jobId, userId: session.userId }
  1643. });
  1644. return cb({
  1645. status: "success",
  1646. message: "Removed long job successfully."
  1647. });
  1648. }
  1649. );
  1650. }),
  1651. /**
  1652. * Gets a user from a userId
  1653. *
  1654. * @param {object} session - the session object automatically added by the websocket
  1655. * @param {string} userId - the userId of the person we are trying to get the username from
  1656. * @param {Function} cb - gets called with the result
  1657. */
  1658. getUserFromId: useHasPermission("users.get", async function getUserFromId(session, userId, cb) {
  1659. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1660. userModel
  1661. .findById(userId)
  1662. .then(user => {
  1663. if (user) {
  1664. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  1665. return cb({
  1666. status: "success",
  1667. data: {
  1668. _id: user._id,
  1669. username: user.username,
  1670. role: user.role,
  1671. liked: user.liked,
  1672. disliked: user.disliked,
  1673. songsRequested: user.statistics.songsRequested,
  1674. email: {
  1675. address: user.email.address,
  1676. verified: user.email.verified
  1677. },
  1678. hasPassword: !!user.services.password,
  1679. services: { github: user.services.github }
  1680. }
  1681. });
  1682. }
  1683. this.log(
  1684. "ERROR",
  1685. "GET_USER_FROM_ID",
  1686. `Getting the user from userId "${userId}" failed. User not found.`
  1687. );
  1688. return cb({
  1689. status: "error",
  1690. message: "Couldn't find the user."
  1691. });
  1692. })
  1693. .catch(async err => {
  1694. if (err && err !== true) {
  1695. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1696. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  1697. cb({ status: "error", message: err });
  1698. }
  1699. });
  1700. }),
  1701. /**
  1702. * Gets user info from session
  1703. *
  1704. * @param {object} session - the session object automatically added by the websocket
  1705. * @param {Function} cb - gets called with the result
  1706. */
  1707. findBySession: isLoginRequired(async function findBySession(session, cb) {
  1708. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1709. async.waterfall(
  1710. [
  1711. next => {
  1712. CacheModule.runJob(
  1713. "HGET",
  1714. {
  1715. table: "sessions",
  1716. key: session.sessionId
  1717. },
  1718. this
  1719. )
  1720. .then(session => next(null, session))
  1721. .catch(next);
  1722. },
  1723. (session, next) => {
  1724. if (!session) return next("Session not found.");
  1725. return next(null, session);
  1726. },
  1727. (session, next) => {
  1728. userModel.findOne({ _id: session.userId }, next);
  1729. },
  1730. (user, next) => {
  1731. if (!user) return next("User not found.");
  1732. return next(null, user);
  1733. }
  1734. ],
  1735. async (err, user) => {
  1736. if (err && err !== true) {
  1737. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1738. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  1739. return cb({ status: "error", message: err });
  1740. }
  1741. const sanitisedUser = {
  1742. email: {
  1743. address: user.email.address
  1744. },
  1745. avatar: user.avatar,
  1746. username: user.username,
  1747. name: user.name,
  1748. location: user.location,
  1749. bio: user.bio
  1750. };
  1751. if (user.services.password && user.services.password.password) sanitisedUser.password = true;
  1752. if (user.services.github && user.services.github.id) sanitisedUser.github = true;
  1753. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  1754. return cb({
  1755. status: "success",
  1756. data: { user: sanitisedUser }
  1757. });
  1758. }
  1759. );
  1760. }),
  1761. /**
  1762. * Updates a user's username
  1763. *
  1764. * @param {object} session - the session object automatically added by the websocket
  1765. * @param {string} updatingUserId - the updating user's id
  1766. * @param {string} newUsername - the new username
  1767. * @param {Function} cb - gets called with the result
  1768. */
  1769. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  1770. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1771. async.waterfall(
  1772. [
  1773. next => {
  1774. if (updatingUserId === session.userId) return next();
  1775. return hasPermission("users.update", session)
  1776. .then(() => next())
  1777. .catch(() => next("Invalid permissions."));
  1778. },
  1779. next => userModel.findOne({ _id: updatingUserId }, next),
  1780. (user, next) => {
  1781. if (!user) return next("User not found.");
  1782. if (user.username === newUsername)
  1783. return next("New username can't be the same as the old username.");
  1784. return next(null);
  1785. },
  1786. next => {
  1787. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1788. },
  1789. (user, next) => {
  1790. if (!user) return next();
  1791. if (user._id.toString() === updatingUserId) return next();
  1792. return next("That username is already in use.");
  1793. },
  1794. next => {
  1795. userModel.updateOne(
  1796. { _id: updatingUserId },
  1797. { $set: { username: newUsername } },
  1798. { runValidators: true },
  1799. next
  1800. );
  1801. }
  1802. ],
  1803. async err => {
  1804. if (err && err !== true) {
  1805. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1806. this.log(
  1807. "ERROR",
  1808. "UPDATE_USERNAME",
  1809. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1810. );
  1811. return cb({ status: "error", message: err });
  1812. }
  1813. CacheModule.runJob("PUB", {
  1814. channel: "user.updateUsername",
  1815. value: {
  1816. username: newUsername,
  1817. _id: updatingUserId
  1818. }
  1819. });
  1820. CacheModule.runJob("PUB", {
  1821. channel: "user.updated",
  1822. value: { userId: updatingUserId }
  1823. });
  1824. this.log(
  1825. "SUCCESS",
  1826. "UPDATE_USERNAME",
  1827. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1828. );
  1829. return cb({
  1830. status: "success",
  1831. message: "Username updated successfully"
  1832. });
  1833. }
  1834. );
  1835. }),
  1836. /**
  1837. * Updates a user's email
  1838. *
  1839. * @param {object} session - the session object automatically added by the websocket
  1840. * @param {string} updatingUserId - the updating user's id
  1841. * @param {string} newEmail - the new email
  1842. * @param {Function} cb - gets called with the result
  1843. */
  1844. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1845. newEmail = newEmail.toLowerCase();
  1846. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1847. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1848. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1849. async.waterfall(
  1850. [
  1851. next => {
  1852. if (updatingUserId === session.userId) return next();
  1853. return hasPermission("users.update.restricted", session)
  1854. .then(() => next())
  1855. .catch(() => next("Invalid permissions."));
  1856. },
  1857. next => userModel.findOne({ _id: updatingUserId }, next),
  1858. (user, next) => {
  1859. if (!user) return next("User not found.");
  1860. if (user.email.address === newEmail)
  1861. return next("New email can't be the same as your the old email.");
  1862. return next();
  1863. },
  1864. next => {
  1865. userModel.findOne({ "email.address": newEmail }, next);
  1866. },
  1867. (user, next) => {
  1868. if (!user) return next();
  1869. if (user._id === updatingUserId) return next();
  1870. return next("That email is already in use.");
  1871. },
  1872. // regenerate the url for gravatar avatar
  1873. next => {
  1874. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1875. next(null, url);
  1876. });
  1877. },
  1878. (newAvatarUrl, next) => {
  1879. userModel.updateOne(
  1880. { _id: updatingUserId },
  1881. {
  1882. $set: {
  1883. "avatar.url": newAvatarUrl,
  1884. "email.address": newEmail,
  1885. "email.verified": false,
  1886. "email.verificationToken": verificationToken
  1887. }
  1888. },
  1889. { runValidators: true },
  1890. next
  1891. );
  1892. },
  1893. (res, next) => {
  1894. userModel.findOne({ _id: updatingUserId }, next);
  1895. },
  1896. (user, next) => {
  1897. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1898. next(err);
  1899. });
  1900. }
  1901. ],
  1902. async err => {
  1903. if (err && err !== true) {
  1904. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1905. this.log(
  1906. "ERROR",
  1907. "UPDATE_EMAIL",
  1908. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1909. );
  1910. return cb({ status: "error", message: err });
  1911. }
  1912. this.log(
  1913. "SUCCESS",
  1914. "UPDATE_EMAIL",
  1915. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1916. );
  1917. CacheModule.runJob("PUB", {
  1918. channel: "user.updated",
  1919. value: { userId: updatingUserId }
  1920. });
  1921. return cb({
  1922. status: "success",
  1923. message: "Email updated successfully."
  1924. });
  1925. }
  1926. );
  1927. }),
  1928. /**
  1929. * Updates a user's name
  1930. *
  1931. * @param {object} session - the session object automatically added by the websocket
  1932. * @param {string} updatingUserId - the updating user's id
  1933. * @param {string} newBio - the new name
  1934. * @param {Function} cb - gets called with the result
  1935. */
  1936. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1937. const userModel = await DBModule.runJob(
  1938. "GET_MODEL",
  1939. {
  1940. modelName: "user"
  1941. },
  1942. this
  1943. );
  1944. async.waterfall(
  1945. [
  1946. next => {
  1947. if (updatingUserId === session.userId) return next();
  1948. return hasPermission("users.update", session)
  1949. .then(() => next())
  1950. .catch(() => next("Invalid permissions."));
  1951. },
  1952. next => userModel.findOne({ _id: updatingUserId }, next),
  1953. (user, next) => {
  1954. if (!user) return next("User not found.");
  1955. return userModel.updateOne(
  1956. { _id: updatingUserId },
  1957. { $set: { name: newName } },
  1958. { runValidators: true },
  1959. next
  1960. );
  1961. }
  1962. ],
  1963. async err => {
  1964. if (err && err !== true) {
  1965. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1966. this.log(
  1967. "ERROR",
  1968. "UPDATE_NAME",
  1969. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1970. );
  1971. return cb({ status: "error", message: err });
  1972. }
  1973. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1974. userId: updatingUserId,
  1975. type: "user__edit_name",
  1976. payload: { message: `Changed name to ${newName}` }
  1977. });
  1978. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1979. CacheModule.runJob("PUB", {
  1980. channel: "user.updated",
  1981. value: { userId: updatingUserId }
  1982. });
  1983. return cb({
  1984. status: "success",
  1985. message: "Name updated successfully"
  1986. });
  1987. }
  1988. );
  1989. }),
  1990. /**
  1991. * Updates a user's location
  1992. *
  1993. * @param {object} session - the session object automatically added by the websocket
  1994. * @param {string} updatingUserId - the updating user's id
  1995. * @param {string} newLocation - the new location
  1996. * @param {Function} cb - gets called with the result
  1997. */
  1998. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1999. const userModel = await DBModule.runJob(
  2000. "GET_MODEL",
  2001. {
  2002. modelName: "user"
  2003. },
  2004. this
  2005. );
  2006. async.waterfall(
  2007. [
  2008. next => {
  2009. if (updatingUserId === session.userId) return next();
  2010. return hasPermission("users.update", session)
  2011. .then(() => next())
  2012. .catch(() => next("Invalid permissions."));
  2013. },
  2014. next => userModel.findOne({ _id: updatingUserId }, next),
  2015. (user, next) => {
  2016. if (!user) return next("User not found.");
  2017. return userModel.updateOne(
  2018. { _id: updatingUserId },
  2019. { $set: { location: newLocation } },
  2020. { runValidators: true },
  2021. next
  2022. );
  2023. }
  2024. ],
  2025. async err => {
  2026. if (err && err !== true) {
  2027. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2028. this.log(
  2029. "ERROR",
  2030. "UPDATE_LOCATION",
  2031. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  2032. );
  2033. return cb({ status: "error", message: err });
  2034. }
  2035. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2036. userId: updatingUserId,
  2037. type: "user__edit_location",
  2038. payload: { message: `Changed location to ${newLocation}` }
  2039. });
  2040. this.log(
  2041. "SUCCESS",
  2042. "UPDATE_LOCATION",
  2043. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  2044. );
  2045. CacheModule.runJob("PUB", {
  2046. channel: "user.updated",
  2047. value: { userId: updatingUserId }
  2048. });
  2049. return cb({
  2050. status: "success",
  2051. message: "Location updated successfully"
  2052. });
  2053. }
  2054. );
  2055. }),
  2056. /**
  2057. * Updates a user's bio
  2058. *
  2059. * @param {object} session - the session object automatically added by the websocket
  2060. * @param {string} updatingUserId - the updating user's id
  2061. * @param {string} newBio - the new bio
  2062. * @param {Function} cb - gets called with the result
  2063. */
  2064. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  2065. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2066. async.waterfall(
  2067. [
  2068. next => {
  2069. if (updatingUserId === session.userId) return next();
  2070. return hasPermission("users.update", session)
  2071. .then(() => next())
  2072. .catch(() => next("Invalid permissions."));
  2073. },
  2074. next => userModel.findOne({ _id: updatingUserId }, next),
  2075. (user, next) => {
  2076. if (!user) return next("User not found.");
  2077. return userModel.updateOne(
  2078. { _id: updatingUserId },
  2079. { $set: { bio: newBio } },
  2080. { runValidators: true },
  2081. next
  2082. );
  2083. }
  2084. ],
  2085. async err => {
  2086. if (err && err !== true) {
  2087. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2088. this.log(
  2089. "ERROR",
  2090. "UPDATE_BIO",
  2091. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  2092. );
  2093. return cb({ status: "error", message: err });
  2094. }
  2095. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2096. userId: updatingUserId,
  2097. type: "user__edit_bio",
  2098. payload: { message: `Changed bio to ${newBio}` }
  2099. });
  2100. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  2101. CacheModule.runJob("PUB", {
  2102. channel: "user.updated",
  2103. value: { userId: updatingUserId }
  2104. });
  2105. return cb({
  2106. status: "success",
  2107. message: "Bio updated successfully"
  2108. });
  2109. }
  2110. );
  2111. }),
  2112. /**
  2113. * Updates a user's avatar
  2114. *
  2115. * @param {object} session - the session object automatically added by the websocket
  2116. * @param {string} updatingUserId - the updating user's id
  2117. * @param {string} newAvatar - the new avatar object
  2118. * @param {Function} cb - gets called with the result
  2119. */
  2120. updateAvatar: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  2121. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2122. async.waterfall(
  2123. [
  2124. next => {
  2125. if (updatingUserId === session.userId) return next();
  2126. return hasPermission("users.update", session)
  2127. .then(() => next())
  2128. .catch(() => next("Invalid permissions."));
  2129. },
  2130. next => userModel.findOne({ _id: updatingUserId }, next),
  2131. (user, next) => {
  2132. if (!user) return next("User not found.");
  2133. return userModel.findOneAndUpdate(
  2134. { _id: updatingUserId },
  2135. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  2136. { new: true, runValidators: true },
  2137. next
  2138. );
  2139. }
  2140. ],
  2141. async err => {
  2142. if (err && err !== true) {
  2143. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2144. this.log(
  2145. "ERROR",
  2146. "UPDATE_AVATAR",
  2147. `Couldn't update avatar for user "${updatingUserId}" to type "${newAvatar.type}" and color "${newAvatar.color}". "${err}"`
  2148. );
  2149. return cb({ status: "error", message: err });
  2150. }
  2151. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2152. userId: updatingUserId,
  2153. type: "user__edit_avatar",
  2154. payload: { message: `Changed avatar to use ${newAvatar.type} and ${newAvatar.color}` }
  2155. });
  2156. this.log(
  2157. "SUCCESS",
  2158. "UPDATE_AVATAR",
  2159. `Updated avatar for user "${updatingUserId}" to type "${newAvatar.type} and color ${newAvatar.color}".`
  2160. );
  2161. CacheModule.runJob("PUB", {
  2162. channel: "user.updated",
  2163. value: { userId: updatingUserId }
  2164. });
  2165. return cb({
  2166. status: "success",
  2167. message: "Avatar updated successfully"
  2168. });
  2169. }
  2170. );
  2171. }),
  2172. /**
  2173. * Updates a user's role
  2174. *
  2175. * @param {object} session - the session object automatically added by the websocket
  2176. * @param {string} updatingUserId - the updating user's id
  2177. * @param {string} newRole - the new role
  2178. * @param {Function} cb - gets called with the result
  2179. */
  2180. updateRole: useHasPermission(
  2181. "users.update.restricted",
  2182. async function updateRole(session, updatingUserId, newRole, cb) {
  2183. newRole = newRole.toLowerCase();
  2184. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2185. async.waterfall(
  2186. [
  2187. next => {
  2188. userModel.findOne({ _id: updatingUserId }, next);
  2189. },
  2190. (user, next) => {
  2191. if (!user) return next("User not found.");
  2192. if (user.role === newRole) return next("New role can't be the same as the old role.");
  2193. return next(null, user);
  2194. },
  2195. (user, next) => {
  2196. userModel.updateOne(
  2197. { _id: updatingUserId },
  2198. { $set: { role: newRole } },
  2199. { runValidators: true },
  2200. err => next(err, user)
  2201. );
  2202. }
  2203. ],
  2204. async (err, user) => {
  2205. if (err && err !== true) {
  2206. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2207. this.log(
  2208. "ERROR",
  2209. "UPDATE_ROLE",
  2210. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  2211. );
  2212. return cb({ status: "error", message: err });
  2213. }
  2214. this.log(
  2215. "SUCCESS",
  2216. "UPDATE_ROLE",
  2217. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  2218. );
  2219. CacheModule.runJob("PUB", {
  2220. channel: "user.updated",
  2221. value: { userId: updatingUserId }
  2222. });
  2223. CacheModule.runJob("PUB", {
  2224. channel: "user.updateRole",
  2225. value: { user }
  2226. });
  2227. return cb({
  2228. status: "success",
  2229. message: "Role successfully updated."
  2230. });
  2231. }
  2232. );
  2233. }
  2234. ),
  2235. /**
  2236. * Updates a user's password
  2237. *
  2238. * @param {object} session - the session object automatically added by the websocket
  2239. * @param {string} previousPassword - the previous password
  2240. * @param {string} newPassword - the new password
  2241. * @param {Function} cb - gets called with the result
  2242. */
  2243. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  2244. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2245. async.waterfall(
  2246. [
  2247. next => {
  2248. userModel.findOne({ _id: session.userId }, next);
  2249. },
  2250. (user, next) => {
  2251. if (!user.services.password) return next("This account does not have a password set.");
  2252. return next(null, user.services.password.password);
  2253. },
  2254. (storedPassword, next) => {
  2255. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  2256. if (res) return next();
  2257. return next("Please enter the correct previous password.");
  2258. });
  2259. },
  2260. next => {
  2261. if (!DBModule.passwordValid(newPassword))
  2262. return next("Invalid new password. Check if it meets all the requirements.");
  2263. return next();
  2264. },
  2265. next => {
  2266. bcrypt.genSalt(10, next);
  2267. },
  2268. // hash the password
  2269. (salt, next) => {
  2270. bcrypt.hash(sha256(newPassword), salt, next);
  2271. },
  2272. (hashedPassword, next) => {
  2273. userModel.updateOne(
  2274. { _id: session.userId },
  2275. {
  2276. $set: {
  2277. "services.password.password": hashedPassword
  2278. }
  2279. },
  2280. next
  2281. );
  2282. }
  2283. ],
  2284. async err => {
  2285. if (err) {
  2286. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2287. this.log(
  2288. "ERROR",
  2289. "UPDATE_PASSWORD",
  2290. `Failed updating user password of user '${session.userId}'. '${err}'.`
  2291. );
  2292. return cb({ status: "error", message: err });
  2293. }
  2294. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  2295. return cb({
  2296. status: "success",
  2297. message: "Password successfully updated."
  2298. });
  2299. }
  2300. );
  2301. }),
  2302. /**
  2303. * Requests a password for a session
  2304. *
  2305. * @param {object} session - the session object automatically added by the websocket
  2306. * @param {string} email - the email of the user that requests a password reset
  2307. * @param {Function} cb - gets called with the result
  2308. */
  2309. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  2310. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2311. const passwordRequestSchema = await MailModule.runJob(
  2312. "GET_SCHEMA",
  2313. {
  2314. schemaName: "passwordRequest"
  2315. },
  2316. this
  2317. );
  2318. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2319. async.waterfall(
  2320. [
  2321. next => {
  2322. userModel.findOne({ _id: session.userId }, next);
  2323. },
  2324. (user, next) => {
  2325. if (!user) return next("User not found.");
  2326. if (user.services.password && user.services.password.password)
  2327. return next("You already have a password set.");
  2328. return next(null, user);
  2329. },
  2330. (user, next) => {
  2331. const expires = new Date();
  2332. expires.setDate(expires.getDate() + 1);
  2333. userModel.findOneAndUpdate(
  2334. { "email.address": user.email.address },
  2335. {
  2336. $set: {
  2337. "services.password": {
  2338. set: { code, expires }
  2339. }
  2340. }
  2341. },
  2342. { runValidators: true },
  2343. next
  2344. );
  2345. },
  2346. (user, next) => {
  2347. passwordRequestSchema(user.email.address, user.username, code, next);
  2348. }
  2349. ],
  2350. async err => {
  2351. if (err && err !== true) {
  2352. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2353. this.log(
  2354. "ERROR",
  2355. "REQUEST_PASSWORD",
  2356. `UserId '${session.userId}' failed to request password. '${err}'`
  2357. );
  2358. return cb({ status: "error", message: err });
  2359. }
  2360. this.log(
  2361. "SUCCESS",
  2362. "REQUEST_PASSWORD",
  2363. `UserId '${session.userId}' successfully requested a password.`
  2364. );
  2365. return cb({
  2366. status: "success",
  2367. message: "Successfully requested password."
  2368. });
  2369. }
  2370. );
  2371. }),
  2372. /**
  2373. * Verifies a password code
  2374. *
  2375. * @param {object} session - the session object automatically added by the websocket
  2376. * @param {string} code - the password code
  2377. * @param {Function} cb - gets called with the result
  2378. */
  2379. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  2380. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2381. async.waterfall(
  2382. [
  2383. next => {
  2384. if (!code || typeof code !== "string") return next("Invalid code.");
  2385. return userModel.findOne(
  2386. {
  2387. "services.password.set.code": code,
  2388. _id: session.userId
  2389. },
  2390. next
  2391. );
  2392. },
  2393. (user, next) => {
  2394. if (!user) return next("Invalid code.");
  2395. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  2396. return next(null);
  2397. }
  2398. ],
  2399. async err => {
  2400. if (err && err !== true) {
  2401. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2402. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  2403. cb({ status: "error", message: err });
  2404. } else {
  2405. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  2406. cb({
  2407. status: "success",
  2408. message: "Successfully verified password code."
  2409. });
  2410. }
  2411. }
  2412. );
  2413. }),
  2414. /**
  2415. * Adds a password to a user with a code
  2416. *
  2417. * @param {object} session - the session object automatically added by the websocket
  2418. * @param {string} code - the password code
  2419. * @param {string} newPassword - the new password code
  2420. * @param {Function} cb - gets called with the result
  2421. */
  2422. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  2423. const userModel = await DBModule.runJob(
  2424. "GET_MODEL",
  2425. {
  2426. modelName: "user"
  2427. },
  2428. this
  2429. );
  2430. async.waterfall(
  2431. [
  2432. next => {
  2433. if (!code || typeof code !== "string") return next("Invalid code.");
  2434. return userModel.findOne({ "services.password.set.code": code }, next);
  2435. },
  2436. (user, next) => {
  2437. if (!user) return next("Invalid code.");
  2438. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  2439. return next();
  2440. },
  2441. next => {
  2442. if (!DBModule.passwordValid(newPassword))
  2443. return next("Invalid password. Check if it meets all the requirements.");
  2444. return next();
  2445. },
  2446. next => {
  2447. bcrypt.genSalt(10, next);
  2448. },
  2449. // hash the password
  2450. (salt, next) => {
  2451. bcrypt.hash(sha256(newPassword), salt, next);
  2452. },
  2453. (hashedPassword, next) => {
  2454. userModel.updateOne(
  2455. { "services.password.set.code": code },
  2456. {
  2457. $set: {
  2458. "services.password.password": hashedPassword
  2459. },
  2460. $unset: { "services.password.set": "" }
  2461. },
  2462. { runValidators: true },
  2463. next
  2464. );
  2465. }
  2466. ],
  2467. async err => {
  2468. if (err && err !== true) {
  2469. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2470. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  2471. return cb({ status: "error", message: err });
  2472. }
  2473. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  2474. CacheModule.runJob("PUB", {
  2475. channel: "user.linkPassword",
  2476. value: session.userId
  2477. });
  2478. CacheModule.runJob("PUB", {
  2479. channel: "user.updated",
  2480. value: { userId: session.userId }
  2481. });
  2482. return cb({
  2483. status: "success",
  2484. message: "Successfully added password."
  2485. });
  2486. }
  2487. );
  2488. }),
  2489. /**
  2490. * Unlinks password from user
  2491. *
  2492. * @param {object} session - the session object automatically added by the websocket
  2493. * @param {Function} cb - gets called with the result
  2494. */
  2495. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  2496. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2497. async.waterfall(
  2498. [
  2499. next => {
  2500. userModel.findOne({ _id: session.userId }, next);
  2501. },
  2502. (user, next) => {
  2503. if (!user) return next("Not logged in.");
  2504. if (!config.get("apis.github.enabled")) return next("Unlinking password is disabled.");
  2505. if (!user.services.github || !user.services.github.id)
  2506. return next("You can't remove password login without having GitHub login.");
  2507. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  2508. }
  2509. ],
  2510. async err => {
  2511. if (err && err !== true) {
  2512. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2513. this.log(
  2514. "ERROR",
  2515. "UNLINK_PASSWORD",
  2516. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  2517. );
  2518. return cb({ status: "error", message: err });
  2519. }
  2520. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  2521. CacheModule.runJob("PUB", {
  2522. channel: "user.unlinkPassword",
  2523. value: session.userId
  2524. });
  2525. CacheModule.runJob("PUB", {
  2526. channel: "user.updated",
  2527. value: { userId: session.userId }
  2528. });
  2529. return cb({
  2530. status: "success",
  2531. message: "Successfully unlinked password."
  2532. });
  2533. }
  2534. );
  2535. }),
  2536. /**
  2537. * Unlinks GitHub from user
  2538. *
  2539. * @param {object} session - the session object automatically added by the websocket
  2540. * @param {Function} cb - gets called with the result
  2541. */
  2542. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  2543. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2544. async.waterfall(
  2545. [
  2546. next => {
  2547. userModel.findOne({ _id: session.userId }, next);
  2548. },
  2549. (user, next) => {
  2550. if (!user) return next("Not logged in.");
  2551. if (!user.services.password || !user.services.password.password)
  2552. return next("You can't remove GitHub login without having password login.");
  2553. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  2554. }
  2555. ],
  2556. async err => {
  2557. if (err && err !== true) {
  2558. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2559. this.log(
  2560. "ERROR",
  2561. "UNLINK_GITHUB",
  2562. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  2563. );
  2564. return cb({ status: "error", message: err });
  2565. }
  2566. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  2567. CacheModule.runJob("PUB", {
  2568. channel: "user.unlinkGithub",
  2569. value: session.userId
  2570. });
  2571. CacheModule.runJob("PUB", {
  2572. channel: "user.updated",
  2573. value: { userId: session.userId }
  2574. });
  2575. return cb({
  2576. status: "success",
  2577. message: "Successfully unlinked GitHub."
  2578. });
  2579. }
  2580. );
  2581. }),
  2582. /**
  2583. * Requests a password reset for an email
  2584. *
  2585. * @param {object} session - the session object automatically added by the websocket
  2586. * @param {string} email - the email of the user that requests a password reset
  2587. * @param {Function} cb - gets called with the result
  2588. */
  2589. async requestPasswordReset(session, email, cb) {
  2590. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2591. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2592. const resetPasswordRequestSchema = await MailModule.runJob(
  2593. "GET_SCHEMA",
  2594. { schemaName: "resetPasswordRequest" },
  2595. this
  2596. );
  2597. async.waterfall(
  2598. [
  2599. next => {
  2600. if (!email || typeof email !== "string") return next("Invalid email.");
  2601. email = email.toLowerCase();
  2602. return userModel.findOne({ "email.address": email }, next);
  2603. },
  2604. (user, next) => {
  2605. if (!user) return next("User not found.");
  2606. if (!user.services.password || !user.services.password.password)
  2607. return next("User does not have a password set, and probably uses GitHub to log in.");
  2608. return next(null, user);
  2609. },
  2610. (user, next) => {
  2611. const expires = new Date();
  2612. expires.setDate(expires.getDate() + 1);
  2613. userModel.findOneAndUpdate(
  2614. { "email.address": email },
  2615. {
  2616. $set: {
  2617. "services.password.reset": {
  2618. code,
  2619. expires
  2620. }
  2621. }
  2622. },
  2623. { runValidators: true },
  2624. next
  2625. );
  2626. },
  2627. (user, next) => {
  2628. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2629. }
  2630. ],
  2631. async err => {
  2632. if (err && err !== true) {
  2633. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2634. this.log(
  2635. "ERROR",
  2636. "REQUEST_PASSWORD_RESET",
  2637. `Email '${email}' failed to request password reset. '${err}'`
  2638. );
  2639. return cb({ status: "error", message: err });
  2640. }
  2641. this.log(
  2642. "SUCCESS",
  2643. "REQUEST_PASSWORD_RESET",
  2644. `Email '${email}' successfully requested a password reset.`
  2645. );
  2646. return cb({
  2647. status: "success",
  2648. message: "Successfully requested password reset."
  2649. });
  2650. }
  2651. );
  2652. },
  2653. /**
  2654. * Requests a password reset for a a user as an admin
  2655. *
  2656. * @param {object} session - the session object automatically added by the websocket
  2657. * @param {string} email - the email of the user for which the password reset is intended
  2658. * @param {Function} cb - gets called with the result
  2659. */
  2660. adminRequestPasswordReset: useHasPermission(
  2661. "users.requestPasswordReset",
  2662. async function adminRequestPasswordReset(session, userId, cb) {
  2663. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2664. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2665. const resetPasswordRequestSchema = await MailModule.runJob(
  2666. "GET_SCHEMA",
  2667. { schemaName: "resetPasswordRequest" },
  2668. this
  2669. );
  2670. async.waterfall(
  2671. [
  2672. next => userModel.findOne({ _id: userId }, next),
  2673. (user, next) => {
  2674. if (!user) return next("User not found.");
  2675. if (!user.services.password || !user.services.password.password)
  2676. return next("User does not have a password set, and probably uses GitHub to log in.");
  2677. return next();
  2678. },
  2679. next => {
  2680. const expires = new Date();
  2681. expires.setDate(expires.getDate() + 1);
  2682. userModel.findOneAndUpdate(
  2683. { _id: userId },
  2684. {
  2685. $set: {
  2686. "services.password.reset": {
  2687. code,
  2688. expires
  2689. }
  2690. }
  2691. },
  2692. { runValidators: true },
  2693. next
  2694. );
  2695. },
  2696. (user, next) => {
  2697. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2698. }
  2699. ],
  2700. async err => {
  2701. if (err && err !== true) {
  2702. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2703. this.log(
  2704. "ERROR",
  2705. "ADMINREQUEST_PASSWORD_RESET",
  2706. `User '${userId}' failed to get a password reset. '${err}'`
  2707. );
  2708. return cb({ status: "error", message: err });
  2709. }
  2710. this.log(
  2711. "SUCCESS",
  2712. "ADMIN_REQUEST_PASSWORD_RESET",
  2713. `User '${userId}' successfully got sent a password reset.`
  2714. );
  2715. return cb({
  2716. status: "success",
  2717. message: "Successfully requested password reset for user."
  2718. });
  2719. }
  2720. );
  2721. }
  2722. ),
  2723. /**
  2724. * Verifies a reset code
  2725. *
  2726. * @param {object} session - the session object automatically added by the websocket
  2727. * @param {string} code - the password reset code
  2728. * @param {Function} cb - gets called with the result
  2729. */
  2730. async verifyPasswordResetCode(session, code, cb) {
  2731. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2732. async.waterfall(
  2733. [
  2734. next => {
  2735. if (!code || typeof code !== "string") return next("Invalid code.");
  2736. return userModel.findOne({ "services.password.reset.code": code }, next);
  2737. },
  2738. (user, next) => {
  2739. if (!user) return next("Invalid code.");
  2740. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2741. return next(null);
  2742. }
  2743. ],
  2744. async err => {
  2745. if (err && err !== true) {
  2746. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2747. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  2748. return cb({ status: "error", message: err });
  2749. }
  2750. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  2751. return cb({
  2752. status: "success",
  2753. message: "Successfully verified password reset code."
  2754. });
  2755. }
  2756. );
  2757. },
  2758. /**
  2759. * Changes a user's password with a reset code
  2760. *
  2761. * @param {object} session - the session object automatically added by the websocket
  2762. * @param {string} code - the password reset code
  2763. * @param {string} newPassword - the new password reset code
  2764. * @param {Function} cb - gets called with the result
  2765. */
  2766. async changePasswordWithResetCode(session, code, newPassword, cb) {
  2767. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2768. async.waterfall(
  2769. [
  2770. next => {
  2771. if (!code || typeof code !== "string") return next("Invalid code.");
  2772. return userModel.findOne({ "services.password.reset.code": code }, next);
  2773. },
  2774. (user, next) => {
  2775. if (!user) return next("Invalid code.");
  2776. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2777. return next();
  2778. },
  2779. next => {
  2780. if (!DBModule.passwordValid(newPassword))
  2781. return next("Invalid password. Check if it meets all the requirements.");
  2782. return next();
  2783. },
  2784. next => {
  2785. bcrypt.genSalt(10, next);
  2786. },
  2787. // hash the password
  2788. (salt, next) => {
  2789. bcrypt.hash(sha256(newPassword), salt, next);
  2790. },
  2791. (hashedPassword, next) => {
  2792. userModel.updateOne(
  2793. { "services.password.reset.code": code },
  2794. {
  2795. $set: {
  2796. "services.password.password": hashedPassword
  2797. },
  2798. $unset: { "services.password.reset": "" }
  2799. },
  2800. { runValidators: true },
  2801. next
  2802. );
  2803. }
  2804. ],
  2805. async err => {
  2806. if (err && err !== true) {
  2807. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2808. this.log(
  2809. "ERROR",
  2810. "CHANGE_PASSWORD_WITH_RESET_CODE",
  2811. `Code '${code}' failed to change password. '${err}'`
  2812. );
  2813. return cb({ status: "error", message: err });
  2814. }
  2815. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  2816. return cb({
  2817. status: "success",
  2818. message: "Successfully changed password."
  2819. });
  2820. }
  2821. );
  2822. },
  2823. /**
  2824. * Resends the verify email email
  2825. *
  2826. * @param {object} session - the session object automatically added by the websocket
  2827. * @param {string} userId - the user id of the person to resend the email to
  2828. * @param {Function} cb - gets called with the result
  2829. */
  2830. resendVerifyEmail: useHasPermission(
  2831. "users.resendVerifyEmail",
  2832. async function resendVerifyEmail(session, userId, cb) {
  2833. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2834. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  2835. async.waterfall(
  2836. [
  2837. next => userModel.findOne({ _id: userId }, next),
  2838. (user, next) => {
  2839. if (!user) return next("User not found.");
  2840. if (user.email.verified) return next("The user's email is already verified.");
  2841. return next(null, user);
  2842. },
  2843. (user, next) => {
  2844. verifyEmailSchema(user.email.address, user.username, user.email.verificationToken, err => {
  2845. next(err);
  2846. });
  2847. }
  2848. ],
  2849. async err => {
  2850. if (err && err !== true) {
  2851. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2852. this.log(
  2853. "ERROR",
  2854. "RESEND_VERIFY_EMAIL",
  2855. `Couldn't resend verify email for user "${userId}". '${err}'`
  2856. );
  2857. return cb({ status: "error", message: err });
  2858. }
  2859. this.log("SUCCESS", "RESEND_VERIFY_EMAIL", `Resent verify email for user "${userId}".`);
  2860. return cb({
  2861. status: "success",
  2862. message: "Email resent successfully."
  2863. });
  2864. }
  2865. );
  2866. }
  2867. ),
  2868. /**
  2869. * Bans a user by userId
  2870. *
  2871. * @param {object} session - the session object automatically added by the websocket
  2872. * @param {string} value - the user id that is going to be banned
  2873. * @param {string} reason - the reason for the ban
  2874. * @param {string} expiresAt - the time the ban expires
  2875. * @param {Function} cb - gets called with the result
  2876. */
  2877. banUserById: useHasPermission("users.ban", function banUserById(session, userId, reason, expiresAt, cb) {
  2878. async.waterfall(
  2879. [
  2880. next => {
  2881. if (!userId) return next("You must provide a userId to ban.");
  2882. if (!reason) return next("You must provide a reason for the ban.");
  2883. return next();
  2884. },
  2885. next => {
  2886. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  2887. const date = new Date();
  2888. switch (expiresAt) {
  2889. case "1h":
  2890. expiresAt = date.setHours(date.getHours() + 1);
  2891. break;
  2892. case "12h":
  2893. expiresAt = date.setHours(date.getHours() + 12);
  2894. break;
  2895. case "1d":
  2896. expiresAt = date.setDate(date.getDate() + 1);
  2897. break;
  2898. case "1w":
  2899. expiresAt = date.setDate(date.getDate() + 7);
  2900. break;
  2901. case "1m":
  2902. expiresAt = date.setMonth(date.getMonth() + 1);
  2903. break;
  2904. case "3m":
  2905. expiresAt = date.setMonth(date.getMonth() + 3);
  2906. break;
  2907. case "6m":
  2908. expiresAt = date.setMonth(date.getMonth() + 6);
  2909. break;
  2910. case "1y":
  2911. expiresAt = date.setFullYear(date.getFullYear() + 1);
  2912. break;
  2913. case "never":
  2914. expiresAt = new Date(3093527980800000);
  2915. break;
  2916. default:
  2917. return next("Invalid expire date.");
  2918. }
  2919. return next();
  2920. },
  2921. next => {
  2922. PunishmentsModule.runJob(
  2923. "ADD_PUNISHMENT",
  2924. {
  2925. type: "banUserId",
  2926. value: userId,
  2927. reason,
  2928. expiresAt,
  2929. punishedBy: session.userId
  2930. },
  2931. this
  2932. )
  2933. .then(punishment => next(null, punishment))
  2934. .catch(next);
  2935. },
  2936. (punishment, next) => {
  2937. CacheModule.runJob("PUB", {
  2938. channel: "user.ban",
  2939. value: { userId, punishment }
  2940. });
  2941. next();
  2942. }
  2943. ],
  2944. async err => {
  2945. if (err && err !== true) {
  2946. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2947. this.log(
  2948. "ERROR",
  2949. "BAN_USER_BY_ID",
  2950. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2951. );
  2952. return cb({ status: "error", message: err });
  2953. }
  2954. this.log(
  2955. "SUCCESS",
  2956. "BAN_USER_BY_ID",
  2957. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2958. );
  2959. return cb({
  2960. status: "success",
  2961. message: "Successfully banned user."
  2962. });
  2963. }
  2964. );
  2965. }),
  2966. /**
  2967. * Search for a user by username or name
  2968. *
  2969. * @param {object} session - the session object automatically added by the websocket
  2970. * @param {string} query - the query
  2971. * @param {string} page - page
  2972. * @param {Function} cb - gets called with the result
  2973. */
  2974. search: isLoginRequired(async function search(session, query, page, cb) {
  2975. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2976. async.waterfall(
  2977. [
  2978. next => {
  2979. if ((!query && query !== "") || typeof query !== "string") next("Invalid query.");
  2980. else next();
  2981. },
  2982. next => {
  2983. const findQuery = {
  2984. $or: [{ name: new RegExp(`${query}`, "i"), username: new RegExp(`${query}`, "i") }]
  2985. };
  2986. const pageSize = 15;
  2987. const skipAmount = pageSize * (page - 1);
  2988. userModel.find(findQuery).count((err, count) => {
  2989. if (err) next(err);
  2990. else {
  2991. userModel
  2992. .find(findQuery, { _id: true, name: true, username: true, avatar: true })
  2993. .skip(skipAmount)
  2994. .limit(pageSize)
  2995. .exec((err, users) => {
  2996. if (err) next(err);
  2997. else {
  2998. next(null, {
  2999. users,
  3000. page,
  3001. pageSize,
  3002. skipAmount,
  3003. count
  3004. });
  3005. }
  3006. });
  3007. }
  3008. });
  3009. }
  3010. ],
  3011. async (err, data) => {
  3012. if (err) {
  3013. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  3014. this.log("ERROR", "USERS_SEARCH", `Searching users failed. "${err}"`);
  3015. return cb({ status: "error", message: err });
  3016. }
  3017. this.log("SUCCESS", "USERS_SEARCH", "Searching users successful.");
  3018. return cb({ status: "success", data });
  3019. }
  3020. );
  3021. })
  3022. };