users.js 89 KB

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