users.js 68 KB

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