users.js 91 KB

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