users.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258
  1. import config from "config";
  2. import async from "async";
  3. import axios from "axios";
  4. import bcrypt from "bcrypt";
  5. import sha256 from "sha256";
  6. import { isAdminRequired, isLoginRequired } from "./hooks";
  7. import moduleManager from "../../index";
  8. const DBModule = moduleManager.modules.db;
  9. const UtilsModule = moduleManager.modules.utils;
  10. const WSModule = moduleManager.modules.ws;
  11. const CacheModule = moduleManager.modules.cache;
  12. const MailModule = moduleManager.modules.mail;
  13. const PunishmentsModule = moduleManager.modules.punishments;
  14. const ActivitiesModule = moduleManager.modules.activities;
  15. const PlaylistsModule = moduleManager.modules.playlists;
  16. CacheModule.runJob("SUB", {
  17. channel: "user.updatePreferences",
  18. cb: res => {
  19. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  20. sockets.forEach(socket => {
  21. socket.dispatch("keep.event:user.preferences.changed", res.preferences);
  22. });
  23. });
  24. }
  25. });
  26. CacheModule.runJob("SUB", {
  27. channel: "user.updateOrderOfPlaylists",
  28. cb: res => {
  29. WSModule.runJob("SOCKETS_FROM_USER", { userId: res.userId }, this).then(sockets => {
  30. sockets.forEach(socket => {
  31. socket.dispatch("event:user.orderOfPlaylists.changed", res.orderOfPlaylists);
  32. });
  33. });
  34. WSModule.runJob("EMIT_TO_ROOM", {
  35. room: `profile-${res.userId}-playlists`,
  36. args: ["event:user.orderOfPlaylists.changed", res.orderOfPlaylists]
  37. });
  38. }
  39. });
  40. CacheModule.runJob("SUB", {
  41. channel: "user.updateUsername",
  42. cb: user => {
  43. WSModule.runJob("SOCKETS_FROM_USER", { userId: user._id }).then(sockets => {
  44. sockets.forEach(socket => {
  45. socket.dispatch("event:user.username.changed", user.username);
  46. });
  47. });
  48. }
  49. });
  50. CacheModule.runJob("SUB", {
  51. channel: "user.removeSessions",
  52. cb: userId => {
  53. WSModule.runJob("SOCKETS_FROM_USER_WITHOUT_CACHE", { userId }).then(sockets => {
  54. sockets.forEach(socket => {
  55. socket.dispatch("keep.event:user.session.removed");
  56. });
  57. });
  58. }
  59. });
  60. CacheModule.runJob("SUB", {
  61. channel: "user.linkPassword",
  62. cb: userId => {
  63. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  64. sockets.forEach(socket => {
  65. socket.dispatch("event:user.linkPassword");
  66. });
  67. });
  68. }
  69. });
  70. CacheModule.runJob("SUB", {
  71. channel: "user.unlinkPassword",
  72. cb: userId => {
  73. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  74. sockets.forEach(socket => {
  75. socket.dispatch("event:user.unlinkPassword");
  76. });
  77. });
  78. }
  79. });
  80. CacheModule.runJob("SUB", {
  81. channel: "user.linkGithub",
  82. cb: userId => {
  83. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  84. sockets.forEach(socket => {
  85. socket.dispatch("event:user.linkGithub");
  86. });
  87. });
  88. }
  89. });
  90. CacheModule.runJob("SUB", {
  91. channel: "user.unlinkGithub",
  92. cb: userId => {
  93. WSModule.runJob("SOCKETS_FROM_USER", { userId }).then(sockets => {
  94. sockets.forEach(socket => {
  95. socket.dispatch("event:user.unlinkGithub");
  96. });
  97. });
  98. }
  99. });
  100. CacheModule.runJob("SUB", {
  101. channel: "user.ban",
  102. cb: data => {
  103. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  104. sockets.forEach(socket => {
  105. socket.dispatch("keep.event:banned", data.punishment);
  106. socket.disconnect(true);
  107. });
  108. });
  109. }
  110. });
  111. CacheModule.runJob("SUB", {
  112. channel: "user.favoritedStation",
  113. cb: data => {
  114. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  115. sockets.forEach(socket => {
  116. socket.dispatch("event:user.favoritedStation", data.stationId);
  117. });
  118. });
  119. }
  120. });
  121. CacheModule.runJob("SUB", {
  122. channel: "user.unfavoritedStation",
  123. cb: data => {
  124. WSModule.runJob("SOCKETS_FROM_USER", { userId: data.userId }).then(sockets => {
  125. sockets.forEach(socket => {
  126. socket.dispatch("event:user.unfavoritedStation", data.stationId);
  127. });
  128. });
  129. }
  130. });
  131. export default {
  132. /**
  133. * Lists all Users
  134. *
  135. * @param {object} session - the session object automatically added by the websocket
  136. * @param {Function} cb - gets called with the result
  137. */
  138. index: isAdminRequired(async function index(session, cb) {
  139. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  140. async.waterfall(
  141. [
  142. next => {
  143. userModel.find({}).exec(next);
  144. }
  145. ],
  146. async (err, users) => {
  147. if (err) {
  148. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  149. this.log("ERROR", "USER_INDEX", `Indexing users failed. "${err}"`);
  150. return cb({ status: "failure", message: err });
  151. }
  152. this.log("SUCCESS", "USER_INDEX", `Indexing users successful.`);
  153. const filteredUsers = [];
  154. users.forEach(user => {
  155. filteredUsers.push({
  156. _id: user._id,
  157. name: user.name,
  158. username: user.username,
  159. role: user.role,
  160. liked: user.liked,
  161. disliked: user.disliked,
  162. songsRequested: user.statistics.songsRequested,
  163. email: {
  164. address: user.email.address,
  165. verified: user.email.verified
  166. },
  167. avatar: {
  168. type: user.avatar.type,
  169. url: user.avatar.url,
  170. color: user.avatar.color
  171. },
  172. hasPassword: !!user.services.password,
  173. services: { github: user.services.github }
  174. });
  175. });
  176. return cb({ status: "success", data: filteredUsers });
  177. }
  178. );
  179. }),
  180. /**
  181. * Removes all data held on a user, including their ability to login
  182. *
  183. * @param {object} session - the session object automatically added by the websocket
  184. * @param {Function} cb - gets called with the result
  185. */
  186. remove: isLoginRequired(async function remove(session, cb) {
  187. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  188. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  189. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  190. const activityModel = await DBModule.runJob("GET_MODEL", { modelName: "activity" }, this);
  191. async.waterfall(
  192. [
  193. next => {
  194. activityModel.deleteMany({ userId: session.userId }, next);
  195. },
  196. (res, next) => {
  197. stationModel.deleteMany({ owner: session.userId }, next);
  198. },
  199. (res, next) => {
  200. playlistModel.deleteMany({ createdBy: session.userId }, next);
  201. },
  202. (res, next) => {
  203. userModel.deleteMany({ _id: session.userId }, next);
  204. }
  205. ],
  206. async err => {
  207. console.log(err);
  208. if (err && err !== true) {
  209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  210. this.log(
  211. "ERROR",
  212. "USER_REMOVE",
  213. `Removing data and account for user "${session.userId}" failed. "${err}"`
  214. );
  215. return cb({ status: "failure", message: err });
  216. }
  217. this.log(
  218. "SUCCESS",
  219. "USER_REMOVE",
  220. `Successfully removed data and account for user "${session.userId}"`
  221. );
  222. return cb({
  223. status: "success",
  224. message: "Successfully removed data and account."
  225. });
  226. }
  227. );
  228. }),
  229. /**
  230. * Logs user in
  231. *
  232. * @param {object} session - the session object automatically added by the websocket
  233. * @param {string} identifier - the email of the user
  234. * @param {string} password - the plaintext of the user
  235. * @param {Function} cb - gets called with the result
  236. */
  237. async login(session, identifier, password, cb) {
  238. identifier = identifier.toLowerCase();
  239. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  240. const sessionSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "session" }, this);
  241. async.waterfall(
  242. [
  243. // check if a user with the requested identifier exists
  244. next => {
  245. userModel.findOne(
  246. {
  247. $or: [{ "email.address": identifier }]
  248. },
  249. next
  250. );
  251. },
  252. // if the user doesn't exist, respond with a failure
  253. // otherwise compare the requested password and the actual users password
  254. (user, next) => {
  255. if (!user) return next("User not found");
  256. if (!user.services.password || !user.services.password.password)
  257. return next("The account you are trying to access uses GitHub to log in.");
  258. return bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  259. if (err) return next(err);
  260. if (!match) return next("Incorrect password");
  261. return next(null, user);
  262. });
  263. },
  264. (user, next) => {
  265. UtilsModule.runJob("GUID", {}, this).then(sessionId => {
  266. next(null, user, sessionId);
  267. });
  268. },
  269. (user, sessionId, next) => {
  270. CacheModule.runJob(
  271. "HSET",
  272. {
  273. table: "sessions",
  274. key: sessionId,
  275. value: sessionSchema(sessionId, user._id)
  276. },
  277. this
  278. )
  279. .then(() => {
  280. next(null, sessionId);
  281. })
  282. .catch(next);
  283. }
  284. ],
  285. async (err, sessionId) => {
  286. if (err && err !== true) {
  287. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  288. this.log(
  289. "ERROR",
  290. "USER_PASSWORD_LOGIN",
  291. `Login failed with password for user "${identifier}". "${err}"`
  292. );
  293. return cb({ status: "failure", message: err });
  294. }
  295. this.log("SUCCESS", "USER_PASSWORD_LOGIN", `Login successful with password for user "${identifier}"`);
  296. return cb({
  297. status: "success",
  298. message: "Login successful",
  299. user: {},
  300. SID: sessionId
  301. });
  302. }
  303. );
  304. },
  305. /**
  306. * Registers a new user
  307. *
  308. * @param {object} session - the session object automatically added by the websocket
  309. * @param {string} username - the username for the new user
  310. * @param {string} email - the email for the new user
  311. * @param {string} password - the plaintext password for the new user
  312. * @param {object} recaptcha - the recaptcha data
  313. * @param {Function} cb - gets called with the result
  314. */
  315. async register(session, username, email, password, recaptcha, cb) {
  316. email = email.toLowerCase();
  317. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  318. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  319. const verifyEmailSchema = await MailModule.runJob(
  320. "GET_SCHEMA",
  321. {
  322. schemaName: "verifyEmail"
  323. },
  324. this
  325. );
  326. async.waterfall(
  327. [
  328. next => {
  329. if (config.get("registrationDisabled") === true)
  330. return next("Registration is not allowed at this time.");
  331. return next();
  332. },
  333. next => {
  334. if (!DBModule.passwordValid(password))
  335. return next("Invalid password. Check if it meets all the requirements.");
  336. return next();
  337. },
  338. // verify the request with google recaptcha
  339. next => {
  340. if (config.get("apis.recaptcha.enabled") === true)
  341. axios
  342. .post("https://www.google.com/recaptcha/api/siteverify", {
  343. data: {
  344. secret: config.get("apis").recaptcha.secret,
  345. response: recaptcha
  346. }
  347. })
  348. .then(res => next(null, res.data))
  349. .catch(err => next(err));
  350. else next(null, null);
  351. },
  352. // check if the response from Google recaptcha is successful
  353. // if it is, we check if a user with the requested username already exists
  354. (body, next) => {
  355. if (config.get("apis.recaptcha.enabled") === true)
  356. if (body.success !== true) return next("Response from recaptcha was not successful.");
  357. return userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  358. },
  359. // if the user already exists, respond with that
  360. // otherwise check if a user with the requested email already exists
  361. (user, next) => {
  362. if (user) return next("A user with that username already exists.");
  363. return userModel.findOne({ "email.address": email }, next);
  364. },
  365. // if the user already exists, respond with that
  366. // otherwise, generate a salt to use with hashing the new users password
  367. (user, next) => {
  368. if (user) return next("A user with that email already exists.");
  369. return bcrypt.genSalt(10, next);
  370. },
  371. // hash the password
  372. (salt, next) => {
  373. bcrypt.hash(sha256(password), salt, next);
  374. },
  375. (hash, next) => {
  376. UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 12 }, this).then(_id => {
  377. next(null, hash, _id);
  378. });
  379. },
  380. // create the user object
  381. (hash, _id, next) => {
  382. next(null, {
  383. _id,
  384. username,
  385. email: {
  386. address: email,
  387. verificationToken
  388. },
  389. services: {
  390. password: {
  391. password: hash
  392. }
  393. }
  394. });
  395. },
  396. // generate the url for gravatar avatar
  397. (user, next) => {
  398. UtilsModule.runJob("CREATE_GRAVATAR", { email: user.email.address }, this).then(url => {
  399. user.avatar = {
  400. type: "gravatar",
  401. url
  402. };
  403. next(null, user);
  404. });
  405. },
  406. // save the new user to the database
  407. (user, next) => {
  408. userModel.create(user, next);
  409. },
  410. // respond with the new user
  411. (user, next) => {
  412. verifyEmailSchema(email, username, verificationToken, err => {
  413. next(err, user._id);
  414. });
  415. },
  416. // create a liked songs playlist for the new user
  417. (userId, next) => {
  418. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  419. userId,
  420. displayName: "Liked Songs",
  421. type: "user"
  422. })
  423. .then(likedSongsPlaylist => {
  424. next(null, likedSongsPlaylist, userId);
  425. })
  426. .catch(err => next(err));
  427. },
  428. // create a disliked songs playlist for the new user
  429. (likedSongsPlaylist, userId, next) => {
  430. PlaylistsModule.runJob("CREATE_READ_ONLY_PLAYLIST", {
  431. userId,
  432. displayName: "Disliked Songs",
  433. type: "user"
  434. })
  435. .then(dislikedSongsPlaylist => {
  436. next(null, { likedSongsPlaylist, dislikedSongsPlaylist }, userId);
  437. })
  438. .catch(err => next(err));
  439. },
  440. // associate liked + disliked songs playlist to the user object
  441. ({ likedSongsPlaylist, dislikedSongsPlaylist }, userId, next) => {
  442. userModel.updateOne(
  443. { _id: userId },
  444. { $set: { likedSongsPlaylist, dislikedSongsPlaylist } },
  445. { runValidators: true },
  446. err => {
  447. if (err) return next(err);
  448. return next(null, userId);
  449. }
  450. );
  451. }
  452. ],
  453. async (err, userId) => {
  454. if (err && err !== true) {
  455. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  456. this.log(
  457. "ERROR",
  458. "USER_PASSWORD_REGISTER",
  459. `Register failed with password for user "${username}"."${err}"`
  460. );
  461. return cb({ status: "failure", message: err });
  462. }
  463. ActivitiesModule.runJob("ADD_ACTIVITY", {
  464. userId,
  465. type: "user__joined",
  466. payload: { message: "Welcome to Musare!" }
  467. });
  468. this.log(
  469. "SUCCESS",
  470. "USER_PASSWORD_REGISTER",
  471. `Register successful with password for user "${username}".`
  472. );
  473. const result = await this.module.runJob(
  474. "RUN_ACTION2",
  475. {
  476. session,
  477. namespace: "users",
  478. action: "login",
  479. args: [email, password]
  480. },
  481. this
  482. );
  483. const obj = {
  484. status: "success",
  485. message: "Successfully registered."
  486. };
  487. if (result.status === "success") {
  488. obj.SID = result.SID;
  489. }
  490. return cb(obj);
  491. }
  492. );
  493. },
  494. /**
  495. * Logs out a user
  496. *
  497. * @param {object} session - the session object automatically added by the websocket
  498. * @param {Function} cb - gets called with the result
  499. */
  500. logout(session, cb) {
  501. async.waterfall(
  502. [
  503. next => {
  504. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }, this)
  505. .then(session => next(null, session))
  506. .catch(next);
  507. },
  508. (session, next) => {
  509. if (!session) return next("Session not found");
  510. return next(null, session);
  511. },
  512. (session, next) => {
  513. CacheModule.runJob("HDEL", { table: "sessions", key: session.sessionId }, this)
  514. .then(() => next())
  515. .catch(next);
  516. }
  517. ],
  518. async err => {
  519. if (err && err !== true) {
  520. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  521. this.log("ERROR", "USER_LOGOUT", `Logout failed. "${err}" `);
  522. cb({ status: "failure", message: err });
  523. } else {
  524. this.log("SUCCESS", "USER_LOGOUT", `Logout successful.`);
  525. cb({
  526. status: "success",
  527. message: "Successfully logged out."
  528. });
  529. }
  530. }
  531. );
  532. },
  533. /**
  534. * Removes all sessions for a user
  535. *
  536. * @param {object} session - the session object automatically added by the websocket
  537. * @param {string} userId - the id of the user we are trying to delete the sessions of
  538. * @param {Function} cb - gets called with the result
  539. */
  540. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  541. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  542. async.waterfall(
  543. [
  544. next => {
  545. userModel.findOne({ _id: session.userId }, (err, user) => {
  546. if (err) return next(err);
  547. if (user.role !== "admin" && session.userId !== userId)
  548. return next("Only admins and the owner of the account can remove their sessions.");
  549. return next();
  550. });
  551. },
  552. next => {
  553. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  554. .then(sessions => {
  555. next(null, sessions);
  556. })
  557. .catch(next);
  558. },
  559. (sessions, next) => {
  560. if (!sessions) return next("There are no sessions for this user to remove.");
  561. const keys = Object.keys(sessions);
  562. return next(null, keys, sessions);
  563. },
  564. (keys, sessions, next) => {
  565. CacheModule.runJob("PUB", {
  566. channel: "user.removeSessions",
  567. value: userId
  568. });
  569. async.each(
  570. keys,
  571. (sessionId, callback) => {
  572. const session = sessions[sessionId];
  573. if (session.userId === userId) {
  574. // TODO Also maybe add this to this runJob
  575. CacheModule.runJob("HDEL", {
  576. channel: "sessions",
  577. key: sessionId
  578. })
  579. .then(() => {
  580. callback(null);
  581. })
  582. .catch(next);
  583. }
  584. },
  585. err => {
  586. next(err);
  587. }
  588. );
  589. }
  590. ],
  591. async err => {
  592. if (err) {
  593. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  594. this.log(
  595. "ERROR",
  596. "REMOVE_SESSIONS_FOR_USER",
  597. `Couldn't remove all sessions for user "${userId}". "${err}"`
  598. );
  599. return cb({ status: "failure", message: err });
  600. }
  601. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  602. return cb({
  603. status: "success",
  604. message: "Successfully removed all sessions."
  605. });
  606. }
  607. );
  608. }),
  609. /**
  610. * Updates the order of a user's playlists
  611. *
  612. * @param {object} session - the session object automatically added by the websocket
  613. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  614. * @param {Function} cb - gets called with the result
  615. */
  616. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  617. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  618. async.waterfall(
  619. [
  620. next => {
  621. userModel.updateOne(
  622. { _id: session.userId },
  623. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  624. { runValidators: true },
  625. next
  626. );
  627. }
  628. ],
  629. async err => {
  630. if (err) {
  631. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  632. this.log(
  633. "ERROR",
  634. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  635. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  636. );
  637. return cb({ status: "failure", message: err });
  638. }
  639. CacheModule.runJob("PUB", {
  640. channel: "user.updateOrderOfPlaylists",
  641. value: {
  642. orderOfPlaylists,
  643. userId: session.userId
  644. }
  645. });
  646. this.log(
  647. "SUCCESS",
  648. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  649. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  650. );
  651. return cb({
  652. status: "success",
  653. message: "Order of playlists successfully updated"
  654. });
  655. }
  656. );
  657. }),
  658. /**
  659. * Updates a user's preferences
  660. *
  661. * @param {object} session - the session object automatically added by the websocket
  662. * @param {object} preferences - object containing preferences
  663. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  664. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  665. * @param {boolean} preferences.activityLogPublic - whether or not a user's activity log can be publicly viewed
  666. * @param {Function} cb - gets called with the result
  667. */
  668. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  669. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  670. async.waterfall(
  671. [
  672. next => {
  673. userModel.findByIdAndUpdate(
  674. session.userId,
  675. {
  676. $set: {
  677. preferences: {
  678. nightmode: preferences.nightmode,
  679. autoSkipDisliked: preferences.autoSkipDisliked,
  680. activityLogPublic: preferences.activityLogPublic
  681. }
  682. }
  683. },
  684. { new: false },
  685. next
  686. );
  687. }
  688. ],
  689. async (err, user) => {
  690. if (err) {
  691. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  692. this.log(
  693. "ERROR",
  694. "UPDATE_USER_PREFERENCES",
  695. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  696. preferences
  697. )}". "${err}"`
  698. );
  699. return cb({ status: "failure", message: err });
  700. }
  701. CacheModule.runJob("PUB", {
  702. channel: "user.updatePreferences",
  703. value: {
  704. preferences,
  705. userId: session.userId
  706. }
  707. });
  708. if (preferences.nightmode !== user.preferences.nightmode)
  709. ActivitiesModule.runJob("ADD_ACTIVITY", {
  710. userId: session.userId,
  711. type: "user__toggle_nightmode",
  712. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  713. });
  714. if (preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked)
  715. ActivitiesModule.runJob("ADD_ACTIVITY", {
  716. userId: session.userId,
  717. type: "user__toggle_autoskip_disliked_songs",
  718. payload: {
  719. message: preferences.autoSkipDisliked
  720. ? "Enabled the autoskipping of disliked songs"
  721. : "Disabled the autoskipping of disliked songs"
  722. }
  723. });
  724. this.log(
  725. "SUCCESS",
  726. "UPDATE_USER_PREFERENCES",
  727. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  728. );
  729. return cb({
  730. status: "success",
  731. message: "Preferences successfully updated"
  732. });
  733. }
  734. );
  735. }),
  736. /**
  737. * Retrieves a user's preferences
  738. *
  739. * @param {object} session - the session object automatically added by the websocket
  740. * @param {Function} cb - gets called with the result
  741. */
  742. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  743. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  744. async.waterfall(
  745. [
  746. next => {
  747. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  748. }
  749. ],
  750. async (err, { preferences }) => {
  751. if (err) {
  752. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  753. this.log(
  754. "ERROR",
  755. "GET_USER_PREFERENCES",
  756. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  757. );
  758. return cb({ status: "failure", message: err });
  759. }
  760. this.log(
  761. "SUCCESS",
  762. "GET_USER_PREFERENCES",
  763. `Successfully obtained preferences for user "${session.userId}".`
  764. );
  765. return cb({
  766. status: "success",
  767. message: "Preferences successfully retrieved",
  768. data: preferences
  769. });
  770. }
  771. );
  772. }),
  773. /**
  774. * Gets user object from username (only a few properties)
  775. *
  776. * @param {object} session - the session object automatically added by the websocket
  777. * @param {string} username - the username of the user we are trying to find
  778. * @param {Function} cb - gets called with the result
  779. */
  780. findByUsername: async function findByUsername(session, username, cb) {
  781. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  782. async.waterfall(
  783. [
  784. next => {
  785. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  786. },
  787. (account, next) => {
  788. if (!account) return next("User not found.");
  789. return next(null, account);
  790. }
  791. ],
  792. async (err, account) => {
  793. if (err && err !== true) {
  794. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  795. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  796. return cb({ status: "failure", message: err });
  797. }
  798. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  799. return cb({
  800. status: "success",
  801. data: {
  802. _id: account._id,
  803. name: account.name,
  804. username: account.username,
  805. location: account.location,
  806. bio: account.bio,
  807. role: account.role,
  808. avatar: account.avatar,
  809. createdAt: account.createdAt
  810. }
  811. });
  812. }
  813. );
  814. },
  815. /**
  816. * Gets a username from an userId
  817. *
  818. * @param {object} session - the session object automatically added by the websocket
  819. * @param {string} userId - the userId of the person we are trying to get the username from
  820. * @param {Function} cb - gets called with the result
  821. */
  822. async getUsernameFromId(session, userId, cb) {
  823. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  824. userModel
  825. .findById(userId)
  826. .then(user => {
  827. if (user) {
  828. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  829. return cb({
  830. status: "success",
  831. data: user.username
  832. });
  833. }
  834. this.log(
  835. "ERROR",
  836. "GET_USERNAME_FROM_ID",
  837. `Getting the username from userId "${userId}" failed. User not found.`
  838. );
  839. return cb({
  840. status: "failure",
  841. message: "Couldn't find the user."
  842. });
  843. })
  844. .catch(async err => {
  845. if (err && err !== true) {
  846. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  847. this.log(
  848. "ERROR",
  849. "GET_USERNAME_FROM_ID",
  850. `Getting the username from userId "${userId}" failed. "${err}"`
  851. );
  852. cb({ status: "failure", message: err });
  853. }
  854. });
  855. },
  856. /**
  857. * Gets a user from a userId
  858. *
  859. * @param {object} session - the session object automatically added by the websocket
  860. * @param {string} userId - the userId of the person we are trying to get the username from
  861. * @param {Function} cb - gets called with the result
  862. */
  863. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  864. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  865. userModel
  866. .findById(userId)
  867. .then(user => {
  868. if (user) {
  869. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  870. return cb({
  871. status: "success",
  872. data: {
  873. _id: user._id,
  874. username: user.username,
  875. role: user.role,
  876. liked: user.liked,
  877. disliked: user.disliked,
  878. songsRequested: user.statistics.songsRequested,
  879. email: {
  880. address: user.email.address,
  881. verified: user.email.verified
  882. },
  883. hasPassword: !!user.services.password,
  884. services: { github: user.services.github }
  885. }
  886. });
  887. }
  888. this.log(
  889. "ERROR",
  890. "GET_USER_FROM_ID",
  891. `Getting the user from userId "${userId}" failed. User not found.`
  892. );
  893. return cb({
  894. status: "failure",
  895. message: "Couldn't find the user."
  896. });
  897. })
  898. .catch(async err => {
  899. if (err && err !== true) {
  900. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  901. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  902. cb({ status: "failure", message: err });
  903. }
  904. });
  905. }),
  906. // TODO Fix security issues
  907. /**
  908. * Gets user info from session
  909. *
  910. * @param {object} session - the session object automatically added by the websocket
  911. * @param {Function} cb - gets called with the result
  912. */
  913. async findBySession(session, cb) {
  914. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  915. async.waterfall(
  916. [
  917. next => {
  918. CacheModule.runJob(
  919. "HGET",
  920. {
  921. table: "sessions",
  922. key: session.sessionId
  923. },
  924. this
  925. )
  926. .then(session => next(null, session))
  927. .catch(next);
  928. },
  929. (session, next) => {
  930. if (!session) return next("Session not found.");
  931. return next(null, session);
  932. },
  933. (session, next) => {
  934. userModel.findOne({ _id: session.userId }, next);
  935. },
  936. (user, next) => {
  937. if (!user) return next("User not found.");
  938. return next(null, user);
  939. }
  940. ],
  941. async (err, user) => {
  942. if (err && err !== true) {
  943. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  944. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  945. return cb({ status: "failure", message: err });
  946. }
  947. const data = {
  948. email: {
  949. address: user.email.address
  950. },
  951. avatar: user.avatar,
  952. username: user.username,
  953. name: user.name,
  954. location: user.location,
  955. bio: user.bio
  956. };
  957. if (user.services.password && user.services.password.password) data.password = true;
  958. if (user.services.github && user.services.github.id) data.github = true;
  959. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  960. return cb({
  961. status: "success",
  962. data
  963. });
  964. }
  965. );
  966. },
  967. /**
  968. * Updates a user's username
  969. *
  970. * @param {object} session - the session object automatically added by the websocket
  971. * @param {string} updatingUserId - the updating user's id
  972. * @param {string} newUsername - the new username
  973. * @param {Function} cb - gets called with the result
  974. */
  975. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  976. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  977. async.waterfall(
  978. [
  979. next => {
  980. if (updatingUserId === session.userId) return next(null, true);
  981. return userModel.findOne({ _id: session.userId }, next);
  982. },
  983. (user, next) => {
  984. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  985. return userModel.findOne({ _id: updatingUserId }, next);
  986. },
  987. (user, next) => {
  988. if (!user) return next("User not found.");
  989. if (user.username === newUsername)
  990. return next("New username can't be the same as the old username.");
  991. return next(null);
  992. },
  993. next => {
  994. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  995. },
  996. (user, next) => {
  997. if (!user) return next();
  998. if (user._id === updatingUserId) return next();
  999. return next("That username is already in use.");
  1000. },
  1001. next => {
  1002. userModel.updateOne(
  1003. { _id: updatingUserId },
  1004. { $set: { username: newUsername } },
  1005. { runValidators: true },
  1006. next
  1007. );
  1008. }
  1009. ],
  1010. async err => {
  1011. if (err && err !== true) {
  1012. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1013. this.log(
  1014. "ERROR",
  1015. "UPDATE_USERNAME",
  1016. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1017. );
  1018. return cb({ status: "failure", message: err });
  1019. }
  1020. CacheModule.runJob("PUB", {
  1021. channel: "user.updateUsername",
  1022. value: {
  1023. username: newUsername,
  1024. _id: updatingUserId
  1025. }
  1026. });
  1027. this.log(
  1028. "SUCCESS",
  1029. "UPDATE_USERNAME",
  1030. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1031. );
  1032. return cb({
  1033. status: "success",
  1034. message: "Username updated successfully"
  1035. });
  1036. }
  1037. );
  1038. }),
  1039. /**
  1040. * Updates a user's email
  1041. *
  1042. * @param {object} session - the session object automatically added by the websocket
  1043. * @param {string} updatingUserId - the updating user's id
  1044. * @param {string} newEmail - the new email
  1045. * @param {Function} cb - gets called with the result
  1046. */
  1047. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1048. newEmail = newEmail.toLowerCase();
  1049. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1050. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1051. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1052. async.waterfall(
  1053. [
  1054. next => {
  1055. if (updatingUserId === session.userId) return next(null, true);
  1056. return userModel.findOne({ _id: session.userId }, next);
  1057. },
  1058. (user, next) => {
  1059. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1060. return userModel.findOne({ _id: updatingUserId }, next);
  1061. },
  1062. (user, next) => {
  1063. if (!user) return next("User not found.");
  1064. if (user.email.address === newEmail)
  1065. return next("New email can't be the same as your the old email.");
  1066. return next();
  1067. },
  1068. next => {
  1069. userModel.findOne({ "email.address": newEmail }, next);
  1070. },
  1071. (user, next) => {
  1072. if (!user) return next();
  1073. if (user._id === updatingUserId) return next();
  1074. return next("That email is already in use.");
  1075. },
  1076. // regenerate the url for gravatar avatar
  1077. next => {
  1078. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1079. next(null, url);
  1080. });
  1081. },
  1082. (newAvatarUrl, next) => {
  1083. userModel.updateOne(
  1084. { _id: updatingUserId },
  1085. {
  1086. $set: {
  1087. "avatar.url": newAvatarUrl,
  1088. "email.address": newEmail,
  1089. "email.verified": false,
  1090. "email.verificationToken": verificationToken
  1091. }
  1092. },
  1093. { runValidators: true },
  1094. next
  1095. );
  1096. },
  1097. (res, next) => {
  1098. userModel.findOne({ _id: updatingUserId }, next);
  1099. },
  1100. (user, next) => {
  1101. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1102. next(err);
  1103. });
  1104. }
  1105. ],
  1106. async err => {
  1107. if (err && err !== true) {
  1108. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1109. this.log(
  1110. "ERROR",
  1111. "UPDATE_EMAIL",
  1112. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1113. );
  1114. return cb({ status: "failure", message: err });
  1115. }
  1116. this.log(
  1117. "SUCCESS",
  1118. "UPDATE_EMAIL",
  1119. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1120. );
  1121. return cb({
  1122. status: "success",
  1123. message: "Email updated successfully."
  1124. });
  1125. }
  1126. );
  1127. }),
  1128. /**
  1129. * Updates a user's name
  1130. *
  1131. * @param {object} session - the session object automatically added by the websocket
  1132. * @param {string} updatingUserId - the updating user's id
  1133. * @param {string} newBio - the new name
  1134. * @param {Function} cb - gets called with the result
  1135. */
  1136. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1137. const userModel = await DBModule.runJob(
  1138. "GET_MODEL",
  1139. {
  1140. modelName: "user"
  1141. },
  1142. this
  1143. );
  1144. async.waterfall(
  1145. [
  1146. next => {
  1147. if (updatingUserId === session.userId) return next(null, true);
  1148. return userModel.findOne({ _id: session.userId }, next);
  1149. },
  1150. (user, next) => {
  1151. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1152. return userModel.findOne({ _id: updatingUserId }, next);
  1153. },
  1154. (user, next) => {
  1155. if (!user) return next("User not found.");
  1156. return userModel.updateOne(
  1157. { _id: updatingUserId },
  1158. { $set: { name: newName } },
  1159. { runValidators: true },
  1160. next
  1161. );
  1162. }
  1163. ],
  1164. async err => {
  1165. if (err && err !== true) {
  1166. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1167. this.log(
  1168. "ERROR",
  1169. "UPDATE_NAME",
  1170. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1171. );
  1172. return cb({ status: "failure", message: err });
  1173. }
  1174. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1175. userId: updatingUserId,
  1176. type: "user__edit_name",
  1177. payload: { message: `Changed name to ${newName}` }
  1178. });
  1179. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1180. return cb({
  1181. status: "success",
  1182. message: "Name updated successfully"
  1183. });
  1184. }
  1185. );
  1186. }),
  1187. /**
  1188. * Updates a user's location
  1189. *
  1190. * @param {object} session - the session object automatically added by the websocket
  1191. * @param {string} updatingUserId - the updating user's id
  1192. * @param {string} newLocation - the new location
  1193. * @param {Function} cb - gets called with the result
  1194. */
  1195. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1196. const userModel = await DBModule.runJob(
  1197. "GET_MODEL",
  1198. {
  1199. modelName: "user"
  1200. },
  1201. this
  1202. );
  1203. async.waterfall(
  1204. [
  1205. next => {
  1206. if (updatingUserId === session.userId) return next(null, true);
  1207. return userModel.findOne({ _id: session.userId }, next);
  1208. },
  1209. (user, next) => {
  1210. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1211. return userModel.findOne({ _id: updatingUserId }, next);
  1212. },
  1213. (user, next) => {
  1214. if (!user) return next("User not found.");
  1215. return userModel.updateOne(
  1216. { _id: updatingUserId },
  1217. { $set: { location: newLocation } },
  1218. { runValidators: true },
  1219. next
  1220. );
  1221. }
  1222. ],
  1223. async err => {
  1224. if (err && err !== true) {
  1225. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1226. this.log(
  1227. "ERROR",
  1228. "UPDATE_LOCATION",
  1229. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1230. );
  1231. return cb({ status: "failure", message: err });
  1232. }
  1233. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1234. userId: updatingUserId,
  1235. type: "user__edit_location",
  1236. payload: { message: `Changed location to ${newLocation}` }
  1237. });
  1238. this.log(
  1239. "SUCCESS",
  1240. "UPDATE_LOCATION",
  1241. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1242. );
  1243. return cb({
  1244. status: "success",
  1245. message: "Location updated successfully"
  1246. });
  1247. }
  1248. );
  1249. }),
  1250. /**
  1251. * Updates a user's bio
  1252. *
  1253. * @param {object} session - the session object automatically added by the websocket
  1254. * @param {string} updatingUserId - the updating user's id
  1255. * @param {string} newBio - the new bio
  1256. * @param {Function} cb - gets called with the result
  1257. */
  1258. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1259. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1260. async.waterfall(
  1261. [
  1262. next => {
  1263. if (updatingUserId === session.userId) return next(null, true);
  1264. return userModel.findOne({ _id: session.userId }, next);
  1265. },
  1266. (user, next) => {
  1267. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1268. return userModel.findOne({ _id: updatingUserId }, next);
  1269. },
  1270. (user, next) => {
  1271. if (!user) return next("User not found.");
  1272. return userModel.updateOne(
  1273. { _id: updatingUserId },
  1274. { $set: { bio: newBio } },
  1275. { runValidators: true },
  1276. next
  1277. );
  1278. }
  1279. ],
  1280. async err => {
  1281. if (err && err !== true) {
  1282. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1283. this.log(
  1284. "ERROR",
  1285. "UPDATE_BIO",
  1286. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1287. );
  1288. return cb({ status: "failure", message: err });
  1289. }
  1290. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1291. userId: updatingUserId,
  1292. type: "user__edit_bio",
  1293. payload: { message: `Changed bio to ${newBio}` }
  1294. });
  1295. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1296. return cb({
  1297. status: "success",
  1298. message: "Bio updated successfully"
  1299. });
  1300. }
  1301. );
  1302. }),
  1303. /**
  1304. * Updates the type of a user's avatar
  1305. *
  1306. * @param {object} session - the session object automatically added by the websocket
  1307. * @param {string} updatingUserId - the updating user's id
  1308. * @param {string} newType - the new type
  1309. * @param {Function} cb - gets called with the result
  1310. */
  1311. updateAvatarType: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1312. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1313. async.waterfall(
  1314. [
  1315. next => {
  1316. if (updatingUserId === session.userId) return next(null, true);
  1317. return userModel.findOne({ _id: session.userId }, next);
  1318. },
  1319. (user, next) => {
  1320. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1321. return userModel.findOne({ _id: updatingUserId }, next);
  1322. },
  1323. (user, next) => {
  1324. if (!user) return next("User not found.");
  1325. return userModel.findOneAndUpdate(
  1326. { _id: updatingUserId },
  1327. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1328. { new: true, runValidators: true },
  1329. next
  1330. );
  1331. }
  1332. ],
  1333. async err => {
  1334. if (err && err !== true) {
  1335. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1336. this.log(
  1337. "ERROR",
  1338. "UPDATE_AVATAR_TYPE",
  1339. `Couldn't update avatar type for user "${updatingUserId}" to type "${newAvatar.type}". "${err}"`
  1340. );
  1341. return cb({ status: "failure", message: err });
  1342. }
  1343. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1344. userId: updatingUserId,
  1345. type: "user__edit_avatar",
  1346. payload: { message: `Changed avatar to use ${newAvatar.type}` }
  1347. });
  1348. this.log(
  1349. "SUCCESS",
  1350. "UPDATE_AVATAR_TYPE",
  1351. `Updated avatar type for user "${updatingUserId}" to type "${newAvatar.type}".`
  1352. );
  1353. return cb({
  1354. status: "success",
  1355. message: "Avatar type updated successfully"
  1356. });
  1357. }
  1358. );
  1359. }),
  1360. /**
  1361. * Updates a user's role
  1362. *
  1363. * @param {object} session - the session object automatically added by the websocket
  1364. * @param {string} updatingUserId - the updating user's id
  1365. * @param {string} newRole - the new role
  1366. * @param {Function} cb - gets called with the result
  1367. */
  1368. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1369. newRole = newRole.toLowerCase();
  1370. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1371. async.waterfall(
  1372. [
  1373. next => {
  1374. userModel.findOne({ _id: updatingUserId }, next);
  1375. },
  1376. (user, next) => {
  1377. if (!user) return next("User not found.");
  1378. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1379. return next();
  1380. },
  1381. next => {
  1382. userModel.updateOne(
  1383. { _id: updatingUserId },
  1384. { $set: { role: newRole } },
  1385. { runValidators: true },
  1386. next
  1387. );
  1388. }
  1389. ],
  1390. async err => {
  1391. if (err && err !== true) {
  1392. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1393. this.log(
  1394. "ERROR",
  1395. "UPDATE_ROLE",
  1396. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1397. );
  1398. return cb({ status: "failure", message: err });
  1399. }
  1400. this.log(
  1401. "SUCCESS",
  1402. "UPDATE_ROLE",
  1403. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1404. );
  1405. return cb({
  1406. status: "success",
  1407. message: "Role successfully updated."
  1408. });
  1409. }
  1410. );
  1411. }),
  1412. /**
  1413. * Updates a user's password
  1414. *
  1415. * @param {object} session - the session object automatically added by the websocket
  1416. * @param {string} previousPassword - the previous password
  1417. * @param {string} newPassword - the new password
  1418. * @param {Function} cb - gets called with the result
  1419. */
  1420. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1421. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1422. async.waterfall(
  1423. [
  1424. next => {
  1425. userModel.findOne({ _id: session.userId }, next);
  1426. },
  1427. (user, next) => {
  1428. if (!user.services.password) return next("This account does not have a password set.");
  1429. return next(null, user.services.password.password);
  1430. },
  1431. (storedPassword, next) => {
  1432. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1433. if (res) return next();
  1434. return next("Please enter the correct previous password.");
  1435. });
  1436. },
  1437. next => {
  1438. if (!DBModule.passwordValid(newPassword))
  1439. return next("Invalid new password. Check if it meets all the requirements.");
  1440. return next();
  1441. },
  1442. next => {
  1443. bcrypt.genSalt(10, next);
  1444. },
  1445. // hash the password
  1446. (salt, next) => {
  1447. bcrypt.hash(sha256(newPassword), salt, next);
  1448. },
  1449. (hashedPassword, next) => {
  1450. userModel.updateOne(
  1451. { _id: session.userId },
  1452. {
  1453. $set: {
  1454. "services.password.password": hashedPassword
  1455. }
  1456. },
  1457. next
  1458. );
  1459. }
  1460. ],
  1461. async err => {
  1462. if (err) {
  1463. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1464. this.log(
  1465. "ERROR",
  1466. "UPDATE_PASSWORD",
  1467. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1468. );
  1469. return cb({ status: "failure", message: err });
  1470. }
  1471. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1472. return cb({
  1473. status: "success",
  1474. message: "Password successfully updated."
  1475. });
  1476. }
  1477. );
  1478. }),
  1479. /**
  1480. * Requests a password for a session
  1481. *
  1482. * @param {object} session - the session object automatically added by the websocket
  1483. * @param {string} email - the email of the user that requests a password reset
  1484. * @param {Function} cb - gets called with the result
  1485. */
  1486. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1487. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1488. const passwordRequestSchema = await MailModule.runJob(
  1489. "GET_SCHEMA",
  1490. {
  1491. schemaName: "passwordRequest"
  1492. },
  1493. this
  1494. );
  1495. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1496. async.waterfall(
  1497. [
  1498. next => {
  1499. userModel.findOne({ _id: session.userId }, next);
  1500. },
  1501. (user, next) => {
  1502. if (!user) return next("User not found.");
  1503. if (user.services.password && user.services.password.password)
  1504. return next("You already have a password set.");
  1505. return next(null, user);
  1506. },
  1507. (user, next) => {
  1508. const expires = new Date();
  1509. expires.setDate(expires.getDate() + 1);
  1510. userModel.findOneAndUpdate(
  1511. { "email.address": user.email.address },
  1512. {
  1513. $set: {
  1514. "services.password": {
  1515. set: { code, expires }
  1516. }
  1517. }
  1518. },
  1519. { runValidators: true },
  1520. next
  1521. );
  1522. },
  1523. (user, next) => {
  1524. passwordRequestSchema(user.email.address, user.username, code, next);
  1525. }
  1526. ],
  1527. async err => {
  1528. if (err && err !== true) {
  1529. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1530. this.log(
  1531. "ERROR",
  1532. "REQUEST_PASSWORD",
  1533. `UserId '${session.userId}' failed to request password. '${err}'`
  1534. );
  1535. return cb({ status: "failure", message: err });
  1536. }
  1537. this.log(
  1538. "SUCCESS",
  1539. "REQUEST_PASSWORD",
  1540. `UserId '${session.userId}' successfully requested a password.`
  1541. );
  1542. return cb({
  1543. status: "success",
  1544. message: "Successfully requested password."
  1545. });
  1546. }
  1547. );
  1548. }),
  1549. /**
  1550. * Verifies a password code
  1551. *
  1552. * @param {object} session - the session object automatically added by the websocket
  1553. * @param {string} code - the password code
  1554. * @param {Function} cb - gets called with the result
  1555. */
  1556. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1557. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1558. async.waterfall(
  1559. [
  1560. next => {
  1561. if (!code || typeof code !== "string") return next("Invalid code.");
  1562. return userModel.findOne(
  1563. {
  1564. "services.password.set.code": code,
  1565. _id: session.userId
  1566. },
  1567. next
  1568. );
  1569. },
  1570. (user, next) => {
  1571. if (!user) return next("Invalid code.");
  1572. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1573. return next(null);
  1574. }
  1575. ],
  1576. async err => {
  1577. if (err && err !== true) {
  1578. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1579. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1580. cb({ status: "failure", message: err });
  1581. } else {
  1582. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1583. cb({
  1584. status: "success",
  1585. message: "Successfully verified password code."
  1586. });
  1587. }
  1588. }
  1589. );
  1590. }),
  1591. /**
  1592. * Adds a password to a user with a code
  1593. *
  1594. * @param {object} session - the session object automatically added by the websocket
  1595. * @param {string} code - the password code
  1596. * @param {string} newPassword - the new password code
  1597. * @param {Function} cb - gets called with the result
  1598. */
  1599. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1600. const userModel = await DBModule.runJob(
  1601. "GET_MODEL",
  1602. {
  1603. modelName: "user"
  1604. },
  1605. this
  1606. );
  1607. async.waterfall(
  1608. [
  1609. next => {
  1610. if (!code || typeof code !== "string") return next("Invalid code.");
  1611. return userModel.findOne({ "services.password.set.code": code }, next);
  1612. },
  1613. (user, next) => {
  1614. if (!user) return next("Invalid code.");
  1615. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1616. return next();
  1617. },
  1618. next => {
  1619. if (!DBModule.passwordValid(newPassword))
  1620. return next("Invalid password. Check if it meets all the requirements.");
  1621. return next();
  1622. },
  1623. next => {
  1624. bcrypt.genSalt(10, next);
  1625. },
  1626. // hash the password
  1627. (salt, next) => {
  1628. bcrypt.hash(sha256(newPassword), salt, next);
  1629. },
  1630. (hashedPassword, next) => {
  1631. userModel.updateOne(
  1632. { "services.password.set.code": code },
  1633. {
  1634. $set: {
  1635. "services.password.password": hashedPassword
  1636. },
  1637. $unset: { "services.password.set": "" }
  1638. },
  1639. { runValidators: true },
  1640. next
  1641. );
  1642. }
  1643. ],
  1644. async err => {
  1645. if (err && err !== true) {
  1646. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1647. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1648. return cb({ status: "failure", message: err });
  1649. }
  1650. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1651. CacheModule.runJob("PUB", {
  1652. channel: "user.linkPassword",
  1653. value: session.userId
  1654. });
  1655. return cb({
  1656. status: "success",
  1657. message: "Successfully added password."
  1658. });
  1659. }
  1660. );
  1661. }),
  1662. /**
  1663. * Unlinks password from user
  1664. *
  1665. * @param {object} session - the session object automatically added by the websocket
  1666. * @param {Function} cb - gets called with the result
  1667. */
  1668. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1669. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1670. async.waterfall(
  1671. [
  1672. next => {
  1673. userModel.findOne({ _id: session.userId }, next);
  1674. },
  1675. (user, next) => {
  1676. if (!user) return next("Not logged in.");
  1677. if (!user.services.github || !user.services.github.id)
  1678. return next("You can't remove password login without having GitHub login.");
  1679. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1680. }
  1681. ],
  1682. async err => {
  1683. if (err && err !== true) {
  1684. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1685. this.log(
  1686. "ERROR",
  1687. "UNLINK_PASSWORD",
  1688. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1689. );
  1690. return cb({ status: "failure", message: err });
  1691. }
  1692. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  1693. CacheModule.runJob("PUB", {
  1694. channel: "user.unlinkPassword",
  1695. value: session.userId
  1696. });
  1697. return cb({
  1698. status: "success",
  1699. message: "Successfully unlinked password."
  1700. });
  1701. }
  1702. );
  1703. }),
  1704. /**
  1705. * Unlinks GitHub from user
  1706. *
  1707. * @param {object} session - the session object automatically added by the websocket
  1708. * @param {Function} cb - gets called with the result
  1709. */
  1710. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1711. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1712. async.waterfall(
  1713. [
  1714. next => {
  1715. userModel.findOne({ _id: session.userId }, next);
  1716. },
  1717. (user, next) => {
  1718. if (!user) return next("Not logged in.");
  1719. if (!user.services.password || !user.services.password.password)
  1720. return next("You can't remove GitHub login without having password login.");
  1721. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1722. }
  1723. ],
  1724. async err => {
  1725. if (err && err !== true) {
  1726. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1727. this.log(
  1728. "ERROR",
  1729. "UNLINK_GITHUB",
  1730. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  1731. );
  1732. return cb({ status: "failure", message: err });
  1733. }
  1734. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  1735. CacheModule.runJob("PUB", {
  1736. channel: "user.unlinkGithub",
  1737. value: session.userId
  1738. });
  1739. return cb({
  1740. status: "success",
  1741. message: "Successfully unlinked GitHub."
  1742. });
  1743. }
  1744. );
  1745. }),
  1746. /**
  1747. * Requests a password reset for an email
  1748. *
  1749. * @param {object} session - the session object automatically added by the websocket
  1750. * @param {string} email - the email of the user that requests a password reset
  1751. * @param {Function} cb - gets called with the result
  1752. */
  1753. async requestPasswordReset(session, email, cb) {
  1754. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1755. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1756. const resetPasswordRequestSchema = await MailModule.runJob(
  1757. "GET_SCHEMA",
  1758. { schemaName: "resetPasswordRequest" },
  1759. this
  1760. );
  1761. async.waterfall(
  1762. [
  1763. next => {
  1764. if (!email || typeof email !== "string") return next("Invalid email.");
  1765. email = email.toLowerCase();
  1766. return userModel.findOne({ "email.address": email }, next);
  1767. },
  1768. (user, next) => {
  1769. if (!user) return next("User not found.");
  1770. if (!user.services.password || !user.services.password.password)
  1771. return next("User does not have a password set, and probably uses GitHub to log in.");
  1772. return next(null, user);
  1773. },
  1774. (user, next) => {
  1775. const expires = new Date();
  1776. expires.setDate(expires.getDate() + 1);
  1777. userModel.findOneAndUpdate(
  1778. { "email.address": email },
  1779. {
  1780. $set: {
  1781. "services.password.reset": {
  1782. code,
  1783. expires
  1784. }
  1785. }
  1786. },
  1787. { runValidators: true },
  1788. next
  1789. );
  1790. },
  1791. (user, next) => {
  1792. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  1793. }
  1794. ],
  1795. async err => {
  1796. if (err && err !== true) {
  1797. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1798. this.log(
  1799. "ERROR",
  1800. "REQUEST_PASSWORD_RESET",
  1801. `Email '${email}' failed to request password reset. '${err}'`
  1802. );
  1803. return cb({ status: "failure", message: err });
  1804. }
  1805. this.log(
  1806. "SUCCESS",
  1807. "REQUEST_PASSWORD_RESET",
  1808. `Email '${email}' successfully requested a password reset.`
  1809. );
  1810. return cb({
  1811. status: "success",
  1812. message: "Successfully requested password reset."
  1813. });
  1814. }
  1815. );
  1816. },
  1817. /**
  1818. * Verifies a reset code
  1819. *
  1820. * @param {object} session - the session object automatically added by the websocket
  1821. * @param {string} code - the password reset code
  1822. * @param {Function} cb - gets called with the result
  1823. */
  1824. async verifyPasswordResetCode(session, code, cb) {
  1825. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1826. async.waterfall(
  1827. [
  1828. next => {
  1829. if (!code || typeof code !== "string") return next("Invalid code.");
  1830. return userModel.findOne({ "services.password.reset.code": code }, next);
  1831. },
  1832. (user, next) => {
  1833. if (!user) return next("Invalid code.");
  1834. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1835. return next(null);
  1836. }
  1837. ],
  1838. async err => {
  1839. if (err && err !== true) {
  1840. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1841. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  1842. return cb({ status: "failure", message: err });
  1843. }
  1844. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  1845. return cb({
  1846. status: "success",
  1847. message: "Successfully verified password reset code."
  1848. });
  1849. }
  1850. );
  1851. },
  1852. /**
  1853. * Changes a user's password with a reset code
  1854. *
  1855. * @param {object} session - the session object automatically added by the websocket
  1856. * @param {string} code - the password reset code
  1857. * @param {string} newPassword - the new password reset code
  1858. * @param {Function} cb - gets called with the result
  1859. */
  1860. async changePasswordWithResetCode(session, code, newPassword, cb) {
  1861. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1862. async.waterfall(
  1863. [
  1864. next => {
  1865. if (!code || typeof code !== "string") return next("Invalid code.");
  1866. return userModel.findOne({ "services.password.reset.code": code }, next);
  1867. },
  1868. (user, next) => {
  1869. if (!user) return next("Invalid code.");
  1870. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1871. return next();
  1872. },
  1873. next => {
  1874. if (!DBModule.passwordValid(newPassword))
  1875. return next("Invalid password. Check if it meets all the requirements.");
  1876. return next();
  1877. },
  1878. next => {
  1879. bcrypt.genSalt(10, next);
  1880. },
  1881. // hash the password
  1882. (salt, next) => {
  1883. bcrypt.hash(sha256(newPassword), salt, next);
  1884. },
  1885. (hashedPassword, next) => {
  1886. userModel.updateOne(
  1887. { "services.password.reset.code": code },
  1888. {
  1889. $set: {
  1890. "services.password.password": hashedPassword
  1891. },
  1892. $unset: { "services.password.reset": "" }
  1893. },
  1894. { runValidators: true },
  1895. next
  1896. );
  1897. }
  1898. ],
  1899. async err => {
  1900. if (err && err !== true) {
  1901. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1902. this.log(
  1903. "ERROR",
  1904. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1905. `Code '${code}' failed to change password. '${err}'`
  1906. );
  1907. return cb({ status: "failure", message: err });
  1908. }
  1909. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  1910. return cb({
  1911. status: "success",
  1912. message: "Successfully changed password."
  1913. });
  1914. }
  1915. );
  1916. },
  1917. /**
  1918. * Bans a user by userId
  1919. *
  1920. * @param {object} session - the session object automatically added by the websocket
  1921. * @param {string} value - the user id that is going to be banned
  1922. * @param {string} reason - the reason for the ban
  1923. * @param {string} expiresAt - the time the ban expires
  1924. * @param {Function} cb - gets called with the result
  1925. */
  1926. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  1927. async.waterfall(
  1928. [
  1929. next => {
  1930. if (!userId) return next("You must provide a userId to ban.");
  1931. if (!reason) return next("You must provide a reason for the ban.");
  1932. return next();
  1933. },
  1934. next => {
  1935. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  1936. const date = new Date();
  1937. switch (expiresAt) {
  1938. case "1h":
  1939. expiresAt = date.setHours(date.getHours() + 1);
  1940. break;
  1941. case "12h":
  1942. expiresAt = date.setHours(date.getHours() + 12);
  1943. break;
  1944. case "1d":
  1945. expiresAt = date.setDate(date.getDate() + 1);
  1946. break;
  1947. case "1w":
  1948. expiresAt = date.setDate(date.getDate() + 7);
  1949. break;
  1950. case "1m":
  1951. expiresAt = date.setMonth(date.getMonth() + 1);
  1952. break;
  1953. case "3m":
  1954. expiresAt = date.setMonth(date.getMonth() + 3);
  1955. break;
  1956. case "6m":
  1957. expiresAt = date.setMonth(date.getMonth() + 6);
  1958. break;
  1959. case "1y":
  1960. expiresAt = date.setFullYear(date.getFullYear() + 1);
  1961. break;
  1962. case "never":
  1963. expiresAt = new Date(3093527980800000);
  1964. break;
  1965. default:
  1966. return next("Invalid expire date.");
  1967. }
  1968. return next();
  1969. },
  1970. next => {
  1971. PunishmentsModule.runJob(
  1972. "ADD_PUNISHMENT",
  1973. {
  1974. type: "banUserId",
  1975. value: userId,
  1976. reason,
  1977. expiresAt,
  1978. punishedBy: "" // needs changed
  1979. },
  1980. this
  1981. )
  1982. .then(punishment => next(null, punishment))
  1983. .catch(next);
  1984. },
  1985. (punishment, next) => {
  1986. CacheModule.runJob("PUB", {
  1987. channel: "user.ban",
  1988. value: { userId, punishment }
  1989. });
  1990. next();
  1991. }
  1992. ],
  1993. async err => {
  1994. if (err && err !== true) {
  1995. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1996. this.log(
  1997. "ERROR",
  1998. "BAN_USER_BY_ID",
  1999. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2000. );
  2001. return cb({ status: "failure", message: err });
  2002. }
  2003. this.log(
  2004. "SUCCESS",
  2005. "BAN_USER_BY_ID",
  2006. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2007. );
  2008. return cb({
  2009. status: "success",
  2010. message: "Successfully banned user."
  2011. });
  2012. }
  2013. );
  2014. })
  2015. };