users.js 77 KB

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