users.js 81 KB

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