users.js 86 KB

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