users.js 82 KB

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