users.js 69 KB

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