users.js 86 KB

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