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