users.js 84 KB

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