users.js 70 KB

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