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. name: "",
  471. 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. const $set = {};
  938. Object.keys(preferences).forEach(preference => {
  939. $set[`preferences.${preference}`] = preferences[preference];
  940. });
  941. return next(null, $set);
  942. },
  943. ($set, next) => {
  944. userModel.findByIdAndUpdate(session.userId, { $set }, { new: false, upsert: true }, next);
  945. }
  946. ],
  947. async (err, user) => {
  948. if (err) {
  949. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  950. this.log(
  951. "ERROR",
  952. "UPDATE_USER_PREFERENCES",
  953. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  954. preferences
  955. )}". "${err}"`
  956. );
  957. return cb({ status: "error", message: err });
  958. }
  959. CacheModule.runJob("PUB", {
  960. channel: "user.updatePreferences",
  961. value: {
  962. preferences,
  963. userId: session.userId
  964. }
  965. });
  966. if (preferences.nightmode !== undefined && preferences.nightmode !== user.preferences.nightmode)
  967. ActivitiesModule.runJob("ADD_ACTIVITY", {
  968. userId: session.userId,
  969. type: "user__toggle_nightmode",
  970. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  971. });
  972. if (
  973. preferences.autoSkipDisliked !== undefined &&
  974. preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked
  975. )
  976. ActivitiesModule.runJob("ADD_ACTIVITY", {
  977. userId: session.userId,
  978. type: "user__toggle_autoskip_disliked_songs",
  979. payload: {
  980. message: preferences.autoSkipDisliked
  981. ? "Enabled the autoskipping of disliked songs"
  982. : "Disabled the autoskipping of disliked songs"
  983. }
  984. });
  985. if (
  986. preferences.activityWatch !== undefined &&
  987. preferences.activityWatch !== user.preferences.activityWatch
  988. )
  989. ActivitiesModule.runJob("ADD_ACTIVITY", {
  990. userId: session.userId,
  991. type: "user__toggle_activity_watch",
  992. payload: {
  993. message: preferences.activityWatch
  994. ? "Enabled ActivityWatch integration"
  995. : "Disabled ActivityWatch integration"
  996. }
  997. });
  998. this.log(
  999. "SUCCESS",
  1000. "UPDATE_USER_PREFERENCES",
  1001. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  1002. );
  1003. return cb({
  1004. status: "success",
  1005. message: "Preferences successfully updated"
  1006. });
  1007. }
  1008. );
  1009. }),
  1010. /**
  1011. * Retrieves a user's preferences
  1012. *
  1013. * @param {object} session - the session object automatically added by the websocket
  1014. * @param {Function} cb - gets called with the result
  1015. */
  1016. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  1017. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1018. async.waterfall(
  1019. [
  1020. next => {
  1021. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  1022. }
  1023. ],
  1024. async (err, { preferences }) => {
  1025. if (err) {
  1026. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1027. this.log(
  1028. "ERROR",
  1029. "GET_USER_PREFERENCES",
  1030. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  1031. );
  1032. return cb({ status: "error", message: err });
  1033. }
  1034. this.log(
  1035. "SUCCESS",
  1036. "GET_USER_PREFERENCES",
  1037. `Successfully obtained preferences for user "${session.userId}".`
  1038. );
  1039. return cb({
  1040. status: "success",
  1041. message: "Preferences successfully retrieved",
  1042. data: { preferences }
  1043. });
  1044. }
  1045. );
  1046. }),
  1047. /**
  1048. * Gets user object from username (only a few properties)
  1049. *
  1050. * @param {object} session - the session object automatically added by the websocket
  1051. * @param {string} username - the username of the user we are trying to find
  1052. * @param {Function} cb - gets called with the result
  1053. */
  1054. findByUsername: async function findByUsername(session, username, cb) {
  1055. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1056. async.waterfall(
  1057. [
  1058. next => {
  1059. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  1060. },
  1061. (account, next) => {
  1062. if (!account) return next("User not found.");
  1063. return next(null, account);
  1064. }
  1065. ],
  1066. async (err, account) => {
  1067. if (err && err !== true) {
  1068. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1069. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  1070. return cb({ status: "error", message: err });
  1071. }
  1072. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  1073. return cb({
  1074. status: "success",
  1075. data: {
  1076. _id: account._id,
  1077. name: account.name,
  1078. username: account.username,
  1079. location: account.location,
  1080. bio: account.bio,
  1081. role: account.role,
  1082. avatar: account.avatar,
  1083. createdAt: account.createdAt
  1084. }
  1085. });
  1086. }
  1087. );
  1088. },
  1089. /**
  1090. * Gets a username from an userId
  1091. *
  1092. * @param {object} session - the session object automatically added by the websocket
  1093. * @param {string} userId - the userId of the person we are trying to get the username from
  1094. * @param {Function} cb - gets called with the result
  1095. */
  1096. async getUsernameFromId(session, userId, cb) {
  1097. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1098. userModel
  1099. .findById(userId)
  1100. .then(user => {
  1101. if (user) {
  1102. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  1103. return cb({
  1104. status: "success",
  1105. data: { username: user.username }
  1106. });
  1107. }
  1108. this.log(
  1109. "ERROR",
  1110. "GET_USERNAME_FROM_ID",
  1111. `Getting the username from userId "${userId}" failed. User not found.`
  1112. );
  1113. return cb({
  1114. status: "error",
  1115. message: "Couldn't find the user."
  1116. });
  1117. })
  1118. .catch(async err => {
  1119. if (err && err !== true) {
  1120. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1121. this.log(
  1122. "ERROR",
  1123. "GET_USERNAME_FROM_ID",
  1124. `Getting the username from userId "${userId}" failed. "${err}"`
  1125. );
  1126. cb({ status: "error", message: err });
  1127. }
  1128. });
  1129. },
  1130. /**
  1131. * Gets a user from a userId
  1132. *
  1133. * @param {object} session - the session object automatically added by the websocket
  1134. * @param {string} userId - the userId of the person we are trying to get the username from
  1135. * @param {Function} cb - gets called with the result
  1136. */
  1137. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  1138. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1139. userModel
  1140. .findById(userId)
  1141. .then(user => {
  1142. if (user) {
  1143. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  1144. return cb({
  1145. status: "success",
  1146. data: {
  1147. _id: user._id,
  1148. username: user.username,
  1149. role: user.role,
  1150. liked: user.liked,
  1151. disliked: user.disliked,
  1152. songsRequested: user.statistics.songsRequested,
  1153. email: {
  1154. address: user.email.address,
  1155. verified: user.email.verified
  1156. },
  1157. hasPassword: !!user.services.password,
  1158. services: { github: user.services.github }
  1159. }
  1160. });
  1161. }
  1162. this.log(
  1163. "ERROR",
  1164. "GET_USER_FROM_ID",
  1165. `Getting the user from userId "${userId}" failed. User not found.`
  1166. );
  1167. return cb({
  1168. status: "error",
  1169. message: "Couldn't find the user."
  1170. });
  1171. })
  1172. .catch(async err => {
  1173. if (err && err !== true) {
  1174. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1175. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  1176. cb({ status: "error", message: err });
  1177. }
  1178. });
  1179. }),
  1180. /**
  1181. * Gets user info from session
  1182. *
  1183. * @param {object} session - the session object automatically added by the websocket
  1184. * @param {Function} cb - gets called with the result
  1185. */
  1186. findBySession: isLoginRequired(async function findBySession(session, cb) {
  1187. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1188. async.waterfall(
  1189. [
  1190. next => {
  1191. CacheModule.runJob(
  1192. "HGET",
  1193. {
  1194. table: "sessions",
  1195. key: session.sessionId
  1196. },
  1197. this
  1198. )
  1199. .then(session => next(null, session))
  1200. .catch(next);
  1201. },
  1202. (session, next) => {
  1203. if (!session) return next("Session not found.");
  1204. return next(null, session);
  1205. },
  1206. (session, next) => {
  1207. userModel.findOne({ _id: session.userId }, next);
  1208. },
  1209. (user, next) => {
  1210. if (!user) return next("User not found.");
  1211. return next(null, user);
  1212. }
  1213. ],
  1214. async (err, user) => {
  1215. if (err && err !== true) {
  1216. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1217. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  1218. return cb({ status: "error", message: err });
  1219. }
  1220. const sanitisedUser = {
  1221. email: {
  1222. address: user.email.address
  1223. },
  1224. avatar: user.avatar,
  1225. username: user.username,
  1226. name: user.name,
  1227. location: user.location,
  1228. bio: user.bio
  1229. };
  1230. if (user.services.password && user.services.password.password) sanitisedUser.password = true;
  1231. if (user.services.github && user.services.github.id) sanitisedUser.github = true;
  1232. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  1233. return cb({
  1234. status: "success",
  1235. data: { user: sanitisedUser }
  1236. });
  1237. }
  1238. );
  1239. }),
  1240. /**
  1241. * Updates a user's username
  1242. *
  1243. * @param {object} session - the session object automatically added by the websocket
  1244. * @param {string} updatingUserId - the updating user's id
  1245. * @param {string} newUsername - the new username
  1246. * @param {Function} cb - gets called with the result
  1247. */
  1248. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  1249. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1250. async.waterfall(
  1251. [
  1252. next => {
  1253. if (updatingUserId === session.userId) return next(null, true);
  1254. return userModel.findOne({ _id: session.userId }, next);
  1255. },
  1256. (user, next) => {
  1257. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1258. return userModel.findOne({ _id: updatingUserId }, next);
  1259. },
  1260. (user, next) => {
  1261. if (!user) return next("User not found.");
  1262. if (user.username === newUsername)
  1263. return next("New username can't be the same as the old username.");
  1264. return next(null);
  1265. },
  1266. next => {
  1267. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1268. },
  1269. (user, next) => {
  1270. if (!user) return next();
  1271. if (user._id === updatingUserId) return next();
  1272. return next("That username is already in use.");
  1273. },
  1274. next => {
  1275. userModel.updateOne(
  1276. { _id: updatingUserId },
  1277. { $set: { username: newUsername } },
  1278. { runValidators: true },
  1279. next
  1280. );
  1281. }
  1282. ],
  1283. async err => {
  1284. if (err && err !== true) {
  1285. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1286. this.log(
  1287. "ERROR",
  1288. "UPDATE_USERNAME",
  1289. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1290. );
  1291. return cb({ status: "error", message: err });
  1292. }
  1293. CacheModule.runJob("PUB", {
  1294. channel: "user.updateUsername",
  1295. value: {
  1296. username: newUsername,
  1297. _id: updatingUserId
  1298. }
  1299. });
  1300. this.log(
  1301. "SUCCESS",
  1302. "UPDATE_USERNAME",
  1303. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1304. );
  1305. return cb({
  1306. status: "success",
  1307. message: "Username updated successfully"
  1308. });
  1309. }
  1310. );
  1311. }),
  1312. /**
  1313. * Updates a user's email
  1314. *
  1315. * @param {object} session - the session object automatically added by the websocket
  1316. * @param {string} updatingUserId - the updating user's id
  1317. * @param {string} newEmail - the new email
  1318. * @param {Function} cb - gets called with the result
  1319. */
  1320. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1321. newEmail = newEmail.toLowerCase();
  1322. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1323. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1324. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1325. async.waterfall(
  1326. [
  1327. next => {
  1328. if (updatingUserId === session.userId) return next(null, true);
  1329. return userModel.findOne({ _id: session.userId }, next);
  1330. },
  1331. (user, next) => {
  1332. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1333. return userModel.findOne({ _id: updatingUserId }, next);
  1334. },
  1335. (user, next) => {
  1336. if (!user) return next("User not found.");
  1337. if (user.email.address === newEmail)
  1338. return next("New email can't be the same as your the old email.");
  1339. return next();
  1340. },
  1341. next => {
  1342. userModel.findOne({ "email.address": newEmail }, next);
  1343. },
  1344. (user, next) => {
  1345. if (!user) return next();
  1346. if (user._id === updatingUserId) return next();
  1347. return next("That email is already in use.");
  1348. },
  1349. // regenerate the url for gravatar avatar
  1350. next => {
  1351. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1352. next(null, url);
  1353. });
  1354. },
  1355. (newAvatarUrl, next) => {
  1356. userModel.updateOne(
  1357. { _id: updatingUserId },
  1358. {
  1359. $set: {
  1360. "avatar.url": newAvatarUrl,
  1361. "email.address": newEmail,
  1362. "email.verified": false,
  1363. "email.verificationToken": verificationToken
  1364. }
  1365. },
  1366. { runValidators: true },
  1367. next
  1368. );
  1369. },
  1370. (res, next) => {
  1371. userModel.findOne({ _id: updatingUserId }, next);
  1372. },
  1373. (user, next) => {
  1374. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1375. next(err);
  1376. });
  1377. }
  1378. ],
  1379. async err => {
  1380. if (err && err !== true) {
  1381. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1382. this.log(
  1383. "ERROR",
  1384. "UPDATE_EMAIL",
  1385. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1386. );
  1387. return cb({ status: "error", message: err });
  1388. }
  1389. this.log(
  1390. "SUCCESS",
  1391. "UPDATE_EMAIL",
  1392. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1393. );
  1394. return cb({
  1395. status: "success",
  1396. message: "Email updated successfully."
  1397. });
  1398. }
  1399. );
  1400. }),
  1401. /**
  1402. * Updates a user's name
  1403. *
  1404. * @param {object} session - the session object automatically added by the websocket
  1405. * @param {string} updatingUserId - the updating user's id
  1406. * @param {string} newBio - the new name
  1407. * @param {Function} cb - gets called with the result
  1408. */
  1409. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1410. const userModel = await DBModule.runJob(
  1411. "GET_MODEL",
  1412. {
  1413. modelName: "user"
  1414. },
  1415. this
  1416. );
  1417. async.waterfall(
  1418. [
  1419. next => {
  1420. if (updatingUserId === session.userId) return next(null, true);
  1421. return userModel.findOne({ _id: session.userId }, next);
  1422. },
  1423. (user, next) => {
  1424. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1425. return userModel.findOne({ _id: updatingUserId }, next);
  1426. },
  1427. (user, next) => {
  1428. if (!user) return next("User not found.");
  1429. return userModel.updateOne(
  1430. { _id: updatingUserId },
  1431. { $set: { name: newName } },
  1432. { runValidators: true },
  1433. next
  1434. );
  1435. }
  1436. ],
  1437. async err => {
  1438. if (err && err !== true) {
  1439. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1440. this.log(
  1441. "ERROR",
  1442. "UPDATE_NAME",
  1443. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1444. );
  1445. return cb({ status: "error", message: err });
  1446. }
  1447. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1448. userId: updatingUserId,
  1449. type: "user__edit_name",
  1450. payload: { message: `Changed name to ${newName}` }
  1451. });
  1452. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1453. return cb({
  1454. status: "success",
  1455. message: "Name updated successfully"
  1456. });
  1457. }
  1458. );
  1459. }),
  1460. /**
  1461. * Updates a user's location
  1462. *
  1463. * @param {object} session - the session object automatically added by the websocket
  1464. * @param {string} updatingUserId - the updating user's id
  1465. * @param {string} newLocation - the new location
  1466. * @param {Function} cb - gets called with the result
  1467. */
  1468. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1469. const userModel = await DBModule.runJob(
  1470. "GET_MODEL",
  1471. {
  1472. modelName: "user"
  1473. },
  1474. this
  1475. );
  1476. async.waterfall(
  1477. [
  1478. next => {
  1479. if (updatingUserId === session.userId) return next(null, true);
  1480. return userModel.findOne({ _id: session.userId }, next);
  1481. },
  1482. (user, next) => {
  1483. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1484. return userModel.findOne({ _id: updatingUserId }, next);
  1485. },
  1486. (user, next) => {
  1487. if (!user) return next("User not found.");
  1488. return userModel.updateOne(
  1489. { _id: updatingUserId },
  1490. { $set: { location: newLocation } },
  1491. { runValidators: true },
  1492. next
  1493. );
  1494. }
  1495. ],
  1496. async err => {
  1497. if (err && err !== true) {
  1498. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1499. this.log(
  1500. "ERROR",
  1501. "UPDATE_LOCATION",
  1502. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1503. );
  1504. return cb({ status: "error", message: err });
  1505. }
  1506. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1507. userId: updatingUserId,
  1508. type: "user__edit_location",
  1509. payload: { message: `Changed location to ${newLocation}` }
  1510. });
  1511. this.log(
  1512. "SUCCESS",
  1513. "UPDATE_LOCATION",
  1514. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1515. );
  1516. return cb({
  1517. status: "success",
  1518. message: "Location updated successfully"
  1519. });
  1520. }
  1521. );
  1522. }),
  1523. /**
  1524. * Updates a user's bio
  1525. *
  1526. * @param {object} session - the session object automatically added by the websocket
  1527. * @param {string} updatingUserId - the updating user's id
  1528. * @param {string} newBio - the new bio
  1529. * @param {Function} cb - gets called with the result
  1530. */
  1531. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1532. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1533. async.waterfall(
  1534. [
  1535. next => {
  1536. if (updatingUserId === session.userId) return next(null, true);
  1537. return userModel.findOne({ _id: session.userId }, next);
  1538. },
  1539. (user, next) => {
  1540. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1541. return userModel.findOne({ _id: updatingUserId }, next);
  1542. },
  1543. (user, next) => {
  1544. if (!user) return next("User not found.");
  1545. return userModel.updateOne(
  1546. { _id: updatingUserId },
  1547. { $set: { bio: newBio } },
  1548. { runValidators: true },
  1549. next
  1550. );
  1551. }
  1552. ],
  1553. async err => {
  1554. if (err && err !== true) {
  1555. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1556. this.log(
  1557. "ERROR",
  1558. "UPDATE_BIO",
  1559. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1560. );
  1561. return cb({ status: "error", message: err });
  1562. }
  1563. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1564. userId: updatingUserId,
  1565. type: "user__edit_bio",
  1566. payload: { message: `Changed bio to ${newBio}` }
  1567. });
  1568. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1569. return cb({
  1570. status: "success",
  1571. message: "Bio updated successfully"
  1572. });
  1573. }
  1574. );
  1575. }),
  1576. /**
  1577. * Updates a user's avatar
  1578. *
  1579. * @param {object} session - the session object automatically added by the websocket
  1580. * @param {string} updatingUserId - the updating user's id
  1581. * @param {string} newAvatar - the new avatar object
  1582. * @param {Function} cb - gets called with the result
  1583. */
  1584. updateAvatar: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1585. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1586. async.waterfall(
  1587. [
  1588. next => {
  1589. if (updatingUserId === session.userId) return next(null, true);
  1590. return userModel.findOne({ _id: session.userId }, next);
  1591. },
  1592. (user, next) => {
  1593. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1594. return userModel.findOne({ _id: updatingUserId }, next);
  1595. },
  1596. (user, next) => {
  1597. if (!user) return next("User not found.");
  1598. return userModel.findOneAndUpdate(
  1599. { _id: updatingUserId },
  1600. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1601. { new: true, runValidators: true },
  1602. next
  1603. );
  1604. }
  1605. ],
  1606. async err => {
  1607. if (err && err !== true) {
  1608. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1609. this.log(
  1610. "ERROR",
  1611. "UPDATE_AVATAR",
  1612. `Couldn't update avatar for user "${updatingUserId}" to type "${newAvatar.type}" and color "${newAvatar.color}". "${err}"`
  1613. );
  1614. return cb({ status: "error", message: err });
  1615. }
  1616. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1617. userId: updatingUserId,
  1618. type: "user__edit_avatar",
  1619. payload: { message: `Changed avatar to use ${newAvatar.type} and ${newAvatar.color}` }
  1620. });
  1621. this.log(
  1622. "SUCCESS",
  1623. "UPDATE_AVATAR",
  1624. `Updated avatar for user "${updatingUserId}" to type "${newAvatar.type} and color ${newAvatar.color}".`
  1625. );
  1626. return cb({
  1627. status: "success",
  1628. message: "Avatar updated successfully"
  1629. });
  1630. }
  1631. );
  1632. }),
  1633. /**
  1634. * Updates a user's role
  1635. *
  1636. * @param {object} session - the session object automatically added by the websocket
  1637. * @param {string} updatingUserId - the updating user's id
  1638. * @param {string} newRole - the new role
  1639. * @param {Function} cb - gets called with the result
  1640. */
  1641. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1642. newRole = newRole.toLowerCase();
  1643. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1644. async.waterfall(
  1645. [
  1646. next => {
  1647. userModel.findOne({ _id: updatingUserId }, next);
  1648. },
  1649. (user, next) => {
  1650. if (!user) return next("User not found.");
  1651. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1652. return next();
  1653. },
  1654. next => {
  1655. userModel.updateOne(
  1656. { _id: updatingUserId },
  1657. { $set: { role: newRole } },
  1658. { runValidators: true },
  1659. next
  1660. );
  1661. }
  1662. ],
  1663. async err => {
  1664. if (err && err !== true) {
  1665. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1666. this.log(
  1667. "ERROR",
  1668. "UPDATE_ROLE",
  1669. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1670. );
  1671. return cb({ status: "error", message: err });
  1672. }
  1673. this.log(
  1674. "SUCCESS",
  1675. "UPDATE_ROLE",
  1676. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1677. );
  1678. return cb({
  1679. status: "success",
  1680. message: "Role successfully updated."
  1681. });
  1682. }
  1683. );
  1684. }),
  1685. /**
  1686. * Updates a user's password
  1687. *
  1688. * @param {object} session - the session object automatically added by the websocket
  1689. * @param {string} previousPassword - the previous password
  1690. * @param {string} newPassword - the new password
  1691. * @param {Function} cb - gets called with the result
  1692. */
  1693. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1694. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1695. async.waterfall(
  1696. [
  1697. next => {
  1698. userModel.findOne({ _id: session.userId }, next);
  1699. },
  1700. (user, next) => {
  1701. if (!user.services.password) return next("This account does not have a password set.");
  1702. return next(null, user.services.password.password);
  1703. },
  1704. (storedPassword, next) => {
  1705. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1706. if (res) return next();
  1707. return next("Please enter the correct previous password.");
  1708. });
  1709. },
  1710. next => {
  1711. if (!DBModule.passwordValid(newPassword))
  1712. return next("Invalid new password. Check if it meets all the requirements.");
  1713. return next();
  1714. },
  1715. next => {
  1716. bcrypt.genSalt(10, next);
  1717. },
  1718. // hash the password
  1719. (salt, next) => {
  1720. bcrypt.hash(sha256(newPassword), salt, next);
  1721. },
  1722. (hashedPassword, next) => {
  1723. userModel.updateOne(
  1724. { _id: session.userId },
  1725. {
  1726. $set: {
  1727. "services.password.password": hashedPassword
  1728. }
  1729. },
  1730. next
  1731. );
  1732. }
  1733. ],
  1734. async err => {
  1735. if (err) {
  1736. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1737. this.log(
  1738. "ERROR",
  1739. "UPDATE_PASSWORD",
  1740. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1741. );
  1742. return cb({ status: "error", message: err });
  1743. }
  1744. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1745. return cb({
  1746. status: "success",
  1747. message: "Password successfully updated."
  1748. });
  1749. }
  1750. );
  1751. }),
  1752. /**
  1753. * Requests a password for a session
  1754. *
  1755. * @param {object} session - the session object automatically added by the websocket
  1756. * @param {string} email - the email of the user that requests a password reset
  1757. * @param {Function} cb - gets called with the result
  1758. */
  1759. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1760. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1761. const passwordRequestSchema = await MailModule.runJob(
  1762. "GET_SCHEMA",
  1763. {
  1764. schemaName: "passwordRequest"
  1765. },
  1766. this
  1767. );
  1768. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1769. async.waterfall(
  1770. [
  1771. next => {
  1772. userModel.findOne({ _id: session.userId }, next);
  1773. },
  1774. (user, next) => {
  1775. if (!user) return next("User not found.");
  1776. if (user.services.password && user.services.password.password)
  1777. return next("You already have a password set.");
  1778. return next(null, user);
  1779. },
  1780. (user, next) => {
  1781. const expires = new Date();
  1782. expires.setDate(expires.getDate() + 1);
  1783. userModel.findOneAndUpdate(
  1784. { "email.address": user.email.address },
  1785. {
  1786. $set: {
  1787. "services.password": {
  1788. set: { code, expires }
  1789. }
  1790. }
  1791. },
  1792. { runValidators: true },
  1793. next
  1794. );
  1795. },
  1796. (user, next) => {
  1797. passwordRequestSchema(user.email.address, user.username, code, next);
  1798. }
  1799. ],
  1800. async err => {
  1801. if (err && err !== true) {
  1802. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1803. this.log(
  1804. "ERROR",
  1805. "REQUEST_PASSWORD",
  1806. `UserId '${session.userId}' failed to request password. '${err}'`
  1807. );
  1808. return cb({ status: "error", message: err });
  1809. }
  1810. this.log(
  1811. "SUCCESS",
  1812. "REQUEST_PASSWORD",
  1813. `UserId '${session.userId}' successfully requested a password.`
  1814. );
  1815. return cb({
  1816. status: "success",
  1817. message: "Successfully requested password."
  1818. });
  1819. }
  1820. );
  1821. }),
  1822. /**
  1823. * Verifies a password code
  1824. *
  1825. * @param {object} session - the session object automatically added by the websocket
  1826. * @param {string} code - the password code
  1827. * @param {Function} cb - gets called with the result
  1828. */
  1829. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1830. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1831. async.waterfall(
  1832. [
  1833. next => {
  1834. if (!code || typeof code !== "string") return next("Invalid code.");
  1835. return userModel.findOne(
  1836. {
  1837. "services.password.set.code": code,
  1838. _id: session.userId
  1839. },
  1840. next
  1841. );
  1842. },
  1843. (user, next) => {
  1844. if (!user) return next("Invalid code.");
  1845. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1846. return next(null);
  1847. }
  1848. ],
  1849. async err => {
  1850. if (err && err !== true) {
  1851. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1852. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1853. cb({ status: "error", message: err });
  1854. } else {
  1855. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1856. cb({
  1857. status: "success",
  1858. message: "Successfully verified password code."
  1859. });
  1860. }
  1861. }
  1862. );
  1863. }),
  1864. /**
  1865. * Adds a password to a user with a code
  1866. *
  1867. * @param {object} session - the session object automatically added by the websocket
  1868. * @param {string} code - the password code
  1869. * @param {string} newPassword - the new password code
  1870. * @param {Function} cb - gets called with the result
  1871. */
  1872. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1873. const userModel = await DBModule.runJob(
  1874. "GET_MODEL",
  1875. {
  1876. modelName: "user"
  1877. },
  1878. this
  1879. );
  1880. async.waterfall(
  1881. [
  1882. next => {
  1883. if (!code || typeof code !== "string") return next("Invalid code.");
  1884. return userModel.findOne({ "services.password.set.code": code }, next);
  1885. },
  1886. (user, next) => {
  1887. if (!user) return next("Invalid code.");
  1888. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1889. return next();
  1890. },
  1891. next => {
  1892. if (!DBModule.passwordValid(newPassword))
  1893. return next("Invalid password. Check if it meets all the requirements.");
  1894. return next();
  1895. },
  1896. next => {
  1897. bcrypt.genSalt(10, next);
  1898. },
  1899. // hash the password
  1900. (salt, next) => {
  1901. bcrypt.hash(sha256(newPassword), salt, next);
  1902. },
  1903. (hashedPassword, next) => {
  1904. userModel.updateOne(
  1905. { "services.password.set.code": code },
  1906. {
  1907. $set: {
  1908. "services.password.password": hashedPassword
  1909. },
  1910. $unset: { "services.password.set": "" }
  1911. },
  1912. { runValidators: true },
  1913. next
  1914. );
  1915. }
  1916. ],
  1917. async err => {
  1918. if (err && err !== true) {
  1919. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1920. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1921. return cb({ status: "error", message: err });
  1922. }
  1923. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1924. CacheModule.runJob("PUB", {
  1925. channel: "user.linkPassword",
  1926. value: session.userId
  1927. });
  1928. return cb({
  1929. status: "success",
  1930. message: "Successfully added password."
  1931. });
  1932. }
  1933. );
  1934. }),
  1935. /**
  1936. * Unlinks password from user
  1937. *
  1938. * @param {object} session - the session object automatically added by the websocket
  1939. * @param {Function} cb - gets called with the result
  1940. */
  1941. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1942. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1943. async.waterfall(
  1944. [
  1945. next => {
  1946. userModel.findOne({ _id: session.userId }, next);
  1947. },
  1948. (user, next) => {
  1949. if (!user) return next("Not logged in.");
  1950. if (!user.services.github || !user.services.github.id)
  1951. return next("You can't remove password login without having GitHub login.");
  1952. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1953. }
  1954. ],
  1955. async err => {
  1956. if (err && err !== true) {
  1957. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1958. this.log(
  1959. "ERROR",
  1960. "UNLINK_PASSWORD",
  1961. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1962. );
  1963. return cb({ status: "error", message: err });
  1964. }
  1965. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  1966. CacheModule.runJob("PUB", {
  1967. channel: "user.unlinkPassword",
  1968. value: session.userId
  1969. });
  1970. return cb({
  1971. status: "success",
  1972. message: "Successfully unlinked password."
  1973. });
  1974. }
  1975. );
  1976. }),
  1977. /**
  1978. * Unlinks GitHub from user
  1979. *
  1980. * @param {object} session - the session object automatically added by the websocket
  1981. * @param {Function} cb - gets called with the result
  1982. */
  1983. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1984. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1985. async.waterfall(
  1986. [
  1987. next => {
  1988. userModel.findOne({ _id: session.userId }, next);
  1989. },
  1990. (user, next) => {
  1991. if (!user) return next("Not logged in.");
  1992. if (!user.services.password || !user.services.password.password)
  1993. return next("You can't remove GitHub login without having password login.");
  1994. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1995. }
  1996. ],
  1997. async err => {
  1998. if (err && err !== true) {
  1999. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2000. this.log(
  2001. "ERROR",
  2002. "UNLINK_GITHUB",
  2003. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  2004. );
  2005. return cb({ status: "error", message: err });
  2006. }
  2007. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  2008. CacheModule.runJob("PUB", {
  2009. channel: "user.unlinkGithub",
  2010. value: session.userId
  2011. });
  2012. return cb({
  2013. status: "success",
  2014. message: "Successfully unlinked GitHub."
  2015. });
  2016. }
  2017. );
  2018. }),
  2019. /**
  2020. * Requests a password reset for an email
  2021. *
  2022. * @param {object} session - the session object automatically added by the websocket
  2023. * @param {string} email - the email of the user that requests a password reset
  2024. * @param {Function} cb - gets called with the result
  2025. */
  2026. async requestPasswordReset(session, email, cb) {
  2027. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  2028. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2029. const resetPasswordRequestSchema = await MailModule.runJob(
  2030. "GET_SCHEMA",
  2031. { schemaName: "resetPasswordRequest" },
  2032. this
  2033. );
  2034. async.waterfall(
  2035. [
  2036. next => {
  2037. if (!email || typeof email !== "string") return next("Invalid email.");
  2038. email = email.toLowerCase();
  2039. return userModel.findOne({ "email.address": email }, next);
  2040. },
  2041. (user, next) => {
  2042. if (!user) return next("User not found.");
  2043. if (!user.services.password || !user.services.password.password)
  2044. return next("User does not have a password set, and probably uses GitHub to log in.");
  2045. return next(null, user);
  2046. },
  2047. (user, next) => {
  2048. const expires = new Date();
  2049. expires.setDate(expires.getDate() + 1);
  2050. userModel.findOneAndUpdate(
  2051. { "email.address": email },
  2052. {
  2053. $set: {
  2054. "services.password.reset": {
  2055. code,
  2056. expires
  2057. }
  2058. }
  2059. },
  2060. { runValidators: true },
  2061. next
  2062. );
  2063. },
  2064. (user, next) => {
  2065. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  2066. }
  2067. ],
  2068. async err => {
  2069. if (err && err !== true) {
  2070. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2071. this.log(
  2072. "ERROR",
  2073. "REQUEST_PASSWORD_RESET",
  2074. `Email '${email}' failed to request password reset. '${err}'`
  2075. );
  2076. return cb({ status: "error", message: err });
  2077. }
  2078. this.log(
  2079. "SUCCESS",
  2080. "REQUEST_PASSWORD_RESET",
  2081. `Email '${email}' successfully requested a password reset.`
  2082. );
  2083. return cb({
  2084. status: "success",
  2085. message: "Successfully requested password reset."
  2086. });
  2087. }
  2088. );
  2089. },
  2090. /**
  2091. * Verifies a reset code
  2092. *
  2093. * @param {object} session - the session object automatically added by the websocket
  2094. * @param {string} code - the password reset code
  2095. * @param {Function} cb - gets called with the result
  2096. */
  2097. async verifyPasswordResetCode(session, code, cb) {
  2098. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2099. async.waterfall(
  2100. [
  2101. next => {
  2102. if (!code || typeof code !== "string") return next("Invalid code.");
  2103. return userModel.findOne({ "services.password.reset.code": code }, next);
  2104. },
  2105. (user, next) => {
  2106. if (!user) return next("Invalid code.");
  2107. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2108. return next(null);
  2109. }
  2110. ],
  2111. async err => {
  2112. if (err && err !== true) {
  2113. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2114. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  2115. return cb({ status: "error", message: err });
  2116. }
  2117. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  2118. return cb({
  2119. status: "success",
  2120. message: "Successfully verified password reset code."
  2121. });
  2122. }
  2123. );
  2124. },
  2125. /**
  2126. * Changes a user's password with a reset code
  2127. *
  2128. * @param {object} session - the session object automatically added by the websocket
  2129. * @param {string} code - the password reset code
  2130. * @param {string} newPassword - the new password reset code
  2131. * @param {Function} cb - gets called with the result
  2132. */
  2133. async changePasswordWithResetCode(session, code, newPassword, cb) {
  2134. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2135. async.waterfall(
  2136. [
  2137. next => {
  2138. if (!code || typeof code !== "string") return next("Invalid code.");
  2139. return userModel.findOne({ "services.password.reset.code": code }, next);
  2140. },
  2141. (user, next) => {
  2142. if (!user) return next("Invalid code.");
  2143. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2144. return next();
  2145. },
  2146. next => {
  2147. if (!DBModule.passwordValid(newPassword))
  2148. return next("Invalid password. Check if it meets all the requirements.");
  2149. return next();
  2150. },
  2151. next => {
  2152. bcrypt.genSalt(10, next);
  2153. },
  2154. // hash the password
  2155. (salt, next) => {
  2156. bcrypt.hash(sha256(newPassword), salt, next);
  2157. },
  2158. (hashedPassword, next) => {
  2159. userModel.updateOne(
  2160. { "services.password.reset.code": code },
  2161. {
  2162. $set: {
  2163. "services.password.password": hashedPassword
  2164. },
  2165. $unset: { "services.password.reset": "" }
  2166. },
  2167. { runValidators: true },
  2168. next
  2169. );
  2170. }
  2171. ],
  2172. async err => {
  2173. if (err && err !== true) {
  2174. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2175. this.log(
  2176. "ERROR",
  2177. "CHANGE_PASSWORD_WITH_RESET_CODE",
  2178. `Code '${code}' failed to change password. '${err}'`
  2179. );
  2180. return cb({ status: "error", message: err });
  2181. }
  2182. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  2183. return cb({
  2184. status: "success",
  2185. message: "Successfully changed password."
  2186. });
  2187. }
  2188. );
  2189. },
  2190. /**
  2191. * Bans a user by userId
  2192. *
  2193. * @param {object} session - the session object automatically added by the websocket
  2194. * @param {string} value - the user id that is going to be banned
  2195. * @param {string} reason - the reason for the ban
  2196. * @param {string} expiresAt - the time the ban expires
  2197. * @param {Function} cb - gets called with the result
  2198. */
  2199. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  2200. async.waterfall(
  2201. [
  2202. next => {
  2203. if (!userId) return next("You must provide a userId to ban.");
  2204. if (!reason) return next("You must provide a reason for the ban.");
  2205. return next();
  2206. },
  2207. next => {
  2208. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  2209. const date = new Date();
  2210. switch (expiresAt) {
  2211. case "1h":
  2212. expiresAt = date.setHours(date.getHours() + 1);
  2213. break;
  2214. case "12h":
  2215. expiresAt = date.setHours(date.getHours() + 12);
  2216. break;
  2217. case "1d":
  2218. expiresAt = date.setDate(date.getDate() + 1);
  2219. break;
  2220. case "1w":
  2221. expiresAt = date.setDate(date.getDate() + 7);
  2222. break;
  2223. case "1m":
  2224. expiresAt = date.setMonth(date.getMonth() + 1);
  2225. break;
  2226. case "3m":
  2227. expiresAt = date.setMonth(date.getMonth() + 3);
  2228. break;
  2229. case "6m":
  2230. expiresAt = date.setMonth(date.getMonth() + 6);
  2231. break;
  2232. case "1y":
  2233. expiresAt = date.setFullYear(date.getFullYear() + 1);
  2234. break;
  2235. case "never":
  2236. expiresAt = new Date(3093527980800000);
  2237. break;
  2238. default:
  2239. return next("Invalid expire date.");
  2240. }
  2241. return next();
  2242. },
  2243. next => {
  2244. PunishmentsModule.runJob(
  2245. "ADD_PUNISHMENT",
  2246. {
  2247. type: "banUserId",
  2248. value: userId,
  2249. reason,
  2250. expiresAt,
  2251. punishedBy: session.userId
  2252. },
  2253. this
  2254. )
  2255. .then(punishment => next(null, punishment))
  2256. .catch(next);
  2257. },
  2258. (punishment, next) => {
  2259. CacheModule.runJob("PUB", {
  2260. channel: "user.ban",
  2261. value: { userId, punishment }
  2262. });
  2263. next();
  2264. }
  2265. ],
  2266. async err => {
  2267. if (err && err !== true) {
  2268. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2269. this.log(
  2270. "ERROR",
  2271. "BAN_USER_BY_ID",
  2272. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2273. );
  2274. return cb({ status: "error", message: err });
  2275. }
  2276. this.log(
  2277. "SUCCESS",
  2278. "BAN_USER_BY_ID",
  2279. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2280. );
  2281. return cb({
  2282. status: "success",
  2283. message: "Successfully banned user."
  2284. });
  2285. }
  2286. );
  2287. })
  2288. };