users.js 80 KB

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