users.js 89 KB

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