users.js 83 KB

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