users.js 83 KB

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