users.js 89 KB

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