users.js 75 KB

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