users.js 70 KB

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