users.js 70 KB

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