users.js 83 KB

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