users.js 89 KB

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