users.js 89 KB

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