users.js 81 KB

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