users.js 70 KB

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