users.js 92 KB

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