users.js 81 KB

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