users.js 75 KB

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