users.js 92 KB

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