users.js 79 KB

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