users.js 67 KB

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