users.js 92 KB

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