users.js 81 KB

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