users.js 80 KB

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