users.js 84 KB

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