users.js 89 KB

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