users.js 82 KB

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