users.js 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762
  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: "",
  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. user.avatar = {
  630. type: "initials",
  631. color: "blue",
  632. url
  633. };
  634. next(null, user);
  635. });
  636. },
  637. // save the new user to the database
  638. (user, next) => {
  639. userModel.create(user, next);
  640. },
  641. // respond with the new user
  642. (user, next) => {
  643. verifyEmailSchema(email, username, verificationToken, err => {
  644. next(err, user._id);
  645. });
  646. },
  647. // create a liked songs playlist for the new user
  648. (userId, next) => {
  649. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  650. userId,
  651. displayName: "Liked Songs",
  652. type: "user"
  653. })
  654. .then(likedSongsPlaylist => {
  655. next(null, likedSongsPlaylist, userId);
  656. })
  657. .catch(err => next(err));
  658. },
  659. // create a disliked songs playlist for the new user
  660. (likedSongsPlaylist, userId, next) => {
  661. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  662. userId,
  663. displayName: "Disliked Songs",
  664. type: "user"
  665. })
  666. .then(dislikedSongsPlaylist => {
  667. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  668. })
  669. .catch(err => next(err));
  670. },
  671. // associate liked + disliked songs playlist to the user object
  672. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  673. userModel.updateOne(
  674. { _id: userId },
  675. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  676. { runValidators: true },
  677. err => {
  678. if (err) return next(err);
  679. return next(null, userId);
  680. }
  681. );
  682. }
  683. ],
  684. async (err, userId) => {
  685. if (err && err !== true) {
  686. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  687. this.log(
  688. "ERROR",
  689. "USER_PASSWORD_REGISTER",
  690. `Register failed with password for user "${username}"."${err}"`
  691. );
  692. return cb({ status: "error", message: err });
  693. }
  694. ActivitiesModule.runJob("ADD_ACTIVITY", {
  695. userId,
  696. type: "user__joined",
  697. payload: { message: "Welcome to Musare!" }
  698. });
  699. this.log(
  700. "SUCCESS",
  701. "USER_PASSWORD_REGISTER",
  702. `Register successful with password for user "${username}".`
  703. );
  704. const res = await this.module.runJob(
  705. "RUN_ACTION2",
  706. {
  707. session,
  708. namespace: "users",
  709. action: "login",
  710. args: [email, password]
  711. },
  712. this
  713. );
  714. const obj = {
  715. status: "success",
  716. message: "Successfully registered."
  717. };
  718. if (res.status === "success") {
  719. obj.SID = res.data.SID;
  720. }
  721. return cb(obj);
  722. }
  723. );
  724. },
  725. /**
  726. * Logs out a user
  727. *
  728. * @param {object} session - the session object automatically added by the websocket
  729. * @param {Function} cb - gets called with the result
  730. */
  731. logout(session, cb) {
  732. async.waterfall(
  733. [
  734. next => {
  735. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }, this)
  736. .then(session => next(null, session))
  737. .catch(next);
  738. },
  739. (session, next) => {
  740. if (!session) return next("Session not found");
  741. return next(null, session);
  742. },
  743. (session, next) => {
  744. CacheModule.runJob("PUB", {
  745. channel: "user.removeSessions",
  746. value: session.userId
  747. });
  748. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  749. setTimeout(() => {
  750. CacheModule.runJob("HDEL", { table: "sessions", key: session.sessionId }, this)
  751. .then(() => next())
  752. .catch(next);
  753. }, 50);
  754. }
  755. ],
  756. async err => {
  757. if (err && err !== true) {
  758. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  759. this.log("ERROR", "USER_LOGOUT", `Logout failed. "${err}" `);
  760. return cb({ status: "error", message: err });
  761. }
  762. this.log("SUCCESS", "USER_LOGOUT", `Logout successful.`);
  763. return cb({
  764. status: "success",
  765. message: "Successfully logged out."
  766. });
  767. }
  768. );
  769. },
  770. /**
  771. * Checks if user's password is correct (e.g. before a sensitive action)
  772. *
  773. * @param {object} session - the session object automatically added by the websocket
  774. * @param {string} password - the password the user entered that we need to validate
  775. * @param {Function} cb - gets called with the result
  776. */
  777. confirmPasswordMatch: isLoginRequired(async function confirmPasswordMatch(session, password, cb) {
  778. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  779. return async.waterfall(
  780. [
  781. next => {
  782. if (!password || password === "") return next("Please provide a valid password.");
  783. return next();
  784. },
  785. next => {
  786. userModel.findOne({ _id: session.userId }, (err, user) =>
  787. next(err, user.services.password.password)
  788. );
  789. },
  790. (passwordHash, next) => {
  791. if (!passwordHash) return next("Your account doesn't have a password linked.");
  792. return bcrypt.compare(sha256(password), passwordHash, (err, match) => {
  793. if (err) return next(err);
  794. if (!match) return next(null, false);
  795. return next(null, true);
  796. });
  797. }
  798. ],
  799. async (err, match) => {
  800. if (err) {
  801. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  802. this.log(
  803. "ERROR",
  804. "USER_CONFIRM_PASSWORD",
  805. `Couldn't confirm password for user "${session.userId}". "${err}"`
  806. );
  807. return cb({ status: "error", message: err });
  808. }
  809. if (match) {
  810. this.log(
  811. "SUCCESS",
  812. "USER_CONFIRM_PASSWORD",
  813. `Successfully checked for password match (it matched) for user "${session.userId}".`
  814. );
  815. return cb({
  816. status: "success",
  817. message: "Your password matches."
  818. });
  819. }
  820. this.log(
  821. "SUCCESS",
  822. "USER_CONFIRM_PASSWORD",
  823. `Successfully checked for password match (it didn't match) for user "${session.userId}".`
  824. );
  825. return cb({
  826. status: "error",
  827. message: "Unfortunately your password doesn't match."
  828. });
  829. }
  830. );
  831. }),
  832. /**
  833. * Checks if user's github access token has expired or not (ie. if their github account is still linked)
  834. *
  835. * @param {object} session - the session object automatically added by the websocket
  836. * @param {Function} cb - gets called with the result
  837. */
  838. confirmGithubLink: isLoginRequired(async function confirmGithubLink(session, cb) {
  839. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  840. return async.waterfall(
  841. [
  842. next => {
  843. userModel.findOne({ _id: session.userId }, (err, user) => next(err, user));
  844. },
  845. (user, next) => {
  846. if (!user.services.github) return next("You don't have GitHub linked to your account.");
  847. return axios
  848. .get(`https://api.github.com/user/emails`, {
  849. headers: {
  850. "User-Agent": "request",
  851. Authorization: `token ${user.services.github.access_token}`
  852. }
  853. })
  854. .then(res => next(null, res))
  855. .catch(err => next(err));
  856. },
  857. (res, next) => next(null, res.status === 200)
  858. ],
  859. async (err, linked) => {
  860. if (err) {
  861. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  862. this.log(
  863. "ERROR",
  864. "USER_CONFIRM_GITHUB_LINK",
  865. `Couldn't confirm github link for user "${session.userId}". "${err}"`
  866. );
  867. return cb({ status: "error", message: err });
  868. }
  869. this.log(
  870. "SUCCESS",
  871. "USER_CONFIRM_GITHUB_LINK",
  872. `GitHub is ${linked ? "linked" : "not linked"} for user "${session.userId}".`
  873. );
  874. return cb({
  875. status: "success",
  876. data: { linked },
  877. message: "Successfully checked if GitHub accounty was linked."
  878. });
  879. }
  880. );
  881. }),
  882. /**
  883. * Removes all sessions for a user
  884. *
  885. * @param {object} session - the session object automatically added by the websocket
  886. * @param {string} userId - the id of the user we are trying to delete the sessions of
  887. * @param {Function} cb - gets called with the result
  888. */
  889. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  890. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  891. async.waterfall(
  892. [
  893. next => {
  894. userModel.findOne({ _id: session.userId }, (err, user) => {
  895. if (err) return next(err);
  896. if (user.role !== "admin" && session.userId !== userId)
  897. return next("Only admins and the owner of the account can remove their sessions.");
  898. return next();
  899. });
  900. },
  901. next => {
  902. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  903. .then(sessions => {
  904. next(null, sessions);
  905. })
  906. .catch(next);
  907. },
  908. (sessions, next) => {
  909. if (!sessions) return next("There are no sessions for this user to remove.");
  910. const keys = Object.keys(sessions);
  911. return next(null, keys, sessions);
  912. },
  913. (keys, sessions, next) => {
  914. CacheModule.runJob("PUB", {
  915. channel: "user.removeSessions",
  916. value: userId
  917. });
  918. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  919. setTimeout(
  920. () =>
  921. async.each(
  922. keys,
  923. (sessionId, callback) => {
  924. const session = sessions[sessionId];
  925. if (session.userId === userId) {
  926. // TODO Also maybe add this to this runJob
  927. CacheModule.runJob("HDEL", {
  928. table: "sessions",
  929. key: sessionId
  930. })
  931. .then(() => callback(null))
  932. .catch(callback);
  933. }
  934. },
  935. err => {
  936. next(err);
  937. }
  938. ),
  939. 50
  940. );
  941. }
  942. ],
  943. async err => {
  944. if (err) {
  945. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  946. this.log(
  947. "ERROR",
  948. "REMOVE_SESSIONS_FOR_USER",
  949. `Couldn't remove all sessions for user "${userId}". "${err}"`
  950. );
  951. return cb({ status: "error", message: err });
  952. }
  953. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  954. return cb({
  955. status: "success",
  956. message: "Successfully removed all sessions."
  957. });
  958. }
  959. );
  960. }),
  961. /**
  962. * Updates the order of a user's favorite stations
  963. *
  964. * @param {object} session - the session object automatically added by the websocket
  965. * @param {Array} favoriteStations - array of station ids (with a specific order)
  966. * @param {Function} cb - gets called with the result
  967. */
  968. updateOrderOfFavoriteStations: isLoginRequired(async function updateOrderOfFavoriteStations(
  969. session,
  970. favoriteStations,
  971. cb
  972. ) {
  973. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  974. async.waterfall(
  975. [
  976. next => {
  977. userModel.updateOne(
  978. { _id: session.userId },
  979. { $set: { favoriteStations } },
  980. { runValidators: true },
  981. next
  982. );
  983. }
  984. ],
  985. async err => {
  986. if (err) {
  987. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  988. this.log(
  989. "ERROR",
  990. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  991. `Couldn't update order of favorite stations for user "${session.userId}" to "${favoriteStations}". "${err}"`
  992. );
  993. return cb({ status: "error", message: err });
  994. }
  995. CacheModule.runJob("PUB", {
  996. channel: "user.updateOrderOfFavoriteStations",
  997. value: {
  998. favoriteStations,
  999. userId: session.userId
  1000. }
  1001. });
  1002. this.log(
  1003. "SUCCESS",
  1004. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  1005. `Updated order of favorite stations for user "${session.userId}" to "${favoriteStations}".`
  1006. );
  1007. return cb({
  1008. status: "success",
  1009. message: "Order of favorite stations successfully updated"
  1010. });
  1011. }
  1012. );
  1013. }),
  1014. /**
  1015. * Updates the order of a user's playlists
  1016. *
  1017. * @param {object} session - the session object automatically added by the websocket
  1018. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  1019. * @param {Function} cb - gets called with the result
  1020. */
  1021. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  1022. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1023. async.waterfall(
  1024. [
  1025. next => {
  1026. userModel.updateOne(
  1027. { _id: session.userId },
  1028. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  1029. { runValidators: true },
  1030. next
  1031. );
  1032. }
  1033. ],
  1034. async err => {
  1035. if (err) {
  1036. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1037. this.log(
  1038. "ERROR",
  1039. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1040. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  1041. );
  1042. return cb({ status: "error", message: err });
  1043. }
  1044. CacheModule.runJob("PUB", {
  1045. channel: "user.updateOrderOfPlaylists",
  1046. value: {
  1047. orderOfPlaylists,
  1048. userId: session.userId
  1049. }
  1050. });
  1051. this.log(
  1052. "SUCCESS",
  1053. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  1054. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  1055. );
  1056. return cb({
  1057. status: "success",
  1058. message: "Order of playlists successfully updated"
  1059. });
  1060. }
  1061. );
  1062. }),
  1063. /**
  1064. * Updates a user's preferences
  1065. *
  1066. * @param {object} session - the session object automatically added by the websocket
  1067. * @param {object} preferences - object containing preferences
  1068. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  1069. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  1070. * @param {boolean} preferences.activityLogPublic - whether or not a user's activity log can be publicly viewed
  1071. * @param {boolean} preferences.anonymousSongRequests - whether or not a user's requested songs will be anonymous
  1072. * @param {boolean} preferences.activityWatch - whether or not a user is using the ActivityWatch integration
  1073. * @param {Function} cb - gets called with the result
  1074. */
  1075. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  1076. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1077. async.waterfall(
  1078. [
  1079. next => {
  1080. const $set = {};
  1081. Object.keys(preferences).forEach(preference => {
  1082. $set[`preferences.${preference}`] = preferences[preference];
  1083. });
  1084. return next(null, $set);
  1085. },
  1086. ($set, next) => {
  1087. userModel.findByIdAndUpdate(session.userId, { $set }, { new: false, upsert: true }, next);
  1088. }
  1089. ],
  1090. async (err, user) => {
  1091. if (err) {
  1092. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1093. this.log(
  1094. "ERROR",
  1095. "UPDATE_USER_PREFERENCES",
  1096. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  1097. preferences
  1098. )}". "${err}"`
  1099. );
  1100. return cb({ status: "error", message: err });
  1101. }
  1102. CacheModule.runJob("PUB", {
  1103. channel: "user.updatePreferences",
  1104. value: {
  1105. preferences,
  1106. userId: session.userId
  1107. }
  1108. });
  1109. if (preferences.nightmode !== undefined && preferences.nightmode !== user.preferences.nightmode)
  1110. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1111. userId: session.userId,
  1112. type: "user__toggle_nightmode",
  1113. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  1114. });
  1115. if (
  1116. preferences.autoSkipDisliked !== undefined &&
  1117. preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked
  1118. )
  1119. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1120. userId: session.userId,
  1121. type: "user__toggle_autoskip_disliked_songs",
  1122. payload: {
  1123. message: preferences.autoSkipDisliked
  1124. ? "Enabled the autoskipping of disliked songs"
  1125. : "Disabled the autoskipping of disliked songs"
  1126. }
  1127. });
  1128. if (
  1129. preferences.activityWatch !== undefined &&
  1130. preferences.activityWatch !== user.preferences.activityWatch
  1131. )
  1132. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1133. userId: session.userId,
  1134. type: "user__toggle_activity_watch",
  1135. payload: {
  1136. message: preferences.activityWatch
  1137. ? "Enabled ActivityWatch integration"
  1138. : "Disabled ActivityWatch integration"
  1139. }
  1140. });
  1141. this.log(
  1142. "SUCCESS",
  1143. "UPDATE_USER_PREFERENCES",
  1144. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  1145. );
  1146. return cb({
  1147. status: "success",
  1148. message: "Preferences successfully updated"
  1149. });
  1150. }
  1151. );
  1152. }),
  1153. /**
  1154. * Retrieves a user's preferences
  1155. *
  1156. * @param {object} session - the session object automatically added by the websocket
  1157. * @param {Function} cb - gets called with the result
  1158. */
  1159. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  1160. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1161. async.waterfall(
  1162. [
  1163. next => {
  1164. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  1165. }
  1166. ],
  1167. async (err, { preferences }) => {
  1168. if (err) {
  1169. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1170. this.log(
  1171. "ERROR",
  1172. "GET_USER_PREFERENCES",
  1173. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  1174. );
  1175. return cb({ status: "error", message: err });
  1176. }
  1177. this.log(
  1178. "SUCCESS",
  1179. "GET_USER_PREFERENCES",
  1180. `Successfully obtained preferences for user "${session.userId}".`
  1181. );
  1182. return cb({
  1183. status: "success",
  1184. message: "Preferences successfully retrieved",
  1185. data: { preferences }
  1186. });
  1187. }
  1188. );
  1189. }),
  1190. /**
  1191. * Gets user object from username (only a few properties)
  1192. *
  1193. * @param {object} session - the session object automatically added by the websocket
  1194. * @param {string} username - the username of the user we are trying to find
  1195. * @param {Function} cb - gets called with the result
  1196. */
  1197. findByUsername: async function findByUsername(session, username, cb) {
  1198. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1199. async.waterfall(
  1200. [
  1201. next => {
  1202. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  1203. },
  1204. (account, next) => {
  1205. if (!account) return next("User not found.");
  1206. return next(null, account);
  1207. }
  1208. ],
  1209. async (err, account) => {
  1210. if (err && err !== true) {
  1211. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1212. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  1213. return cb({ status: "error", message: err });
  1214. }
  1215. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  1216. return cb({
  1217. status: "success",
  1218. data: {
  1219. _id: account._id,
  1220. name: account.name,
  1221. username: account.username,
  1222. location: account.location,
  1223. bio: account.bio,
  1224. role: account.role,
  1225. avatar: account.avatar,
  1226. createdAt: account.createdAt
  1227. }
  1228. });
  1229. }
  1230. );
  1231. },
  1232. /**
  1233. * Gets a username from an userId
  1234. *
  1235. * @param {object} session - the session object automatically added by the websocket
  1236. * @param {string} userId - the userId of the person we are trying to get the username from
  1237. * @param {Function} cb - gets called with the result
  1238. */
  1239. async getUsernameFromId(session, userId, cb) {
  1240. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1241. userModel
  1242. .findById(userId)
  1243. .then(user => {
  1244. if (user) {
  1245. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  1246. return cb({
  1247. status: "success",
  1248. data: { username: user.username }
  1249. });
  1250. }
  1251. this.log(
  1252. "ERROR",
  1253. "GET_USERNAME_FROM_ID",
  1254. `Getting the username from userId "${userId}" failed. User not found.`
  1255. );
  1256. return cb({
  1257. status: "error",
  1258. message: "Couldn't find the user."
  1259. });
  1260. })
  1261. .catch(async err => {
  1262. if (err && err !== true) {
  1263. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1264. this.log(
  1265. "ERROR",
  1266. "GET_USERNAME_FROM_ID",
  1267. `Getting the username from userId "${userId}" failed. "${err}"`
  1268. );
  1269. cb({ status: "error", message: err });
  1270. }
  1271. });
  1272. },
  1273. /**
  1274. * Gets a user from a userId
  1275. *
  1276. * @param {object} session - the session object automatically added by the websocket
  1277. * @param {string} userId - the userId of the person we are trying to get the username from
  1278. * @param {Function} cb - gets called with the result
  1279. */
  1280. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  1281. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1282. userModel
  1283. .findById(userId)
  1284. .then(user => {
  1285. if (user) {
  1286. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  1287. return cb({
  1288. status: "success",
  1289. data: {
  1290. _id: user._id,
  1291. username: user.username,
  1292. role: user.role,
  1293. liked: user.liked,
  1294. disliked: user.disliked,
  1295. songsRequested: user.statistics.songsRequested,
  1296. email: {
  1297. address: user.email.address,
  1298. verified: user.email.verified
  1299. },
  1300. hasPassword: !!user.services.password,
  1301. services: { github: user.services.github }
  1302. }
  1303. });
  1304. }
  1305. this.log(
  1306. "ERROR",
  1307. "GET_USER_FROM_ID",
  1308. `Getting the user from userId "${userId}" failed. User not found.`
  1309. );
  1310. return cb({
  1311. status: "error",
  1312. message: "Couldn't find the user."
  1313. });
  1314. })
  1315. .catch(async err => {
  1316. if (err && err !== true) {
  1317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1318. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  1319. cb({ status: "error", message: err });
  1320. }
  1321. });
  1322. }),
  1323. /**
  1324. * Gets user info from session
  1325. *
  1326. * @param {object} session - the session object automatically added by the websocket
  1327. * @param {Function} cb - gets called with the result
  1328. */
  1329. findBySession: isLoginRequired(async function findBySession(session, cb) {
  1330. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1331. async.waterfall(
  1332. [
  1333. next => {
  1334. CacheModule.runJob(
  1335. "HGET",
  1336. {
  1337. table: "sessions",
  1338. key: session.sessionId
  1339. },
  1340. this
  1341. )
  1342. .then(session => next(null, session))
  1343. .catch(next);
  1344. },
  1345. (session, next) => {
  1346. if (!session) return next("Session not found.");
  1347. return next(null, session);
  1348. },
  1349. (session, next) => {
  1350. userModel.findOne({ _id: session.userId }, next);
  1351. },
  1352. (user, next) => {
  1353. if (!user) return next("User not found.");
  1354. return next(null, user);
  1355. }
  1356. ],
  1357. async (err, user) => {
  1358. if (err && err !== true) {
  1359. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1360. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  1361. return cb({ status: "error", message: err });
  1362. }
  1363. const sanitisedUser = {
  1364. email: {
  1365. address: user.email.address
  1366. },
  1367. avatar: user.avatar,
  1368. username: user.username,
  1369. name: user.name,
  1370. location: user.location,
  1371. bio: user.bio
  1372. };
  1373. if (user.services.password && user.services.password.password) sanitisedUser.password = true;
  1374. if (user.services.github && user.services.github.id) sanitisedUser.github = true;
  1375. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  1376. return cb({
  1377. status: "success",
  1378. data: { user: sanitisedUser }
  1379. });
  1380. }
  1381. );
  1382. }),
  1383. /**
  1384. * Updates a user's username
  1385. *
  1386. * @param {object} session - the session object automatically added by the websocket
  1387. * @param {string} updatingUserId - the updating user's id
  1388. * @param {string} newUsername - the new username
  1389. * @param {Function} cb - gets called with the result
  1390. */
  1391. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  1392. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1393. async.waterfall(
  1394. [
  1395. next => {
  1396. if (updatingUserId === session.userId) return next(null, true);
  1397. return userModel.findOne({ _id: session.userId }, next);
  1398. },
  1399. (user, next) => {
  1400. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1401. return userModel.findOne({ _id: updatingUserId }, next);
  1402. },
  1403. (user, next) => {
  1404. if (!user) return next("User not found.");
  1405. if (user.username === newUsername)
  1406. return next("New username can't be the same as the old username.");
  1407. return next(null);
  1408. },
  1409. next => {
  1410. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1411. },
  1412. (user, next) => {
  1413. if (!user) return next();
  1414. if (user._id === updatingUserId) return next();
  1415. return next("That username is already in use.");
  1416. },
  1417. next => {
  1418. userModel.updateOne(
  1419. { _id: updatingUserId },
  1420. { $set: { username: newUsername } },
  1421. { runValidators: true },
  1422. next
  1423. );
  1424. }
  1425. ],
  1426. async err => {
  1427. if (err && err !== true) {
  1428. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1429. this.log(
  1430. "ERROR",
  1431. "UPDATE_USERNAME",
  1432. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1433. );
  1434. return cb({ status: "error", message: err });
  1435. }
  1436. CacheModule.runJob("PUB", {
  1437. channel: "user.updateUsername",
  1438. value: {
  1439. username: newUsername,
  1440. _id: updatingUserId
  1441. }
  1442. });
  1443. this.log(
  1444. "SUCCESS",
  1445. "UPDATE_USERNAME",
  1446. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1447. );
  1448. return cb({
  1449. status: "success",
  1450. message: "Username updated successfully"
  1451. });
  1452. }
  1453. );
  1454. }),
  1455. /**
  1456. * Updates a user's email
  1457. *
  1458. * @param {object} session - the session object automatically added by the websocket
  1459. * @param {string} updatingUserId - the updating user's id
  1460. * @param {string} newEmail - the new email
  1461. * @param {Function} cb - gets called with the result
  1462. */
  1463. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1464. newEmail = newEmail.toLowerCase();
  1465. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1466. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1467. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1468. async.waterfall(
  1469. [
  1470. next => {
  1471. if (updatingUserId === session.userId) return next(null, true);
  1472. return userModel.findOne({ _id: session.userId }, next);
  1473. },
  1474. (user, next) => {
  1475. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1476. return userModel.findOne({ _id: updatingUserId }, next);
  1477. },
  1478. (user, next) => {
  1479. if (!user) return next("User not found.");
  1480. if (user.email.address === newEmail)
  1481. return next("New email can't be the same as your the old email.");
  1482. return next();
  1483. },
  1484. next => {
  1485. userModel.findOne({ "email.address": newEmail }, next);
  1486. },
  1487. (user, next) => {
  1488. if (!user) return next();
  1489. if (user._id === updatingUserId) return next();
  1490. return next("That email is already in use.");
  1491. },
  1492. // regenerate the url for gravatar avatar
  1493. next => {
  1494. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1495. next(null, url);
  1496. });
  1497. },
  1498. (newAvatarUrl, next) => {
  1499. userModel.updateOne(
  1500. { _id: updatingUserId },
  1501. {
  1502. $set: {
  1503. "avatar.url": newAvatarUrl,
  1504. "email.address": newEmail,
  1505. "email.verified": false,
  1506. "email.verificationToken": verificationToken
  1507. }
  1508. },
  1509. { runValidators: true },
  1510. next
  1511. );
  1512. },
  1513. (res, next) => {
  1514. userModel.findOne({ _id: updatingUserId }, next);
  1515. },
  1516. (user, next) => {
  1517. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1518. next(err);
  1519. });
  1520. }
  1521. ],
  1522. async err => {
  1523. if (err && err !== true) {
  1524. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1525. this.log(
  1526. "ERROR",
  1527. "UPDATE_EMAIL",
  1528. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1529. );
  1530. return cb({ status: "error", message: err });
  1531. }
  1532. this.log(
  1533. "SUCCESS",
  1534. "UPDATE_EMAIL",
  1535. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1536. );
  1537. return cb({
  1538. status: "success",
  1539. message: "Email updated successfully."
  1540. });
  1541. }
  1542. );
  1543. }),
  1544. /**
  1545. * Updates a user's name
  1546. *
  1547. * @param {object} session - the session object automatically added by the websocket
  1548. * @param {string} updatingUserId - the updating user's id
  1549. * @param {string} newBio - the new name
  1550. * @param {Function} cb - gets called with the result
  1551. */
  1552. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1553. const userModel = await DBModule.runJob(
  1554. "GET_MODEL",
  1555. {
  1556. modelName: "user"
  1557. },
  1558. this
  1559. );
  1560. async.waterfall(
  1561. [
  1562. next => {
  1563. if (updatingUserId === session.userId) return next(null, true);
  1564. return userModel.findOne({ _id: session.userId }, next);
  1565. },
  1566. (user, next) => {
  1567. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1568. return userModel.findOne({ _id: updatingUserId }, next);
  1569. },
  1570. (user, next) => {
  1571. if (!user) return next("User not found.");
  1572. return userModel.updateOne(
  1573. { _id: updatingUserId },
  1574. { $set: { name: newName } },
  1575. { runValidators: true },
  1576. next
  1577. );
  1578. }
  1579. ],
  1580. async err => {
  1581. if (err && err !== true) {
  1582. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1583. this.log(
  1584. "ERROR",
  1585. "UPDATE_NAME",
  1586. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1587. );
  1588. return cb({ status: "error", message: err });
  1589. }
  1590. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1591. userId: updatingUserId,
  1592. type: "user__edit_name",
  1593. payload: { message: `Changed name to ${newName}` }
  1594. });
  1595. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1596. return cb({
  1597. status: "success",
  1598. message: "Name updated successfully"
  1599. });
  1600. }
  1601. );
  1602. }),
  1603. /**
  1604. * Updates a user's location
  1605. *
  1606. * @param {object} session - the session object automatically added by the websocket
  1607. * @param {string} updatingUserId - the updating user's id
  1608. * @param {string} newLocation - the new location
  1609. * @param {Function} cb - gets called with the result
  1610. */
  1611. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1612. const userModel = await DBModule.runJob(
  1613. "GET_MODEL",
  1614. {
  1615. modelName: "user"
  1616. },
  1617. this
  1618. );
  1619. async.waterfall(
  1620. [
  1621. next => {
  1622. if (updatingUserId === session.userId) return next(null, true);
  1623. return userModel.findOne({ _id: session.userId }, next);
  1624. },
  1625. (user, next) => {
  1626. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1627. return userModel.findOne({ _id: updatingUserId }, next);
  1628. },
  1629. (user, next) => {
  1630. if (!user) return next("User not found.");
  1631. return userModel.updateOne(
  1632. { _id: updatingUserId },
  1633. { $set: { location: newLocation } },
  1634. { runValidators: true },
  1635. next
  1636. );
  1637. }
  1638. ],
  1639. async err => {
  1640. if (err && err !== true) {
  1641. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1642. this.log(
  1643. "ERROR",
  1644. "UPDATE_LOCATION",
  1645. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1646. );
  1647. return cb({ status: "error", message: err });
  1648. }
  1649. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1650. userId: updatingUserId,
  1651. type: "user__edit_location",
  1652. payload: { message: `Changed location to ${newLocation}` }
  1653. });
  1654. this.log(
  1655. "SUCCESS",
  1656. "UPDATE_LOCATION",
  1657. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1658. );
  1659. return cb({
  1660. status: "success",
  1661. message: "Location updated successfully"
  1662. });
  1663. }
  1664. );
  1665. }),
  1666. /**
  1667. * Updates a user's bio
  1668. *
  1669. * @param {object} session - the session object automatically added by the websocket
  1670. * @param {string} updatingUserId - the updating user's id
  1671. * @param {string} newBio - the new bio
  1672. * @param {Function} cb - gets called with the result
  1673. */
  1674. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1675. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1676. async.waterfall(
  1677. [
  1678. next => {
  1679. if (updatingUserId === session.userId) return next(null, true);
  1680. return userModel.findOne({ _id: session.userId }, next);
  1681. },
  1682. (user, next) => {
  1683. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1684. return userModel.findOne({ _id: updatingUserId }, next);
  1685. },
  1686. (user, next) => {
  1687. if (!user) return next("User not found.");
  1688. return userModel.updateOne(
  1689. { _id: updatingUserId },
  1690. { $set: { bio: newBio } },
  1691. { runValidators: true },
  1692. next
  1693. );
  1694. }
  1695. ],
  1696. async err => {
  1697. if (err && err !== true) {
  1698. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1699. this.log(
  1700. "ERROR",
  1701. "UPDATE_BIO",
  1702. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1703. );
  1704. return cb({ status: "error", message: err });
  1705. }
  1706. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1707. userId: updatingUserId,
  1708. type: "user__edit_bio",
  1709. payload: { message: `Changed bio to ${newBio}` }
  1710. });
  1711. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1712. return cb({
  1713. status: "success",
  1714. message: "Bio updated successfully"
  1715. });
  1716. }
  1717. );
  1718. }),
  1719. /**
  1720. * Updates a user's avatar
  1721. *
  1722. * @param {object} session - the session object automatically added by the websocket
  1723. * @param {string} updatingUserId - the updating user's id
  1724. * @param {string} newAvatar - the new avatar object
  1725. * @param {Function} cb - gets called with the result
  1726. */
  1727. updateAvatar: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1728. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1729. async.waterfall(
  1730. [
  1731. next => {
  1732. if (updatingUserId === session.userId) return next(null, true);
  1733. return userModel.findOne({ _id: session.userId }, next);
  1734. },
  1735. (user, next) => {
  1736. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1737. return userModel.findOne({ _id: updatingUserId }, next);
  1738. },
  1739. (user, next) => {
  1740. if (!user) return next("User not found.");
  1741. return userModel.findOneAndUpdate(
  1742. { _id: updatingUserId },
  1743. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1744. { new: true, runValidators: true },
  1745. next
  1746. );
  1747. }
  1748. ],
  1749. async err => {
  1750. if (err && err !== true) {
  1751. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1752. this.log(
  1753. "ERROR",
  1754. "UPDATE_AVATAR",
  1755. `Couldn't update avatar for user "${updatingUserId}" to type "${newAvatar.type}" and color "${newAvatar.color}". "${err}"`
  1756. );
  1757. return cb({ status: "error", message: err });
  1758. }
  1759. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1760. userId: updatingUserId,
  1761. type: "user__edit_avatar",
  1762. payload: { message: `Changed avatar to use ${newAvatar.type} and ${newAvatar.color}` }
  1763. });
  1764. this.log(
  1765. "SUCCESS",
  1766. "UPDATE_AVATAR",
  1767. `Updated avatar for user "${updatingUserId}" to type "${newAvatar.type} and color ${newAvatar.color}".`
  1768. );
  1769. return cb({
  1770. status: "success",
  1771. message: "Avatar updated successfully"
  1772. });
  1773. }
  1774. );
  1775. }),
  1776. /**
  1777. * Updates a user's role
  1778. *
  1779. * @param {object} session - the session object automatically added by the websocket
  1780. * @param {string} updatingUserId - the updating user's id
  1781. * @param {string} newRole - the new role
  1782. * @param {Function} cb - gets called with the result
  1783. */
  1784. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1785. newRole = newRole.toLowerCase();
  1786. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1787. async.waterfall(
  1788. [
  1789. next => {
  1790. userModel.findOne({ _id: updatingUserId }, next);
  1791. },
  1792. (user, next) => {
  1793. if (!user) return next("User not found.");
  1794. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1795. return next();
  1796. },
  1797. next => {
  1798. userModel.updateOne(
  1799. { _id: updatingUserId },
  1800. { $set: { role: newRole } },
  1801. { runValidators: true },
  1802. next
  1803. );
  1804. }
  1805. ],
  1806. async err => {
  1807. if (err && err !== true) {
  1808. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1809. this.log(
  1810. "ERROR",
  1811. "UPDATE_ROLE",
  1812. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1813. );
  1814. return cb({ status: "error", message: err });
  1815. }
  1816. this.log(
  1817. "SUCCESS",
  1818. "UPDATE_ROLE",
  1819. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1820. );
  1821. return cb({
  1822. status: "success",
  1823. message: "Role successfully updated."
  1824. });
  1825. }
  1826. );
  1827. }),
  1828. /**
  1829. * Updates a user's password
  1830. *
  1831. * @param {object} session - the session object automatically added by the websocket
  1832. * @param {string} previousPassword - the previous password
  1833. * @param {string} newPassword - the new password
  1834. * @param {Function} cb - gets called with the result
  1835. */
  1836. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1837. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1838. async.waterfall(
  1839. [
  1840. next => {
  1841. userModel.findOne({ _id: session.userId }, next);
  1842. },
  1843. (user, next) => {
  1844. if (!user.services.password) return next("This account does not have a password set.");
  1845. return next(null, user.services.password.password);
  1846. },
  1847. (storedPassword, next) => {
  1848. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1849. if (res) return next();
  1850. return next("Please enter the correct previous password.");
  1851. });
  1852. },
  1853. next => {
  1854. if (!DBModule.passwordValid(newPassword))
  1855. return next("Invalid new password. Check if it meets all the requirements.");
  1856. return next();
  1857. },
  1858. next => {
  1859. bcrypt.genSalt(10, next);
  1860. },
  1861. // hash the password
  1862. (salt, next) => {
  1863. bcrypt.hash(sha256(newPassword), salt, next);
  1864. },
  1865. (hashedPassword, next) => {
  1866. userModel.updateOne(
  1867. { _id: session.userId },
  1868. {
  1869. $set: {
  1870. "services.password.password": hashedPassword
  1871. }
  1872. },
  1873. next
  1874. );
  1875. }
  1876. ],
  1877. async err => {
  1878. if (err) {
  1879. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1880. this.log(
  1881. "ERROR",
  1882. "UPDATE_PASSWORD",
  1883. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1884. );
  1885. return cb({ status: "error", message: err });
  1886. }
  1887. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1888. return cb({
  1889. status: "success",
  1890. message: "Password successfully updated."
  1891. });
  1892. }
  1893. );
  1894. }),
  1895. /**
  1896. * Requests a password for a session
  1897. *
  1898. * @param {object} session - the session object automatically added by the websocket
  1899. * @param {string} email - the email of the user that requests a password reset
  1900. * @param {Function} cb - gets called with the result
  1901. */
  1902. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1903. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1904. const passwordRequestSchema = await MailModule.runJob(
  1905. "GET_SCHEMA",
  1906. {
  1907. schemaName: "passwordRequest"
  1908. },
  1909. this
  1910. );
  1911. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1912. async.waterfall(
  1913. [
  1914. next => {
  1915. userModel.findOne({ _id: session.userId }, next);
  1916. },
  1917. (user, next) => {
  1918. if (!user) return next("User not found.");
  1919. if (user.services.password && user.services.password.password)
  1920. return next("You already have a password set.");
  1921. return next(null, user);
  1922. },
  1923. (user, next) => {
  1924. const expires = new Date();
  1925. expires.setDate(expires.getDate() + 1);
  1926. userModel.findOneAndUpdate(
  1927. { "email.address": user.email.address },
  1928. {
  1929. $set: {
  1930. "services.password": {
  1931. set: { code, expires }
  1932. }
  1933. }
  1934. },
  1935. { runValidators: true },
  1936. next
  1937. );
  1938. },
  1939. (user, next) => {
  1940. passwordRequestSchema(user.email.address, user.username, code, next);
  1941. }
  1942. ],
  1943. async err => {
  1944. if (err && err !== true) {
  1945. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1946. this.log(
  1947. "ERROR",
  1948. "REQUEST_PASSWORD",
  1949. `UserId '${session.userId}' failed to request password. '${err}'`
  1950. );
  1951. return cb({ status: "error", message: err });
  1952. }
  1953. this.log(
  1954. "SUCCESS",
  1955. "REQUEST_PASSWORD",
  1956. `UserId '${session.userId}' successfully requested a password.`
  1957. );
  1958. return cb({
  1959. status: "success",
  1960. message: "Successfully requested password."
  1961. });
  1962. }
  1963. );
  1964. }),
  1965. /**
  1966. * Verifies a password code
  1967. *
  1968. * @param {object} session - the session object automatically added by the websocket
  1969. * @param {string} code - the password code
  1970. * @param {Function} cb - gets called with the result
  1971. */
  1972. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1973. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1974. async.waterfall(
  1975. [
  1976. next => {
  1977. if (!code || typeof code !== "string") return next("Invalid code.");
  1978. return userModel.findOne(
  1979. {
  1980. "services.password.set.code": code,
  1981. _id: session.userId
  1982. },
  1983. next
  1984. );
  1985. },
  1986. (user, next) => {
  1987. if (!user) return next("Invalid code.");
  1988. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1989. return next(null);
  1990. }
  1991. ],
  1992. async err => {
  1993. if (err && err !== true) {
  1994. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1995. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1996. cb({ status: "error", message: err });
  1997. } else {
  1998. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1999. cb({
  2000. status: "success",
  2001. message: "Successfully verified password code."
  2002. });
  2003. }
  2004. }
  2005. );
  2006. }),
  2007. /**
  2008. * Adds a password to a user with a code
  2009. *
  2010. * @param {object} session - the session object automatically added by the websocket
  2011. * @param {string} code - the password code
  2012. * @param {string} newPassword - the new password code
  2013. * @param {Function} cb - gets called with the result
  2014. */
  2015. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  2016. const userModel = await DBModule.runJob(
  2017. "GET_MODEL",
  2018. {
  2019. modelName: "user"
  2020. },
  2021. this
  2022. );
  2023. async.waterfall(
  2024. [
  2025. next => {
  2026. if (!code || typeof code !== "string") return next("Invalid code.");
  2027. return userModel.findOne({ "services.password.set.code": code }, next);
  2028. },
  2029. (user, next) => {
  2030. if (!user) return next("Invalid code.");
  2031. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  2032. return next();
  2033. },
  2034. next => {
  2035. if (!DBModule.passwordValid(newPassword))
  2036. return next("Invalid password. Check if it meets all the requirements.");
  2037. return next();
  2038. },
  2039. next => {
  2040. bcrypt.genSalt(10, next);
  2041. },
  2042. // hash the password
  2043. (salt, next) => {
  2044. bcrypt.hash(sha256(newPassword), salt, next);
  2045. },
  2046. (hashedPassword, next) => {
  2047. userModel.updateOne(
  2048. { "services.password.set.code": code },
  2049. {
  2050. $set: {
  2051. "services.password.password": hashedPassword
  2052. },
  2053. $unset: { "services.password.set": "" }
  2054. },
  2055. { runValidators: true },
  2056. next
  2057. );
  2058. }
  2059. ],
  2060. async err => {
  2061. if (err && err !== true) {
  2062. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2063. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  2064. return cb({ status: "error", message: err });
  2065. }
  2066. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  2067. CacheModule.runJob("PUB", {
  2068. channel: "user.linkPassword",
  2069. value: session.userId
  2070. });
  2071. return cb({
  2072. status: "success",
  2073. message: "Successfully added password."
  2074. });
  2075. }
  2076. );
  2077. }),
  2078. /**
  2079. * Unlinks password from user
  2080. *
  2081. * @param {object} session - the session object automatically added by the websocket
  2082. * @param {Function} cb - gets called with the result
  2083. */
  2084. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  2085. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2086. async.waterfall(
  2087. [
  2088. next => {
  2089. userModel.findOne({ _id: session.userId }, next);
  2090. },
  2091. (user, next) => {
  2092. if (!user) return next("Not logged in.");
  2093. if (!user.services.github || !user.services.github.id)
  2094. return next("You can't remove password login without having GitHub login.");
  2095. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  2096. }
  2097. ],
  2098. async err => {
  2099. if (err && err !== true) {
  2100. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2101. this.log(
  2102. "ERROR",
  2103. "UNLINK_PASSWORD",
  2104. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  2105. );
  2106. return cb({ status: "error", message: err });
  2107. }
  2108. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  2109. CacheModule.runJob("PUB", {
  2110. channel: "user.unlinkPassword",
  2111. value: session.userId
  2112. });
  2113. return cb({
  2114. status: "success",
  2115. message: "Successfully unlinked password."
  2116. });
  2117. }
  2118. );
  2119. }),
  2120. /**
  2121. * Unlinks GitHub from user
  2122. *
  2123. * @param {object} session - the session object automatically added by the websocket
  2124. * @param {Function} cb - gets called with the result
  2125. */
  2126. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  2127. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2128. async.waterfall(
  2129. [
  2130. next => {
  2131. userModel.findOne({ _id: session.userId }, next);
  2132. },
  2133. (user, next) => {
  2134. if (!user) return next("Not logged in.");
  2135. if (!user.services.password || !user.services.password.password)
  2136. return next("You can't remove GitHub login without having password login.");
  2137. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  2138. }
  2139. ],
  2140. async err => {
  2141. if (err && err !== true) {
  2142. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2143. this.log(
  2144. "ERROR",
  2145. "UNLINK_GITHUB",
  2146. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  2147. );
  2148. return cb({ status: "error", message: err });
  2149. }
  2150. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  2151. CacheModule.runJob("PUB", {
  2152. channel: "user.unlinkGithub",
  2153. value: session.userId
  2154. });
  2155. return cb({
  2156. status: "success",
  2157. message: "Successfully unlinked GitHub."
  2158. });
  2159. }
  2160. );
  2161. }),
  2162. /**
  2163. * Requests a password reset for an email
  2164. *
  2165. * @param {object} session - the session object automatically added by the websocket
  2166. * @param {string} email - the email of the user that requests a password reset
  2167. * @param {Function} cb - gets called with the result
  2168. */
  2169. async requestPasswordReset(session, email, cb) {
  2170. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2171. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2172. const resetPasswordRequestSchema = await MailModule.runJob(
  2173. "GET_SCHEMA",
  2174. { schemaName: "resetPasswordRequest" },
  2175. this
  2176. );
  2177. async.waterfall(
  2178. [
  2179. next => {
  2180. if (!email || typeof email !== "string") return next("Invalid email.");
  2181. email = email.toLowerCase();
  2182. return userModel.findOne({ "email.address": email }, next);
  2183. },
  2184. (user, next) => {
  2185. if (!user) return next("User not found.");
  2186. if (!user.services.password || !user.services.password.password)
  2187. return next("User does not have a password set, and probably uses GitHub to log in.");
  2188. return next(null, user);
  2189. },
  2190. (user, next) => {
  2191. const expires = new Date();
  2192. expires.setDate(expires.getDate() + 1);
  2193. userModel.findOneAndUpdate(
  2194. { "email.address": email },
  2195. {
  2196. $set: {
  2197. "services.password.reset": {
  2198. code,
  2199. expires
  2200. }
  2201. }
  2202. },
  2203. { runValidators: true },
  2204. next
  2205. );
  2206. },
  2207. (user, next) => {
  2208. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2209. }
  2210. ],
  2211. async err => {
  2212. if (err && err !== true) {
  2213. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2214. this.log(
  2215. "ERROR",
  2216. "REQUEST_PASSWORD_RESET",
  2217. `Email '${email}' failed to request password reset. '${err}'`
  2218. );
  2219. return cb({ status: "error", message: err });
  2220. }
  2221. this.log(
  2222. "SUCCESS",
  2223. "REQUEST_PASSWORD_RESET",
  2224. `Email '${email}' successfully requested a password reset.`
  2225. );
  2226. return cb({
  2227. status: "success",
  2228. message: "Successfully requested password reset."
  2229. });
  2230. }
  2231. );
  2232. },
  2233. /**
  2234. * Verifies a reset code
  2235. *
  2236. * @param {object} session - the session object automatically added by the websocket
  2237. * @param {string} code - the password reset code
  2238. * @param {Function} cb - gets called with the result
  2239. */
  2240. async verifyPasswordResetCode(session, code, cb) {
  2241. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2242. async.waterfall(
  2243. [
  2244. next => {
  2245. if (!code || typeof code !== "string") return next("Invalid code.");
  2246. return userModel.findOne({ "services.password.reset.code": code }, next);
  2247. },
  2248. (user, next) => {
  2249. if (!user) return next("Invalid code.");
  2250. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2251. return next(null);
  2252. }
  2253. ],
  2254. async err => {
  2255. if (err && err !== true) {
  2256. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2257. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  2258. return cb({ status: "error", message: err });
  2259. }
  2260. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  2261. return cb({
  2262. status: "success",
  2263. message: "Successfully verified password reset code."
  2264. });
  2265. }
  2266. );
  2267. },
  2268. /**
  2269. * Changes a user's password with a reset code
  2270. *
  2271. * @param {object} session - the session object automatically added by the websocket
  2272. * @param {string} code - the password reset code
  2273. * @param {string} newPassword - the new password reset code
  2274. * @param {Function} cb - gets called with the result
  2275. */
  2276. async changePasswordWithResetCode(session, code, newPassword, cb) {
  2277. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2278. async.waterfall(
  2279. [
  2280. next => {
  2281. if (!code || typeof code !== "string") return next("Invalid code.");
  2282. return userModel.findOne({ "services.password.reset.code": code }, next);
  2283. },
  2284. (user, next) => {
  2285. if (!user) return next("Invalid code.");
  2286. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2287. return next();
  2288. },
  2289. next => {
  2290. if (!DBModule.passwordValid(newPassword))
  2291. return next("Invalid password. Check if it meets all the requirements.");
  2292. return next();
  2293. },
  2294. next => {
  2295. bcrypt.genSalt(10, next);
  2296. },
  2297. // hash the password
  2298. (salt, next) => {
  2299. bcrypt.hash(sha256(newPassword), salt, next);
  2300. },
  2301. (hashedPassword, next) => {
  2302. userModel.updateOne(
  2303. { "services.password.reset.code": code },
  2304. {
  2305. $set: {
  2306. "services.password.password": hashedPassword
  2307. },
  2308. $unset: { "services.password.reset": "" }
  2309. },
  2310. { runValidators: true },
  2311. next
  2312. );
  2313. }
  2314. ],
  2315. async err => {
  2316. if (err && err !== true) {
  2317. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2318. this.log(
  2319. "ERROR",
  2320. "CHANGE_PASSWORD_WITH_RESET_CODE",
  2321. `Code '${code}' failed to change password. '${err}'`
  2322. );
  2323. return cb({ status: "error", message: err });
  2324. }
  2325. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  2326. return cb({
  2327. status: "success",
  2328. message: "Successfully changed password."
  2329. });
  2330. }
  2331. );
  2332. },
  2333. /**
  2334. * Bans a user by userId
  2335. *
  2336. * @param {object} session - the session object automatically added by the websocket
  2337. * @param {string} value - the user id that is going to be banned
  2338. * @param {string} reason - the reason for the ban
  2339. * @param {string} expiresAt - the time the ban expires
  2340. * @param {Function} cb - gets called with the result
  2341. */
  2342. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  2343. async.waterfall(
  2344. [
  2345. next => {
  2346. if (!userId) return next("You must provide a userId to ban.");
  2347. if (!reason) return next("You must provide a reason for the ban.");
  2348. return next();
  2349. },
  2350. next => {
  2351. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  2352. const date = new Date();
  2353. switch (expiresAt) {
  2354. case "1h":
  2355. expiresAt = date.setHours(date.getHours() + 1);
  2356. break;
  2357. case "12h":
  2358. expiresAt = date.setHours(date.getHours() + 12);
  2359. break;
  2360. case "1d":
  2361. expiresAt = date.setDate(date.getDate() + 1);
  2362. break;
  2363. case "1w":
  2364. expiresAt = date.setDate(date.getDate() + 7);
  2365. break;
  2366. case "1m":
  2367. expiresAt = date.setMonth(date.getMonth() + 1);
  2368. break;
  2369. case "3m":
  2370. expiresAt = date.setMonth(date.getMonth() + 3);
  2371. break;
  2372. case "6m":
  2373. expiresAt = date.setMonth(date.getMonth() + 6);
  2374. break;
  2375. case "1y":
  2376. expiresAt = date.setFullYear(date.getFullYear() + 1);
  2377. break;
  2378. case "never":
  2379. expiresAt = new Date(3093527980800000);
  2380. break;
  2381. default:
  2382. return next("Invalid expire date.");
  2383. }
  2384. return next();
  2385. },
  2386. next => {
  2387. PunishmentsModule.runJob(
  2388. "ADD_PUNISHMENT",
  2389. {
  2390. type: "banUserId",
  2391. value: userId,
  2392. reason,
  2393. expiresAt,
  2394. punishedBy: session.userId
  2395. },
  2396. this
  2397. )
  2398. .then(punishment => next(null, punishment))
  2399. .catch(next);
  2400. },
  2401. (punishment, next) => {
  2402. CacheModule.runJob("PUB", {
  2403. channel: "user.ban",
  2404. value: { userId, punishment }
  2405. });
  2406. next();
  2407. }
  2408. ],
  2409. async err => {
  2410. if (err && err !== true) {
  2411. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2412. this.log(
  2413. "ERROR",
  2414. "BAN_USER_BY_ID",
  2415. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2416. );
  2417. return cb({ status: "error", message: err });
  2418. }
  2419. this.log(
  2420. "SUCCESS",
  2421. "BAN_USER_BY_ID",
  2422. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2423. );
  2424. return cb({
  2425. status: "success",
  2426. message: "Successfully banned user."
  2427. });
  2428. }
  2429. );
  2430. })
  2431. };