users.js 86 KB

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