users.js 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273
  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 {boolean} preferences.anonymousSongRequests - whether or not a user's requested songs will be anonymous
  667. * @param {boolean} preferences.activityWatch - whether or not a user is using the ActivityWatch integration
  668. * @param {Function} cb - gets called with the result
  669. */
  670. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  671. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  672. async.waterfall(
  673. [
  674. next => {
  675. userModel.findByIdAndUpdate(
  676. session.userId,
  677. {
  678. $set: {
  679. preferences: {
  680. nightmode: preferences.nightmode,
  681. autoSkipDisliked: preferences.autoSkipDisliked,
  682. activityLogPublic: preferences.activityLogPublic,
  683. anonymousSongRequests: preferences.anonymousSongRequests,
  684. activityWatch: preferences.activityWatch
  685. }
  686. }
  687. },
  688. { new: false },
  689. next
  690. );
  691. }
  692. ],
  693. async (err, user) => {
  694. if (err) {
  695. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  696. this.log(
  697. "ERROR",
  698. "UPDATE_USER_PREFERENCES",
  699. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  700. preferences
  701. )}". "${err}"`
  702. );
  703. return cb({ status: "failure", message: err });
  704. }
  705. CacheModule.runJob("PUB", {
  706. channel: "user.updatePreferences",
  707. value: {
  708. preferences,
  709. userId: session.userId
  710. }
  711. });
  712. if (preferences.nightmode !== user.preferences.nightmode)
  713. ActivitiesModule.runJob("ADD_ACTIVITY", {
  714. userId: session.userId,
  715. type: "user__toggle_nightmode",
  716. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  717. });
  718. if (preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked)
  719. ActivitiesModule.runJob("ADD_ACTIVITY", {
  720. userId: session.userId,
  721. type: "user__toggle_autoskip_disliked_songs",
  722. payload: {
  723. message: preferences.autoSkipDisliked
  724. ? "Enabled the autoskipping of disliked songs"
  725. : "Disabled the autoskipping of disliked songs"
  726. }
  727. });
  728. if (preferences.activityWatch !== user.preferences.activityWatch)
  729. ActivitiesModule.runJob("ADD_ACTIVITY", {
  730. userId: session.userId,
  731. type: "user__toggle_activity_watch",
  732. payload: {
  733. message: preferences.activityWatch
  734. ? "Enabled ActivityWatch integration"
  735. : "Disabled ActivityWatch integration"
  736. }
  737. });
  738. this.log(
  739. "SUCCESS",
  740. "UPDATE_USER_PREFERENCES",
  741. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  742. );
  743. return cb({
  744. status: "success",
  745. message: "Preferences successfully updated"
  746. });
  747. }
  748. );
  749. }),
  750. /**
  751. * Retrieves a user's preferences
  752. *
  753. * @param {object} session - the session object automatically added by the websocket
  754. * @param {Function} cb - gets called with the result
  755. */
  756. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  757. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  758. async.waterfall(
  759. [
  760. next => {
  761. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  762. }
  763. ],
  764. async (err, { preferences }) => {
  765. if (err) {
  766. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  767. this.log(
  768. "ERROR",
  769. "GET_USER_PREFERENCES",
  770. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  771. );
  772. return cb({ status: "failure", message: err });
  773. }
  774. this.log(
  775. "SUCCESS",
  776. "GET_USER_PREFERENCES",
  777. `Successfully obtained preferences for user "${session.userId}".`
  778. );
  779. return cb({
  780. status: "success",
  781. message: "Preferences successfully retrieved",
  782. data: preferences
  783. });
  784. }
  785. );
  786. }),
  787. /**
  788. * Gets user object from username (only a few properties)
  789. *
  790. * @param {object} session - the session object automatically added by the websocket
  791. * @param {string} username - the username of the user we are trying to find
  792. * @param {Function} cb - gets called with the result
  793. */
  794. findByUsername: async function findByUsername(session, username, cb) {
  795. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  796. async.waterfall(
  797. [
  798. next => {
  799. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  800. },
  801. (account, next) => {
  802. if (!account) return next("User not found.");
  803. return next(null, account);
  804. }
  805. ],
  806. async (err, account) => {
  807. if (err && err !== true) {
  808. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  809. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  810. return cb({ status: "failure", message: err });
  811. }
  812. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  813. return cb({
  814. status: "success",
  815. data: {
  816. _id: account._id,
  817. name: account.name,
  818. username: account.username,
  819. location: account.location,
  820. bio: account.bio,
  821. role: account.role,
  822. avatar: account.avatar,
  823. createdAt: account.createdAt
  824. }
  825. });
  826. }
  827. );
  828. },
  829. /**
  830. * Gets a username from an userId
  831. *
  832. * @param {object} session - the session object automatically added by the websocket
  833. * @param {string} userId - the userId of the person we are trying to get the username from
  834. * @param {Function} cb - gets called with the result
  835. */
  836. async getUsernameFromId(session, userId, cb) {
  837. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  838. userModel
  839. .findById(userId)
  840. .then(user => {
  841. if (user) {
  842. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  843. return cb({
  844. status: "success",
  845. data: user.username
  846. });
  847. }
  848. this.log(
  849. "ERROR",
  850. "GET_USERNAME_FROM_ID",
  851. `Getting the username from userId "${userId}" failed. User not found.`
  852. );
  853. return cb({
  854. status: "failure",
  855. message: "Couldn't find the user."
  856. });
  857. })
  858. .catch(async err => {
  859. if (err && err !== true) {
  860. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  861. this.log(
  862. "ERROR",
  863. "GET_USERNAME_FROM_ID",
  864. `Getting the username from userId "${userId}" failed. "${err}"`
  865. );
  866. cb({ status: "failure", message: err });
  867. }
  868. });
  869. },
  870. /**
  871. * Gets a user from a userId
  872. *
  873. * @param {object} session - the session object automatically added by the websocket
  874. * @param {string} userId - the userId of the person we are trying to get the username from
  875. * @param {Function} cb - gets called with the result
  876. */
  877. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  878. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  879. userModel
  880. .findById(userId)
  881. .then(user => {
  882. if (user) {
  883. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  884. return cb({
  885. status: "success",
  886. data: {
  887. _id: user._id,
  888. username: user.username,
  889. role: user.role,
  890. liked: user.liked,
  891. disliked: user.disliked,
  892. songsRequested: user.statistics.songsRequested,
  893. email: {
  894. address: user.email.address,
  895. verified: user.email.verified
  896. },
  897. hasPassword: !!user.services.password,
  898. services: { github: user.services.github }
  899. }
  900. });
  901. }
  902. this.log(
  903. "ERROR",
  904. "GET_USER_FROM_ID",
  905. `Getting the user from userId "${userId}" failed. User not found.`
  906. );
  907. return cb({
  908. status: "failure",
  909. message: "Couldn't find the user."
  910. });
  911. })
  912. .catch(async err => {
  913. if (err && err !== true) {
  914. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  915. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  916. cb({ status: "failure", message: err });
  917. }
  918. });
  919. }),
  920. // TODO Fix security issues
  921. /**
  922. * Gets user info from session
  923. *
  924. * @param {object} session - the session object automatically added by the websocket
  925. * @param {Function} cb - gets called with the result
  926. */
  927. async findBySession(session, cb) {
  928. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  929. async.waterfall(
  930. [
  931. next => {
  932. CacheModule.runJob(
  933. "HGET",
  934. {
  935. table: "sessions",
  936. key: session.sessionId
  937. },
  938. this
  939. )
  940. .then(session => next(null, session))
  941. .catch(next);
  942. },
  943. (session, next) => {
  944. if (!session) return next("Session not found.");
  945. return next(null, session);
  946. },
  947. (session, next) => {
  948. userModel.findOne({ _id: session.userId }, next);
  949. },
  950. (user, next) => {
  951. if (!user) return next("User not found.");
  952. return next(null, user);
  953. }
  954. ],
  955. async (err, user) => {
  956. if (err && err !== true) {
  957. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  958. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  959. return cb({ status: "failure", message: err });
  960. }
  961. const data = {
  962. email: {
  963. address: user.email.address
  964. },
  965. avatar: user.avatar,
  966. username: user.username,
  967. name: user.name,
  968. location: user.location,
  969. bio: user.bio
  970. };
  971. if (user.services.password && user.services.password.password) data.password = true;
  972. if (user.services.github && user.services.github.id) data.github = true;
  973. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  974. return cb({
  975. status: "success",
  976. data
  977. });
  978. }
  979. );
  980. },
  981. /**
  982. * Updates a user's username
  983. *
  984. * @param {object} session - the session object automatically added by the websocket
  985. * @param {string} updatingUserId - the updating user's id
  986. * @param {string} newUsername - the new username
  987. * @param {Function} cb - gets called with the result
  988. */
  989. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  990. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  991. async.waterfall(
  992. [
  993. next => {
  994. if (updatingUserId === session.userId) return next(null, true);
  995. return userModel.findOne({ _id: session.userId }, next);
  996. },
  997. (user, next) => {
  998. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  999. return userModel.findOne({ _id: updatingUserId }, next);
  1000. },
  1001. (user, next) => {
  1002. if (!user) return next("User not found.");
  1003. if (user.username === newUsername)
  1004. return next("New username can't be the same as the old username.");
  1005. return next(null);
  1006. },
  1007. next => {
  1008. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1009. },
  1010. (user, next) => {
  1011. if (!user) return next();
  1012. if (user._id === updatingUserId) return next();
  1013. return next("That username is already in use.");
  1014. },
  1015. next => {
  1016. userModel.updateOne(
  1017. { _id: updatingUserId },
  1018. { $set: { username: newUsername } },
  1019. { runValidators: true },
  1020. next
  1021. );
  1022. }
  1023. ],
  1024. async err => {
  1025. if (err && err !== true) {
  1026. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1027. this.log(
  1028. "ERROR",
  1029. "UPDATE_USERNAME",
  1030. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1031. );
  1032. return cb({ status: "failure", message: err });
  1033. }
  1034. CacheModule.runJob("PUB", {
  1035. channel: "user.updateUsername",
  1036. value: {
  1037. username: newUsername,
  1038. _id: updatingUserId
  1039. }
  1040. });
  1041. this.log(
  1042. "SUCCESS",
  1043. "UPDATE_USERNAME",
  1044. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1045. );
  1046. return cb({
  1047. status: "success",
  1048. message: "Username updated successfully"
  1049. });
  1050. }
  1051. );
  1052. }),
  1053. /**
  1054. * Updates a user's email
  1055. *
  1056. * @param {object} session - the session object automatically added by the websocket
  1057. * @param {string} updatingUserId - the updating user's id
  1058. * @param {string} newEmail - the new email
  1059. * @param {Function} cb - gets called with the result
  1060. */
  1061. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1062. newEmail = newEmail.toLowerCase();
  1063. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1064. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1065. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1066. async.waterfall(
  1067. [
  1068. next => {
  1069. if (updatingUserId === session.userId) return next(null, true);
  1070. return userModel.findOne({ _id: session.userId }, next);
  1071. },
  1072. (user, next) => {
  1073. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1074. return userModel.findOne({ _id: updatingUserId }, next);
  1075. },
  1076. (user, next) => {
  1077. if (!user) return next("User not found.");
  1078. if (user.email.address === newEmail)
  1079. return next("New email can't be the same as your the old email.");
  1080. return next();
  1081. },
  1082. next => {
  1083. userModel.findOne({ "email.address": newEmail }, next);
  1084. },
  1085. (user, next) => {
  1086. if (!user) return next();
  1087. if (user._id === updatingUserId) return next();
  1088. return next("That email is already in use.");
  1089. },
  1090. // regenerate the url for gravatar avatar
  1091. next => {
  1092. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1093. next(null, url);
  1094. });
  1095. },
  1096. (newAvatarUrl, next) => {
  1097. userModel.updateOne(
  1098. { _id: updatingUserId },
  1099. {
  1100. $set: {
  1101. "avatar.url": newAvatarUrl,
  1102. "email.address": newEmail,
  1103. "email.verified": false,
  1104. "email.verificationToken": verificationToken
  1105. }
  1106. },
  1107. { runValidators: true },
  1108. next
  1109. );
  1110. },
  1111. (res, next) => {
  1112. userModel.findOne({ _id: updatingUserId }, next);
  1113. },
  1114. (user, next) => {
  1115. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1116. next(err);
  1117. });
  1118. }
  1119. ],
  1120. async err => {
  1121. if (err && err !== true) {
  1122. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1123. this.log(
  1124. "ERROR",
  1125. "UPDATE_EMAIL",
  1126. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1127. );
  1128. return cb({ status: "failure", message: err });
  1129. }
  1130. this.log(
  1131. "SUCCESS",
  1132. "UPDATE_EMAIL",
  1133. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1134. );
  1135. return cb({
  1136. status: "success",
  1137. message: "Email updated successfully."
  1138. });
  1139. }
  1140. );
  1141. }),
  1142. /**
  1143. * Updates a user's name
  1144. *
  1145. * @param {object} session - the session object automatically added by the websocket
  1146. * @param {string} updatingUserId - the updating user's id
  1147. * @param {string} newBio - the new name
  1148. * @param {Function} cb - gets called with the result
  1149. */
  1150. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1151. const userModel = await DBModule.runJob(
  1152. "GET_MODEL",
  1153. {
  1154. modelName: "user"
  1155. },
  1156. this
  1157. );
  1158. async.waterfall(
  1159. [
  1160. next => {
  1161. if (updatingUserId === session.userId) return next(null, true);
  1162. return userModel.findOne({ _id: session.userId }, next);
  1163. },
  1164. (user, next) => {
  1165. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1166. return userModel.findOne({ _id: updatingUserId }, next);
  1167. },
  1168. (user, next) => {
  1169. if (!user) return next("User not found.");
  1170. return userModel.updateOne(
  1171. { _id: updatingUserId },
  1172. { $set: { name: newName } },
  1173. { runValidators: true },
  1174. next
  1175. );
  1176. }
  1177. ],
  1178. async err => {
  1179. if (err && err !== true) {
  1180. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1181. this.log(
  1182. "ERROR",
  1183. "UPDATE_NAME",
  1184. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1185. );
  1186. return cb({ status: "failure", message: err });
  1187. }
  1188. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1189. userId: updatingUserId,
  1190. type: "user__edit_name",
  1191. payload: { message: `Changed name to ${newName}` }
  1192. });
  1193. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1194. return cb({
  1195. status: "success",
  1196. message: "Name updated successfully"
  1197. });
  1198. }
  1199. );
  1200. }),
  1201. /**
  1202. * Updates a user's location
  1203. *
  1204. * @param {object} session - the session object automatically added by the websocket
  1205. * @param {string} updatingUserId - the updating user's id
  1206. * @param {string} newLocation - the new location
  1207. * @param {Function} cb - gets called with the result
  1208. */
  1209. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1210. const userModel = await DBModule.runJob(
  1211. "GET_MODEL",
  1212. {
  1213. modelName: "user"
  1214. },
  1215. this
  1216. );
  1217. async.waterfall(
  1218. [
  1219. next => {
  1220. if (updatingUserId === session.userId) return next(null, true);
  1221. return userModel.findOne({ _id: session.userId }, next);
  1222. },
  1223. (user, next) => {
  1224. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1225. return userModel.findOne({ _id: updatingUserId }, next);
  1226. },
  1227. (user, next) => {
  1228. if (!user) return next("User not found.");
  1229. return userModel.updateOne(
  1230. { _id: updatingUserId },
  1231. { $set: { location: newLocation } },
  1232. { runValidators: true },
  1233. next
  1234. );
  1235. }
  1236. ],
  1237. async err => {
  1238. if (err && err !== true) {
  1239. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1240. this.log(
  1241. "ERROR",
  1242. "UPDATE_LOCATION",
  1243. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1244. );
  1245. return cb({ status: "failure", message: err });
  1246. }
  1247. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1248. userId: updatingUserId,
  1249. type: "user__edit_location",
  1250. payload: { message: `Changed location to ${newLocation}` }
  1251. });
  1252. this.log(
  1253. "SUCCESS",
  1254. "UPDATE_LOCATION",
  1255. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1256. );
  1257. return cb({
  1258. status: "success",
  1259. message: "Location updated successfully"
  1260. });
  1261. }
  1262. );
  1263. }),
  1264. /**
  1265. * Updates a user's bio
  1266. *
  1267. * @param {object} session - the session object automatically added by the websocket
  1268. * @param {string} updatingUserId - the updating user's id
  1269. * @param {string} newBio - the new bio
  1270. * @param {Function} cb - gets called with the result
  1271. */
  1272. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1273. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1274. async.waterfall(
  1275. [
  1276. next => {
  1277. if (updatingUserId === session.userId) return next(null, true);
  1278. return userModel.findOne({ _id: session.userId }, next);
  1279. },
  1280. (user, next) => {
  1281. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1282. return userModel.findOne({ _id: updatingUserId }, next);
  1283. },
  1284. (user, next) => {
  1285. if (!user) return next("User not found.");
  1286. return userModel.updateOne(
  1287. { _id: updatingUserId },
  1288. { $set: { bio: newBio } },
  1289. { runValidators: true },
  1290. next
  1291. );
  1292. }
  1293. ],
  1294. async err => {
  1295. if (err && err !== true) {
  1296. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1297. this.log(
  1298. "ERROR",
  1299. "UPDATE_BIO",
  1300. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1301. );
  1302. return cb({ status: "failure", message: err });
  1303. }
  1304. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1305. userId: updatingUserId,
  1306. type: "user__edit_bio",
  1307. payload: { message: `Changed bio to ${newBio}` }
  1308. });
  1309. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1310. return cb({
  1311. status: "success",
  1312. message: "Bio updated successfully"
  1313. });
  1314. }
  1315. );
  1316. }),
  1317. /**
  1318. * Updates the type of a user's avatar
  1319. *
  1320. * @param {object} session - the session object automatically added by the websocket
  1321. * @param {string} updatingUserId - the updating user's id
  1322. * @param {string} newType - the new type
  1323. * @param {Function} cb - gets called with the result
  1324. */
  1325. updateAvatarType: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1326. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1327. async.waterfall(
  1328. [
  1329. next => {
  1330. if (updatingUserId === session.userId) return next(null, true);
  1331. return userModel.findOne({ _id: session.userId }, next);
  1332. },
  1333. (user, next) => {
  1334. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1335. return userModel.findOne({ _id: updatingUserId }, next);
  1336. },
  1337. (user, next) => {
  1338. if (!user) return next("User not found.");
  1339. return userModel.findOneAndUpdate(
  1340. { _id: updatingUserId },
  1341. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1342. { new: true, runValidators: true },
  1343. next
  1344. );
  1345. }
  1346. ],
  1347. async err => {
  1348. if (err && err !== true) {
  1349. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1350. this.log(
  1351. "ERROR",
  1352. "UPDATE_AVATAR_TYPE",
  1353. `Couldn't update avatar type for user "${updatingUserId}" to type "${newAvatar.type}". "${err}"`
  1354. );
  1355. return cb({ status: "failure", message: err });
  1356. }
  1357. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1358. userId: updatingUserId,
  1359. type: "user__edit_avatar",
  1360. payload: { message: `Changed avatar to use ${newAvatar.type}` }
  1361. });
  1362. this.log(
  1363. "SUCCESS",
  1364. "UPDATE_AVATAR_TYPE",
  1365. `Updated avatar type for user "${updatingUserId}" to type "${newAvatar.type}".`
  1366. );
  1367. return cb({
  1368. status: "success",
  1369. message: "Avatar type updated successfully"
  1370. });
  1371. }
  1372. );
  1373. }),
  1374. /**
  1375. * Updates a user's role
  1376. *
  1377. * @param {object} session - the session object automatically added by the websocket
  1378. * @param {string} updatingUserId - the updating user's id
  1379. * @param {string} newRole - the new role
  1380. * @param {Function} cb - gets called with the result
  1381. */
  1382. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1383. newRole = newRole.toLowerCase();
  1384. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1385. async.waterfall(
  1386. [
  1387. next => {
  1388. userModel.findOne({ _id: updatingUserId }, next);
  1389. },
  1390. (user, next) => {
  1391. if (!user) return next("User not found.");
  1392. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1393. return next();
  1394. },
  1395. next => {
  1396. userModel.updateOne(
  1397. { _id: updatingUserId },
  1398. { $set: { role: newRole } },
  1399. { runValidators: true },
  1400. next
  1401. );
  1402. }
  1403. ],
  1404. async err => {
  1405. if (err && err !== true) {
  1406. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1407. this.log(
  1408. "ERROR",
  1409. "UPDATE_ROLE",
  1410. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1411. );
  1412. return cb({ status: "failure", message: err });
  1413. }
  1414. this.log(
  1415. "SUCCESS",
  1416. "UPDATE_ROLE",
  1417. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1418. );
  1419. return cb({
  1420. status: "success",
  1421. message: "Role successfully updated."
  1422. });
  1423. }
  1424. );
  1425. }),
  1426. /**
  1427. * Updates a user's password
  1428. *
  1429. * @param {object} session - the session object automatically added by the websocket
  1430. * @param {string} previousPassword - the previous password
  1431. * @param {string} newPassword - the new password
  1432. * @param {Function} cb - gets called with the result
  1433. */
  1434. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1435. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1436. async.waterfall(
  1437. [
  1438. next => {
  1439. userModel.findOne({ _id: session.userId }, next);
  1440. },
  1441. (user, next) => {
  1442. if (!user.services.password) return next("This account does not have a password set.");
  1443. return next(null, user.services.password.password);
  1444. },
  1445. (storedPassword, next) => {
  1446. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1447. if (res) return next();
  1448. return next("Please enter the correct previous password.");
  1449. });
  1450. },
  1451. next => {
  1452. if (!DBModule.passwordValid(newPassword))
  1453. return next("Invalid new password. Check if it meets all the requirements.");
  1454. return next();
  1455. },
  1456. next => {
  1457. bcrypt.genSalt(10, next);
  1458. },
  1459. // hash the password
  1460. (salt, next) => {
  1461. bcrypt.hash(sha256(newPassword), salt, next);
  1462. },
  1463. (hashedPassword, next) => {
  1464. userModel.updateOne(
  1465. { _id: session.userId },
  1466. {
  1467. $set: {
  1468. "services.password.password": hashedPassword
  1469. }
  1470. },
  1471. next
  1472. );
  1473. }
  1474. ],
  1475. async err => {
  1476. if (err) {
  1477. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1478. this.log(
  1479. "ERROR",
  1480. "UPDATE_PASSWORD",
  1481. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1482. );
  1483. return cb({ status: "failure", message: err });
  1484. }
  1485. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1486. return cb({
  1487. status: "success",
  1488. message: "Password successfully updated."
  1489. });
  1490. }
  1491. );
  1492. }),
  1493. /**
  1494. * Requests a password for a session
  1495. *
  1496. * @param {object} session - the session object automatically added by the websocket
  1497. * @param {string} email - the email of the user that requests a password reset
  1498. * @param {Function} cb - gets called with the result
  1499. */
  1500. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1501. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1502. const passwordRequestSchema = await MailModule.runJob(
  1503. "GET_SCHEMA",
  1504. {
  1505. schemaName: "passwordRequest"
  1506. },
  1507. this
  1508. );
  1509. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1510. async.waterfall(
  1511. [
  1512. next => {
  1513. userModel.findOne({ _id: session.userId }, next);
  1514. },
  1515. (user, next) => {
  1516. if (!user) return next("User not found.");
  1517. if (user.services.password && user.services.password.password)
  1518. return next("You already have a password set.");
  1519. return next(null, user);
  1520. },
  1521. (user, next) => {
  1522. const expires = new Date();
  1523. expires.setDate(expires.getDate() + 1);
  1524. userModel.findOneAndUpdate(
  1525. { "email.address": user.email.address },
  1526. {
  1527. $set: {
  1528. "services.password": {
  1529. set: { code, expires }
  1530. }
  1531. }
  1532. },
  1533. { runValidators: true },
  1534. next
  1535. );
  1536. },
  1537. (user, next) => {
  1538. passwordRequestSchema(user.email.address, user.username, code, next);
  1539. }
  1540. ],
  1541. async err => {
  1542. if (err && err !== true) {
  1543. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1544. this.log(
  1545. "ERROR",
  1546. "REQUEST_PASSWORD",
  1547. `UserId '${session.userId}' failed to request password. '${err}'`
  1548. );
  1549. return cb({ status: "failure", message: err });
  1550. }
  1551. this.log(
  1552. "SUCCESS",
  1553. "REQUEST_PASSWORD",
  1554. `UserId '${session.userId}' successfully requested a password.`
  1555. );
  1556. return cb({
  1557. status: "success",
  1558. message: "Successfully requested password."
  1559. });
  1560. }
  1561. );
  1562. }),
  1563. /**
  1564. * Verifies a password code
  1565. *
  1566. * @param {object} session - the session object automatically added by the websocket
  1567. * @param {string} code - the password code
  1568. * @param {Function} cb - gets called with the result
  1569. */
  1570. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1571. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1572. async.waterfall(
  1573. [
  1574. next => {
  1575. if (!code || typeof code !== "string") return next("Invalid code.");
  1576. return userModel.findOne(
  1577. {
  1578. "services.password.set.code": code,
  1579. _id: session.userId
  1580. },
  1581. next
  1582. );
  1583. },
  1584. (user, next) => {
  1585. if (!user) return next("Invalid code.");
  1586. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1587. return next(null);
  1588. }
  1589. ],
  1590. async err => {
  1591. if (err && err !== true) {
  1592. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1593. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1594. cb({ status: "failure", message: err });
  1595. } else {
  1596. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1597. cb({
  1598. status: "success",
  1599. message: "Successfully verified password code."
  1600. });
  1601. }
  1602. }
  1603. );
  1604. }),
  1605. /**
  1606. * Adds a password to a user with a code
  1607. *
  1608. * @param {object} session - the session object automatically added by the websocket
  1609. * @param {string} code - the password code
  1610. * @param {string} newPassword - the new password code
  1611. * @param {Function} cb - gets called with the result
  1612. */
  1613. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1614. const userModel = await DBModule.runJob(
  1615. "GET_MODEL",
  1616. {
  1617. modelName: "user"
  1618. },
  1619. this
  1620. );
  1621. async.waterfall(
  1622. [
  1623. next => {
  1624. if (!code || typeof code !== "string") return next("Invalid code.");
  1625. return userModel.findOne({ "services.password.set.code": code }, next);
  1626. },
  1627. (user, next) => {
  1628. if (!user) return next("Invalid code.");
  1629. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1630. return next();
  1631. },
  1632. next => {
  1633. if (!DBModule.passwordValid(newPassword))
  1634. return next("Invalid password. Check if it meets all the requirements.");
  1635. return next();
  1636. },
  1637. next => {
  1638. bcrypt.genSalt(10, next);
  1639. },
  1640. // hash the password
  1641. (salt, next) => {
  1642. bcrypt.hash(sha256(newPassword), salt, next);
  1643. },
  1644. (hashedPassword, next) => {
  1645. userModel.updateOne(
  1646. { "services.password.set.code": code },
  1647. {
  1648. $set: {
  1649. "services.password.password": hashedPassword
  1650. },
  1651. $unset: { "services.password.set": "" }
  1652. },
  1653. { runValidators: true },
  1654. next
  1655. );
  1656. }
  1657. ],
  1658. async err => {
  1659. if (err && err !== true) {
  1660. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1661. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1662. return cb({ status: "failure", message: err });
  1663. }
  1664. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1665. CacheModule.runJob("PUB", {
  1666. channel: "user.linkPassword",
  1667. value: session.userId
  1668. });
  1669. return cb({
  1670. status: "success",
  1671. message: "Successfully added password."
  1672. });
  1673. }
  1674. );
  1675. }),
  1676. /**
  1677. * Unlinks password from user
  1678. *
  1679. * @param {object} session - the session object automatically added by the websocket
  1680. * @param {Function} cb - gets called with the result
  1681. */
  1682. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1683. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1684. async.waterfall(
  1685. [
  1686. next => {
  1687. userModel.findOne({ _id: session.userId }, next);
  1688. },
  1689. (user, next) => {
  1690. if (!user) return next("Not logged in.");
  1691. if (!user.services.github || !user.services.github.id)
  1692. return next("You can't remove password login without having GitHub login.");
  1693. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1694. }
  1695. ],
  1696. async err => {
  1697. if (err && err !== true) {
  1698. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1699. this.log(
  1700. "ERROR",
  1701. "UNLINK_PASSWORD",
  1702. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1703. );
  1704. return cb({ status: "failure", message: err });
  1705. }
  1706. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  1707. CacheModule.runJob("PUB", {
  1708. channel: "user.unlinkPassword",
  1709. value: session.userId
  1710. });
  1711. return cb({
  1712. status: "success",
  1713. message: "Successfully unlinked password."
  1714. });
  1715. }
  1716. );
  1717. }),
  1718. /**
  1719. * Unlinks GitHub from user
  1720. *
  1721. * @param {object} session - the session object automatically added by the websocket
  1722. * @param {Function} cb - gets called with the result
  1723. */
  1724. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1725. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1726. async.waterfall(
  1727. [
  1728. next => {
  1729. userModel.findOne({ _id: session.userId }, next);
  1730. },
  1731. (user, next) => {
  1732. if (!user) return next("Not logged in.");
  1733. if (!user.services.password || !user.services.password.password)
  1734. return next("You can't remove GitHub login without having password login.");
  1735. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1736. }
  1737. ],
  1738. async err => {
  1739. if (err && err !== true) {
  1740. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1741. this.log(
  1742. "ERROR",
  1743. "UNLINK_GITHUB",
  1744. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  1745. );
  1746. return cb({ status: "failure", message: err });
  1747. }
  1748. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  1749. CacheModule.runJob("PUB", {
  1750. channel: "user.unlinkGithub",
  1751. value: session.userId
  1752. });
  1753. return cb({
  1754. status: "success",
  1755. message: "Successfully unlinked GitHub."
  1756. });
  1757. }
  1758. );
  1759. }),
  1760. /**
  1761. * Requests a password reset for an email
  1762. *
  1763. * @param {object} session - the session object automatically added by the websocket
  1764. * @param {string} email - the email of the user that requests a password reset
  1765. * @param {Function} cb - gets called with the result
  1766. */
  1767. async requestPasswordReset(session, email, cb) {
  1768. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1769. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1770. const resetPasswordRequestSchema = await MailModule.runJob(
  1771. "GET_SCHEMA",
  1772. { schemaName: "resetPasswordRequest" },
  1773. this
  1774. );
  1775. async.waterfall(
  1776. [
  1777. next => {
  1778. if (!email || typeof email !== "string") return next("Invalid email.");
  1779. email = email.toLowerCase();
  1780. return userModel.findOne({ "email.address": email }, next);
  1781. },
  1782. (user, next) => {
  1783. if (!user) return next("User not found.");
  1784. if (!user.services.password || !user.services.password.password)
  1785. return next("User does not have a password set, and probably uses GitHub to log in.");
  1786. return next(null, user);
  1787. },
  1788. (user, next) => {
  1789. const expires = new Date();
  1790. expires.setDate(expires.getDate() + 1);
  1791. userModel.findOneAndUpdate(
  1792. { "email.address": email },
  1793. {
  1794. $set: {
  1795. "services.password.reset": {
  1796. code,
  1797. expires
  1798. }
  1799. }
  1800. },
  1801. { runValidators: true },
  1802. next
  1803. );
  1804. },
  1805. (user, next) => {
  1806. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  1807. }
  1808. ],
  1809. async err => {
  1810. if (err && err !== true) {
  1811. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1812. this.log(
  1813. "ERROR",
  1814. "REQUEST_PASSWORD_RESET",
  1815. `Email '${email}' failed to request password reset. '${err}'`
  1816. );
  1817. return cb({ status: "failure", message: err });
  1818. }
  1819. this.log(
  1820. "SUCCESS",
  1821. "REQUEST_PASSWORD_RESET",
  1822. `Email '${email}' successfully requested a password reset.`
  1823. );
  1824. return cb({
  1825. status: "success",
  1826. message: "Successfully requested password reset."
  1827. });
  1828. }
  1829. );
  1830. },
  1831. /**
  1832. * Verifies a reset code
  1833. *
  1834. * @param {object} session - the session object automatically added by the websocket
  1835. * @param {string} code - the password reset code
  1836. * @param {Function} cb - gets called with the result
  1837. */
  1838. async verifyPasswordResetCode(session, code, cb) {
  1839. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1840. async.waterfall(
  1841. [
  1842. next => {
  1843. if (!code || typeof code !== "string") return next("Invalid code.");
  1844. return userModel.findOne({ "services.password.reset.code": code }, next);
  1845. },
  1846. (user, next) => {
  1847. if (!user) return next("Invalid code.");
  1848. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1849. return next(null);
  1850. }
  1851. ],
  1852. async err => {
  1853. if (err && err !== true) {
  1854. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1855. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  1856. return cb({ status: "failure", message: err });
  1857. }
  1858. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  1859. return cb({
  1860. status: "success",
  1861. message: "Successfully verified password reset code."
  1862. });
  1863. }
  1864. );
  1865. },
  1866. /**
  1867. * Changes a user's password with a reset code
  1868. *
  1869. * @param {object} session - the session object automatically added by the websocket
  1870. * @param {string} code - the password reset code
  1871. * @param {string} newPassword - the new password reset code
  1872. * @param {Function} cb - gets called with the result
  1873. */
  1874. async changePasswordWithResetCode(session, code, newPassword, cb) {
  1875. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1876. async.waterfall(
  1877. [
  1878. next => {
  1879. if (!code || typeof code !== "string") return next("Invalid code.");
  1880. return userModel.findOne({ "services.password.reset.code": code }, next);
  1881. },
  1882. (user, next) => {
  1883. if (!user) return next("Invalid code.");
  1884. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  1885. return next();
  1886. },
  1887. next => {
  1888. if (!DBModule.passwordValid(newPassword))
  1889. return next("Invalid password. Check if it meets all the requirements.");
  1890. return next();
  1891. },
  1892. next => {
  1893. bcrypt.genSalt(10, next);
  1894. },
  1895. // hash the password
  1896. (salt, next) => {
  1897. bcrypt.hash(sha256(newPassword), salt, next);
  1898. },
  1899. (hashedPassword, next) => {
  1900. userModel.updateOne(
  1901. { "services.password.reset.code": code },
  1902. {
  1903. $set: {
  1904. "services.password.password": hashedPassword
  1905. },
  1906. $unset: { "services.password.reset": "" }
  1907. },
  1908. { runValidators: true },
  1909. next
  1910. );
  1911. }
  1912. ],
  1913. async err => {
  1914. if (err && err !== true) {
  1915. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1916. this.log(
  1917. "ERROR",
  1918. "CHANGE_PASSWORD_WITH_RESET_CODE",
  1919. `Code '${code}' failed to change password. '${err}'`
  1920. );
  1921. return cb({ status: "failure", message: err });
  1922. }
  1923. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  1924. return cb({
  1925. status: "success",
  1926. message: "Successfully changed password."
  1927. });
  1928. }
  1929. );
  1930. },
  1931. /**
  1932. * Bans a user by userId
  1933. *
  1934. * @param {object} session - the session object automatically added by the websocket
  1935. * @param {string} value - the user id that is going to be banned
  1936. * @param {string} reason - the reason for the ban
  1937. * @param {string} expiresAt - the time the ban expires
  1938. * @param {Function} cb - gets called with the result
  1939. */
  1940. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  1941. async.waterfall(
  1942. [
  1943. next => {
  1944. if (!userId) return next("You must provide a userId to ban.");
  1945. if (!reason) return next("You must provide a reason for the ban.");
  1946. return next();
  1947. },
  1948. next => {
  1949. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  1950. const date = new Date();
  1951. switch (expiresAt) {
  1952. case "1h":
  1953. expiresAt = date.setHours(date.getHours() + 1);
  1954. break;
  1955. case "12h":
  1956. expiresAt = date.setHours(date.getHours() + 12);
  1957. break;
  1958. case "1d":
  1959. expiresAt = date.setDate(date.getDate() + 1);
  1960. break;
  1961. case "1w":
  1962. expiresAt = date.setDate(date.getDate() + 7);
  1963. break;
  1964. case "1m":
  1965. expiresAt = date.setMonth(date.getMonth() + 1);
  1966. break;
  1967. case "3m":
  1968. expiresAt = date.setMonth(date.getMonth() + 3);
  1969. break;
  1970. case "6m":
  1971. expiresAt = date.setMonth(date.getMonth() + 6);
  1972. break;
  1973. case "1y":
  1974. expiresAt = date.setFullYear(date.getFullYear() + 1);
  1975. break;
  1976. case "never":
  1977. expiresAt = new Date(3093527980800000);
  1978. break;
  1979. default:
  1980. return next("Invalid expire date.");
  1981. }
  1982. return next();
  1983. },
  1984. next => {
  1985. PunishmentsModule.runJob(
  1986. "ADD_PUNISHMENT",
  1987. {
  1988. type: "banUserId",
  1989. value: userId,
  1990. reason,
  1991. expiresAt,
  1992. punishedBy: "" // needs changed
  1993. },
  1994. this
  1995. )
  1996. .then(punishment => next(null, punishment))
  1997. .catch(next);
  1998. },
  1999. (punishment, next) => {
  2000. CacheModule.runJob("PUB", {
  2001. channel: "user.ban",
  2002. value: { userId, punishment }
  2003. });
  2004. next();
  2005. }
  2006. ],
  2007. async err => {
  2008. if (err && err !== true) {
  2009. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2010. this.log(
  2011. "ERROR",
  2012. "BAN_USER_BY_ID",
  2013. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2014. );
  2015. return cb({ status: "failure", message: err });
  2016. }
  2017. this.log(
  2018. "SUCCESS",
  2019. "BAN_USER_BY_ID",
  2020. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2021. );
  2022. return cb({
  2023. status: "success",
  2024. message: "Successfully banned user."
  2025. });
  2026. }
  2027. );
  2028. })
  2029. };