users.js 89 KB

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