users.js 81 KB

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