users.js 67 KB

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