users.js 92 KB

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