users.js 91 KB

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