users.js 86 KB

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