users.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  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. return cb({
  653. status: "success",
  654. data: { linked },
  655. message: "Successfully checked if GitHub accounty was linked."
  656. });
  657. }
  658. );
  659. }),
  660. /**
  661. * Removes all sessions for a user
  662. *
  663. * @param {object} session - the session object automatically added by the websocket
  664. * @param {string} userId - the id of the user we are trying to delete the sessions of
  665. * @param {Function} cb - gets called with the result
  666. */
  667. removeSessions: isLoginRequired(async function removeSessions(session, userId, cb) {
  668. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  669. async.waterfall(
  670. [
  671. next => {
  672. userModel.findOne({ _id: session.userId }, (err, user) => {
  673. if (err) return next(err);
  674. if (user.role !== "admin" && session.userId !== userId)
  675. return next("Only admins and the owner of the account can remove their sessions.");
  676. return next();
  677. });
  678. },
  679. next => {
  680. CacheModule.runJob("HGETALL", { table: "sessions" }, this)
  681. .then(sessions => {
  682. next(null, sessions);
  683. })
  684. .catch(next);
  685. },
  686. (sessions, next) => {
  687. if (!sessions) return next("There are no sessions for this user to remove.");
  688. const keys = Object.keys(sessions);
  689. return next(null, keys, sessions);
  690. },
  691. (keys, sessions, next) => {
  692. CacheModule.runJob("PUB", {
  693. channel: "user.removeSessions",
  694. value: userId
  695. });
  696. // temp fix, need to wait properly for the SUB/PUB refactor (on wekan)
  697. setTimeout(
  698. () =>
  699. async.each(
  700. keys,
  701. (sessionId, callback) => {
  702. const session = sessions[sessionId];
  703. if (session.userId === userId) {
  704. // TODO Also maybe add this to this runJob
  705. CacheModule.runJob("HDEL", {
  706. table: "sessions",
  707. key: sessionId
  708. })
  709. .then(() => callback(null))
  710. .catch(callback);
  711. }
  712. },
  713. err => {
  714. next(err);
  715. }
  716. ),
  717. 50
  718. );
  719. }
  720. ],
  721. async err => {
  722. if (err) {
  723. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  724. this.log(
  725. "ERROR",
  726. "REMOVE_SESSIONS_FOR_USER",
  727. `Couldn't remove all sessions for user "${userId}". "${err}"`
  728. );
  729. return cb({ status: "error", message: err });
  730. }
  731. this.log("SUCCESS", "REMOVE_SESSIONS_FOR_USER", `Removed all sessions for user "${userId}".`);
  732. return cb({
  733. status: "success",
  734. message: "Successfully removed all sessions."
  735. });
  736. }
  737. );
  738. }),
  739. /**
  740. * Updates the order of a user's favorite stations
  741. *
  742. * @param {object} session - the session object automatically added by the websocket
  743. * @param {Array} favoriteStations - array of station ids (with a specific order)
  744. * @param {Function} cb - gets called with the result
  745. */
  746. updateOrderOfFavoriteStations: isLoginRequired(async function updateOrderOfFavoriteStations(
  747. session,
  748. favoriteStations,
  749. cb
  750. ) {
  751. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  752. async.waterfall(
  753. [
  754. next => {
  755. userModel.updateOne(
  756. { _id: session.userId },
  757. { $set: { favoriteStations } },
  758. { runValidators: true },
  759. next
  760. );
  761. }
  762. ],
  763. async err => {
  764. if (err) {
  765. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  766. this.log(
  767. "ERROR",
  768. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  769. `Couldn't update order of favorite stations for user "${session.userId}" to "${favoriteStations}". "${err}"`
  770. );
  771. return cb({ status: "error", message: err });
  772. }
  773. CacheModule.runJob("PUB", {
  774. channel: "user.updateOrderOfFavoriteStations",
  775. value: {
  776. favoriteStations,
  777. userId: session.userId
  778. }
  779. });
  780. this.log(
  781. "SUCCESS",
  782. "UPDATE_ORDER_OF_USER_FAVORITE_STATIONS",
  783. `Updated order of favorite stations for user "${session.userId}" to "${favoriteStations}".`
  784. );
  785. return cb({
  786. status: "success",
  787. message: "Order of favorite stations successfully updated"
  788. });
  789. }
  790. );
  791. }),
  792. /**
  793. * Updates the order of a user's playlists
  794. *
  795. * @param {object} session - the session object automatically added by the websocket
  796. * @param {Array} orderOfPlaylists - array of playlist ids (with a specific order)
  797. * @param {Function} cb - gets called with the result
  798. */
  799. updateOrderOfPlaylists: isLoginRequired(async function updateOrderOfPlaylists(session, orderOfPlaylists, cb) {
  800. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  801. async.waterfall(
  802. [
  803. next => {
  804. userModel.updateOne(
  805. { _id: session.userId },
  806. { $set: { "preferences.orderOfPlaylists": orderOfPlaylists } },
  807. { runValidators: true },
  808. next
  809. );
  810. }
  811. ],
  812. async err => {
  813. if (err) {
  814. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  815. this.log(
  816. "ERROR",
  817. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  818. `Couldn't update order of playlists for user "${session.userId}" to "${orderOfPlaylists}". "${err}"`
  819. );
  820. return cb({ status: "error", message: err });
  821. }
  822. CacheModule.runJob("PUB", {
  823. channel: "user.updateOrderOfPlaylists",
  824. value: {
  825. orderOfPlaylists,
  826. userId: session.userId
  827. }
  828. });
  829. this.log(
  830. "SUCCESS",
  831. "UPDATE_ORDER_OF_USER_PLAYLISTS",
  832. `Updated order of playlists for user "${session.userId}" to "${orderOfPlaylists}".`
  833. );
  834. return cb({
  835. status: "success",
  836. message: "Order of playlists successfully updated"
  837. });
  838. }
  839. );
  840. }),
  841. /**
  842. * Updates a user's preferences
  843. *
  844. * @param {object} session - the session object automatically added by the websocket
  845. * @param {object} preferences - object containing preferences
  846. * @param {boolean} preferences.nightmode - whether or not the user is using the night mode theme
  847. * @param {boolean} preferences.autoSkipDisliked - whether to automatically skip disliked songs
  848. * @param {boolean} preferences.activityLogPublic - whether or not a user's activity log can be publicly viewed
  849. * @param {boolean} preferences.anonymousSongRequests - whether or not a user's requested songs will be anonymous
  850. * @param {boolean} preferences.activityWatch - whether or not a user is using the ActivityWatch integration
  851. * @param {Function} cb - gets called with the result
  852. */
  853. updatePreferences: isLoginRequired(async function updatePreferences(session, preferences, cb) {
  854. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  855. async.waterfall(
  856. [
  857. next => {
  858. userModel.findByIdAndUpdate(
  859. session.userId,
  860. {
  861. $set: {
  862. preferences: {
  863. nightmode: preferences.nightmode,
  864. autoSkipDisliked: preferences.autoSkipDisliked,
  865. activityLogPublic: preferences.activityLogPublic,
  866. anonymousSongRequests: preferences.anonymousSongRequests,
  867. activityWatch: preferences.activityWatch
  868. }
  869. }
  870. },
  871. { new: false },
  872. next
  873. );
  874. }
  875. ],
  876. async (err, user) => {
  877. if (err) {
  878. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  879. this.log(
  880. "ERROR",
  881. "UPDATE_USER_PREFERENCES",
  882. `Couldn't update preferences for user "${session.userId}" to "${JSON.stringify(
  883. preferences
  884. )}". "${err}"`
  885. );
  886. return cb({ status: "error", message: err });
  887. }
  888. CacheModule.runJob("PUB", {
  889. channel: "user.updatePreferences",
  890. value: {
  891. preferences,
  892. userId: session.userId
  893. }
  894. });
  895. if (preferences.nightmode !== user.preferences.nightmode)
  896. ActivitiesModule.runJob("ADD_ACTIVITY", {
  897. userId: session.userId,
  898. type: "user__toggle_nightmode",
  899. payload: { message: preferences.nightmode ? "Enabled nightmode" : "Disabled nightmode" }
  900. });
  901. if (preferences.autoSkipDisliked !== user.preferences.autoSkipDisliked)
  902. ActivitiesModule.runJob("ADD_ACTIVITY", {
  903. userId: session.userId,
  904. type: "user__toggle_autoskip_disliked_songs",
  905. payload: {
  906. message: preferences.autoSkipDisliked
  907. ? "Enabled the autoskipping of disliked songs"
  908. : "Disabled the autoskipping of disliked songs"
  909. }
  910. });
  911. if (preferences.activityWatch !== user.preferences.activityWatch)
  912. ActivitiesModule.runJob("ADD_ACTIVITY", {
  913. userId: session.userId,
  914. type: "user__toggle_activity_watch",
  915. payload: {
  916. message: preferences.activityWatch
  917. ? "Enabled ActivityWatch integration"
  918. : "Disabled ActivityWatch integration"
  919. }
  920. });
  921. this.log(
  922. "SUCCESS",
  923. "UPDATE_USER_PREFERENCES",
  924. `Updated preferences for user "${session.userId}" to "${JSON.stringify(preferences)}".`
  925. );
  926. return cb({
  927. status: "success",
  928. message: "Preferences successfully updated"
  929. });
  930. }
  931. );
  932. }),
  933. /**
  934. * Retrieves a user's preferences
  935. *
  936. * @param {object} session - the session object automatically added by the websocket
  937. * @param {Function} cb - gets called with the result
  938. */
  939. getPreferences: isLoginRequired(async function updatePreferences(session, cb) {
  940. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  941. async.waterfall(
  942. [
  943. next => {
  944. userModel.findById(session.userId).select({ preferences: -1 }).exec(next);
  945. }
  946. ],
  947. async (err, { preferences }) => {
  948. if (err) {
  949. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  950. this.log(
  951. "ERROR",
  952. "GET_USER_PREFERENCES",
  953. `Couldn't retrieve preferences for user "${session.userId}". "${err}"`
  954. );
  955. return cb({ status: "error", message: err });
  956. }
  957. this.log(
  958. "SUCCESS",
  959. "GET_USER_PREFERENCES",
  960. `Successfully obtained preferences for user "${session.userId}".`
  961. );
  962. return cb({
  963. status: "success",
  964. message: "Preferences successfully retrieved",
  965. data: { preferences }
  966. });
  967. }
  968. );
  969. }),
  970. /**
  971. * Gets user object from username (only a few properties)
  972. *
  973. * @param {object} session - the session object automatically added by the websocket
  974. * @param {string} username - the username of the user we are trying to find
  975. * @param {Function} cb - gets called with the result
  976. */
  977. findByUsername: async function findByUsername(session, username, cb) {
  978. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  979. async.waterfall(
  980. [
  981. next => {
  982. userModel.findOne({ username: new RegExp(`^${username}$`, "i") }, next);
  983. },
  984. (account, next) => {
  985. if (!account) return next("User not found.");
  986. return next(null, account);
  987. }
  988. ],
  989. async (err, account) => {
  990. if (err && err !== true) {
  991. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  992. this.log("ERROR", "FIND_BY_USERNAME", `User not found for username "${username}". "${err}"`);
  993. return cb({ status: "error", message: err });
  994. }
  995. this.log("SUCCESS", "FIND_BY_USERNAME", `User found for username "${username}".`);
  996. return cb({
  997. status: "success",
  998. data: {
  999. _id: account._id,
  1000. name: account.name,
  1001. username: account.username,
  1002. location: account.location,
  1003. bio: account.bio,
  1004. role: account.role,
  1005. avatar: account.avatar,
  1006. createdAt: account.createdAt
  1007. }
  1008. });
  1009. }
  1010. );
  1011. },
  1012. /**
  1013. * Gets a username from an userId
  1014. *
  1015. * @param {object} session - the session object automatically added by the websocket
  1016. * @param {string} userId - the userId of the person we are trying to get the username from
  1017. * @param {Function} cb - gets called with the result
  1018. */
  1019. async getUsernameFromId(session, userId, cb) {
  1020. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1021. userModel
  1022. .findById(userId)
  1023. .then(user => {
  1024. if (user) {
  1025. this.log("SUCCESS", "GET_USERNAME_FROM_ID", `Found username for userId "${userId}".`);
  1026. return cb({
  1027. status: "success",
  1028. data: { username: user.username }
  1029. });
  1030. }
  1031. this.log(
  1032. "ERROR",
  1033. "GET_USERNAME_FROM_ID",
  1034. `Getting the username from userId "${userId}" failed. User not found.`
  1035. );
  1036. return cb({
  1037. status: "error",
  1038. message: "Couldn't find the user."
  1039. });
  1040. })
  1041. .catch(async err => {
  1042. if (err && err !== true) {
  1043. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1044. this.log(
  1045. "ERROR",
  1046. "GET_USERNAME_FROM_ID",
  1047. `Getting the username from userId "${userId}" failed. "${err}"`
  1048. );
  1049. cb({ status: "error", message: err });
  1050. }
  1051. });
  1052. },
  1053. /**
  1054. * Gets a user from a userId
  1055. *
  1056. * @param {object} session - the session object automatically added by the websocket
  1057. * @param {string} userId - the userId of the person we are trying to get the username from
  1058. * @param {Function} cb - gets called with the result
  1059. */
  1060. getUserFromId: isAdminRequired(async function getUserFromId(session, userId, cb) {
  1061. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1062. userModel
  1063. .findById(userId)
  1064. .then(user => {
  1065. if (user) {
  1066. this.log("SUCCESS", "GET_USER_FROM_ID", `Found user for userId "${userId}".`);
  1067. return cb({
  1068. status: "success",
  1069. data: {
  1070. _id: user._id,
  1071. username: user.username,
  1072. role: user.role,
  1073. liked: user.liked,
  1074. disliked: user.disliked,
  1075. songsRequested: user.statistics.songsRequested,
  1076. email: {
  1077. address: user.email.address,
  1078. verified: user.email.verified
  1079. },
  1080. hasPassword: !!user.services.password,
  1081. services: { github: user.services.github }
  1082. }
  1083. });
  1084. }
  1085. this.log(
  1086. "ERROR",
  1087. "GET_USER_FROM_ID",
  1088. `Getting the user from userId "${userId}" failed. User not found.`
  1089. );
  1090. return cb({
  1091. status: "error",
  1092. message: "Couldn't find the user."
  1093. });
  1094. })
  1095. .catch(async err => {
  1096. if (err && err !== true) {
  1097. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1098. this.log("ERROR", "GET_USER_FROM_ID", `Getting the user from userId "${userId}" failed. "${err}"`);
  1099. cb({ status: "error", message: err });
  1100. }
  1101. });
  1102. }),
  1103. // TODO Fix security issues
  1104. /**
  1105. * Gets user info from session
  1106. *
  1107. * @param {object} session - the session object automatically added by the websocket
  1108. * @param {Function} cb - gets called with the result
  1109. */
  1110. async findBySession(session, cb) {
  1111. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1112. async.waterfall(
  1113. [
  1114. next => {
  1115. CacheModule.runJob(
  1116. "HGET",
  1117. {
  1118. table: "sessions",
  1119. key: session.sessionId
  1120. },
  1121. this
  1122. )
  1123. .then(session => next(null, session))
  1124. .catch(next);
  1125. },
  1126. (session, next) => {
  1127. if (!session) return next("Session not found.");
  1128. return next(null, session);
  1129. },
  1130. (session, next) => {
  1131. userModel.findOne({ _id: session.userId }, next);
  1132. },
  1133. (user, next) => {
  1134. if (!user) return next("User not found.");
  1135. return next(null, user);
  1136. }
  1137. ],
  1138. async (err, user) => {
  1139. if (err && err !== true) {
  1140. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1141. this.log("ERROR", "FIND_BY_SESSION", `User not found. "${err}"`);
  1142. return cb({ status: "error", message: err });
  1143. }
  1144. const sanitisedUser = {
  1145. email: {
  1146. address: user.email.address
  1147. },
  1148. avatar: user.avatar,
  1149. username: user.username,
  1150. name: user.name,
  1151. location: user.location,
  1152. bio: user.bio
  1153. };
  1154. if (user.services.password && user.services.password.password) sanitisedUser.password = true;
  1155. if (user.services.github && user.services.github.id) sanitisedUser.github = true;
  1156. this.log("SUCCESS", "FIND_BY_SESSION", `User found. "${user.username}".`);
  1157. return cb({
  1158. status: "success",
  1159. data: { user: sanitisedUser }
  1160. });
  1161. }
  1162. );
  1163. },
  1164. /**
  1165. * Updates a user's username
  1166. *
  1167. * @param {object} session - the session object automatically added by the websocket
  1168. * @param {string} updatingUserId - the updating user's id
  1169. * @param {string} newUsername - the new username
  1170. * @param {Function} cb - gets called with the result
  1171. */
  1172. updateUsername: isLoginRequired(async function updateUsername(session, updatingUserId, newUsername, cb) {
  1173. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1174. async.waterfall(
  1175. [
  1176. next => {
  1177. if (updatingUserId === session.userId) return next(null, true);
  1178. return userModel.findOne({ _id: session.userId }, next);
  1179. },
  1180. (user, next) => {
  1181. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1182. return userModel.findOne({ _id: updatingUserId }, next);
  1183. },
  1184. (user, next) => {
  1185. if (!user) return next("User not found.");
  1186. if (user.username === newUsername)
  1187. return next("New username can't be the same as the old username.");
  1188. return next(null);
  1189. },
  1190. next => {
  1191. userModel.findOne({ username: new RegExp(`^${newUsername}$`, "i") }, next);
  1192. },
  1193. (user, next) => {
  1194. if (!user) return next();
  1195. if (user._id === updatingUserId) return next();
  1196. return next("That username is already in use.");
  1197. },
  1198. next => {
  1199. userModel.updateOne(
  1200. { _id: updatingUserId },
  1201. { $set: { username: newUsername } },
  1202. { runValidators: true },
  1203. next
  1204. );
  1205. }
  1206. ],
  1207. async err => {
  1208. if (err && err !== true) {
  1209. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1210. this.log(
  1211. "ERROR",
  1212. "UPDATE_USERNAME",
  1213. `Couldn't update username for user "${updatingUserId}" to username "${newUsername}". "${err}"`
  1214. );
  1215. return cb({ status: "error", message: err });
  1216. }
  1217. CacheModule.runJob("PUB", {
  1218. channel: "user.updateUsername",
  1219. value: {
  1220. username: newUsername,
  1221. _id: updatingUserId
  1222. }
  1223. });
  1224. this.log(
  1225. "SUCCESS",
  1226. "UPDATE_USERNAME",
  1227. `Updated username for user "${updatingUserId}" to username "${newUsername}".`
  1228. );
  1229. return cb({
  1230. status: "success",
  1231. message: "Username updated successfully"
  1232. });
  1233. }
  1234. );
  1235. }),
  1236. /**
  1237. * Updates a user's email
  1238. *
  1239. * @param {object} session - the session object automatically added by the websocket
  1240. * @param {string} updatingUserId - the updating user's id
  1241. * @param {string} newEmail - the new email
  1242. * @param {Function} cb - gets called with the result
  1243. */
  1244. updateEmail: isLoginRequired(async function updateEmail(session, updatingUserId, newEmail, cb) {
  1245. newEmail = newEmail.toLowerCase();
  1246. const verificationToken = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 64 }, this);
  1247. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1248. const verifyEmailSchema = await MailModule.runJob("GET_SCHEMA", { schemaName: "verifyEmail" }, this);
  1249. async.waterfall(
  1250. [
  1251. next => {
  1252. if (updatingUserId === session.userId) return next(null, true);
  1253. return userModel.findOne({ _id: session.userId }, next);
  1254. },
  1255. (user, next) => {
  1256. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1257. return userModel.findOne({ _id: updatingUserId }, next);
  1258. },
  1259. (user, next) => {
  1260. if (!user) return next("User not found.");
  1261. if (user.email.address === newEmail)
  1262. return next("New email can't be the same as your the old email.");
  1263. return next();
  1264. },
  1265. next => {
  1266. userModel.findOne({ "email.address": newEmail }, next);
  1267. },
  1268. (user, next) => {
  1269. if (!user) return next();
  1270. if (user._id === updatingUserId) return next();
  1271. return next("That email is already in use.");
  1272. },
  1273. // regenerate the url for gravatar avatar
  1274. next => {
  1275. UtilsModule.runJob("CREATE_GRAVATAR", { email: newEmail }, this).then(url => {
  1276. next(null, url);
  1277. });
  1278. },
  1279. (newAvatarUrl, next) => {
  1280. userModel.updateOne(
  1281. { _id: updatingUserId },
  1282. {
  1283. $set: {
  1284. "avatar.url": newAvatarUrl,
  1285. "email.address": newEmail,
  1286. "email.verified": false,
  1287. "email.verificationToken": verificationToken
  1288. }
  1289. },
  1290. { runValidators: true },
  1291. next
  1292. );
  1293. },
  1294. (res, next) => {
  1295. userModel.findOne({ _id: updatingUserId }, next);
  1296. },
  1297. (user, next) => {
  1298. verifyEmailSchema(newEmail, user.username, verificationToken, err => {
  1299. next(err);
  1300. });
  1301. }
  1302. ],
  1303. async err => {
  1304. if (err && err !== true) {
  1305. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1306. this.log(
  1307. "ERROR",
  1308. "UPDATE_EMAIL",
  1309. `Couldn't update email for user "${updatingUserId}" to email "${newEmail}". '${err}'`
  1310. );
  1311. return cb({ status: "error", message: err });
  1312. }
  1313. this.log(
  1314. "SUCCESS",
  1315. "UPDATE_EMAIL",
  1316. `Updated email for user "${updatingUserId}" to email "${newEmail}".`
  1317. );
  1318. return cb({
  1319. status: "success",
  1320. message: "Email updated successfully."
  1321. });
  1322. }
  1323. );
  1324. }),
  1325. /**
  1326. * Updates a user's name
  1327. *
  1328. * @param {object} session - the session object automatically added by the websocket
  1329. * @param {string} updatingUserId - the updating user's id
  1330. * @param {string} newBio - the new name
  1331. * @param {Function} cb - gets called with the result
  1332. */
  1333. updateName: isLoginRequired(async function updateName(session, updatingUserId, newName, cb) {
  1334. const userModel = await DBModule.runJob(
  1335. "GET_MODEL",
  1336. {
  1337. modelName: "user"
  1338. },
  1339. this
  1340. );
  1341. async.waterfall(
  1342. [
  1343. next => {
  1344. if (updatingUserId === session.userId) return next(null, true);
  1345. return userModel.findOne({ _id: session.userId }, next);
  1346. },
  1347. (user, next) => {
  1348. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1349. return userModel.findOne({ _id: updatingUserId }, next);
  1350. },
  1351. (user, next) => {
  1352. if (!user) return next("User not found.");
  1353. return userModel.updateOne(
  1354. { _id: updatingUserId },
  1355. { $set: { name: newName } },
  1356. { runValidators: true },
  1357. next
  1358. );
  1359. }
  1360. ],
  1361. async err => {
  1362. if (err && err !== true) {
  1363. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1364. this.log(
  1365. "ERROR",
  1366. "UPDATE_NAME",
  1367. `Couldn't update name for user "${updatingUserId}" to name "${newName}". "${err}"`
  1368. );
  1369. return cb({ status: "error", message: err });
  1370. }
  1371. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1372. userId: updatingUserId,
  1373. type: "user__edit_name",
  1374. payload: { message: `Changed name to ${newName}` }
  1375. });
  1376. this.log("SUCCESS", "UPDATE_NAME", `Updated name for user "${updatingUserId}" to name "${newName}".`);
  1377. return cb({
  1378. status: "success",
  1379. message: "Name updated successfully"
  1380. });
  1381. }
  1382. );
  1383. }),
  1384. /**
  1385. * Updates a user's location
  1386. *
  1387. * @param {object} session - the session object automatically added by the websocket
  1388. * @param {string} updatingUserId - the updating user's id
  1389. * @param {string} newLocation - the new location
  1390. * @param {Function} cb - gets called with the result
  1391. */
  1392. updateLocation: isLoginRequired(async function updateLocation(session, updatingUserId, newLocation, cb) {
  1393. const userModel = await DBModule.runJob(
  1394. "GET_MODEL",
  1395. {
  1396. modelName: "user"
  1397. },
  1398. this
  1399. );
  1400. async.waterfall(
  1401. [
  1402. next => {
  1403. if (updatingUserId === session.userId) return next(null, true);
  1404. return userModel.findOne({ _id: session.userId }, next);
  1405. },
  1406. (user, next) => {
  1407. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1408. return userModel.findOne({ _id: updatingUserId }, next);
  1409. },
  1410. (user, next) => {
  1411. if (!user) return next("User not found.");
  1412. return userModel.updateOne(
  1413. { _id: updatingUserId },
  1414. { $set: { location: newLocation } },
  1415. { runValidators: true },
  1416. next
  1417. );
  1418. }
  1419. ],
  1420. async err => {
  1421. if (err && err !== true) {
  1422. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1423. this.log(
  1424. "ERROR",
  1425. "UPDATE_LOCATION",
  1426. `Couldn't update location for user "${updatingUserId}" to location "${newLocation}". "${err}"`
  1427. );
  1428. return cb({ status: "error", message: err });
  1429. }
  1430. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1431. userId: updatingUserId,
  1432. type: "user__edit_location",
  1433. payload: { message: `Changed location to ${newLocation}` }
  1434. });
  1435. this.log(
  1436. "SUCCESS",
  1437. "UPDATE_LOCATION",
  1438. `Updated location for user "${updatingUserId}" to location "${newLocation}".`
  1439. );
  1440. return cb({
  1441. status: "success",
  1442. message: "Location updated successfully"
  1443. });
  1444. }
  1445. );
  1446. }),
  1447. /**
  1448. * Updates a user's bio
  1449. *
  1450. * @param {object} session - the session object automatically added by the websocket
  1451. * @param {string} updatingUserId - the updating user's id
  1452. * @param {string} newBio - the new bio
  1453. * @param {Function} cb - gets called with the result
  1454. */
  1455. updateBio: isLoginRequired(async function updateBio(session, updatingUserId, newBio, cb) {
  1456. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1457. async.waterfall(
  1458. [
  1459. next => {
  1460. if (updatingUserId === session.userId) return next(null, true);
  1461. return userModel.findOne({ _id: session.userId }, next);
  1462. },
  1463. (user, next) => {
  1464. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1465. return userModel.findOne({ _id: updatingUserId }, next);
  1466. },
  1467. (user, next) => {
  1468. if (!user) return next("User not found.");
  1469. return userModel.updateOne(
  1470. { _id: updatingUserId },
  1471. { $set: { bio: newBio } },
  1472. { runValidators: true },
  1473. next
  1474. );
  1475. }
  1476. ],
  1477. async err => {
  1478. if (err && err !== true) {
  1479. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1480. this.log(
  1481. "ERROR",
  1482. "UPDATE_BIO",
  1483. `Couldn't update bio for user "${updatingUserId}" to bio "${newBio}". "${err}"`
  1484. );
  1485. return cb({ status: "error", message: err });
  1486. }
  1487. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1488. userId: updatingUserId,
  1489. type: "user__edit_bio",
  1490. payload: { message: `Changed bio to ${newBio}` }
  1491. });
  1492. this.log("SUCCESS", "UPDATE_BIO", `Updated bio for user "${updatingUserId}" to bio "${newBio}".`);
  1493. return cb({
  1494. status: "success",
  1495. message: "Bio updated successfully"
  1496. });
  1497. }
  1498. );
  1499. }),
  1500. /**
  1501. * Updates the type of a user's avatar
  1502. *
  1503. * @param {object} session - the session object automatically added by the websocket
  1504. * @param {string} updatingUserId - the updating user's id
  1505. * @param {string} newType - the new type
  1506. * @param {Function} cb - gets called with the result
  1507. */
  1508. updateAvatarType: isLoginRequired(async function updateAvatarType(session, updatingUserId, newAvatar, cb) {
  1509. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1510. async.waterfall(
  1511. [
  1512. next => {
  1513. if (updatingUserId === session.userId) return next(null, true);
  1514. return userModel.findOne({ _id: session.userId }, next);
  1515. },
  1516. (user, next) => {
  1517. if (user !== true && (!user || user.role !== "admin")) return next("Invalid permissions.");
  1518. return userModel.findOne({ _id: updatingUserId }, next);
  1519. },
  1520. (user, next) => {
  1521. if (!user) return next("User not found.");
  1522. return userModel.findOneAndUpdate(
  1523. { _id: updatingUserId },
  1524. { $set: { "avatar.type": newAvatar.type, "avatar.color": newAvatar.color } },
  1525. { new: true, runValidators: true },
  1526. next
  1527. );
  1528. }
  1529. ],
  1530. async err => {
  1531. if (err && err !== true) {
  1532. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1533. this.log(
  1534. "ERROR",
  1535. "UPDATE_AVATAR_TYPE",
  1536. `Couldn't update avatar type for user "${updatingUserId}" to type "${newAvatar.type}". "${err}"`
  1537. );
  1538. return cb({ status: "error", message: err });
  1539. }
  1540. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1541. userId: updatingUserId,
  1542. type: "user__edit_avatar",
  1543. payload: { message: `Changed avatar to use ${newAvatar.type}` }
  1544. });
  1545. this.log(
  1546. "SUCCESS",
  1547. "UPDATE_AVATAR_TYPE",
  1548. `Updated avatar type for user "${updatingUserId}" to type "${newAvatar.type}".`
  1549. );
  1550. return cb({
  1551. status: "success",
  1552. message: "Avatar type updated successfully"
  1553. });
  1554. }
  1555. );
  1556. }),
  1557. /**
  1558. * Updates a user's role
  1559. *
  1560. * @param {object} session - the session object automatically added by the websocket
  1561. * @param {string} updatingUserId - the updating user's id
  1562. * @param {string} newRole - the new role
  1563. * @param {Function} cb - gets called with the result
  1564. */
  1565. updateRole: isAdminRequired(async function updateRole(session, updatingUserId, newRole, cb) {
  1566. newRole = newRole.toLowerCase();
  1567. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1568. async.waterfall(
  1569. [
  1570. next => {
  1571. userModel.findOne({ _id: updatingUserId }, next);
  1572. },
  1573. (user, next) => {
  1574. if (!user) return next("User not found.");
  1575. if (user.role === newRole) return next("New role can't be the same as the old role.");
  1576. return next();
  1577. },
  1578. next => {
  1579. userModel.updateOne(
  1580. { _id: updatingUserId },
  1581. { $set: { role: newRole } },
  1582. { runValidators: true },
  1583. next
  1584. );
  1585. }
  1586. ],
  1587. async err => {
  1588. if (err && err !== true) {
  1589. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1590. this.log(
  1591. "ERROR",
  1592. "UPDATE_ROLE",
  1593. `User "${session.userId}" couldn't update role for user "${updatingUserId}" to role "${newRole}". "${err}"`
  1594. );
  1595. return cb({ status: "error", message: err });
  1596. }
  1597. this.log(
  1598. "SUCCESS",
  1599. "UPDATE_ROLE",
  1600. `User "${session.userId}" updated the role of user "${updatingUserId}" to role "${newRole}".`
  1601. );
  1602. return cb({
  1603. status: "success",
  1604. message: "Role successfully updated."
  1605. });
  1606. }
  1607. );
  1608. }),
  1609. /**
  1610. * Updates a user's password
  1611. *
  1612. * @param {object} session - the session object automatically added by the websocket
  1613. * @param {string} previousPassword - the previous password
  1614. * @param {string} newPassword - the new password
  1615. * @param {Function} cb - gets called with the result
  1616. */
  1617. updatePassword: isLoginRequired(async function updatePassword(session, previousPassword, newPassword, cb) {
  1618. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1619. async.waterfall(
  1620. [
  1621. next => {
  1622. userModel.findOne({ _id: session.userId }, next);
  1623. },
  1624. (user, next) => {
  1625. if (!user.services.password) return next("This account does not have a password set.");
  1626. return next(null, user.services.password.password);
  1627. },
  1628. (storedPassword, next) => {
  1629. bcrypt.compare(sha256(previousPassword), storedPassword).then(res => {
  1630. if (res) return next();
  1631. return next("Please enter the correct previous password.");
  1632. });
  1633. },
  1634. next => {
  1635. if (!DBModule.passwordValid(newPassword))
  1636. return next("Invalid new password. Check if it meets all the requirements.");
  1637. return next();
  1638. },
  1639. next => {
  1640. bcrypt.genSalt(10, next);
  1641. },
  1642. // hash the password
  1643. (salt, next) => {
  1644. bcrypt.hash(sha256(newPassword), salt, next);
  1645. },
  1646. (hashedPassword, next) => {
  1647. userModel.updateOne(
  1648. { _id: session.userId },
  1649. {
  1650. $set: {
  1651. "services.password.password": hashedPassword
  1652. }
  1653. },
  1654. next
  1655. );
  1656. }
  1657. ],
  1658. async err => {
  1659. if (err) {
  1660. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1661. this.log(
  1662. "ERROR",
  1663. "UPDATE_PASSWORD",
  1664. `Failed updating user password of user '${session.userId}'. '${err}'.`
  1665. );
  1666. return cb({ status: "error", message: err });
  1667. }
  1668. this.log("SUCCESS", "UPDATE_PASSWORD", `User '${session.userId}' updated their password.`);
  1669. return cb({
  1670. status: "success",
  1671. message: "Password successfully updated."
  1672. });
  1673. }
  1674. );
  1675. }),
  1676. /**
  1677. * Requests a password for a session
  1678. *
  1679. * @param {object} session - the session object automatically added by the websocket
  1680. * @param {string} email - the email of the user that requests a password reset
  1681. * @param {Function} cb - gets called with the result
  1682. */
  1683. requestPassword: isLoginRequired(async function requestPassword(session, cb) {
  1684. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1685. const passwordRequestSchema = await MailModule.runJob(
  1686. "GET_SCHEMA",
  1687. {
  1688. schemaName: "passwordRequest"
  1689. },
  1690. this
  1691. );
  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) return next("User not found.");
  1700. if (user.services.password && user.services.password.password)
  1701. return next("You already have a password set.");
  1702. return next(null, user);
  1703. },
  1704. (user, next) => {
  1705. const expires = new Date();
  1706. expires.setDate(expires.getDate() + 1);
  1707. userModel.findOneAndUpdate(
  1708. { "email.address": user.email.address },
  1709. {
  1710. $set: {
  1711. "services.password": {
  1712. set: { code, expires }
  1713. }
  1714. }
  1715. },
  1716. { runValidators: true },
  1717. next
  1718. );
  1719. },
  1720. (user, next) => {
  1721. passwordRequestSchema(user.email.address, user.username, code, next);
  1722. }
  1723. ],
  1724. async err => {
  1725. if (err && err !== true) {
  1726. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1727. this.log(
  1728. "ERROR",
  1729. "REQUEST_PASSWORD",
  1730. `UserId '${session.userId}' failed to request password. '${err}'`
  1731. );
  1732. return cb({ status: "error", message: err });
  1733. }
  1734. this.log(
  1735. "SUCCESS",
  1736. "REQUEST_PASSWORD",
  1737. `UserId '${session.userId}' successfully requested a password.`
  1738. );
  1739. return cb({
  1740. status: "success",
  1741. message: "Successfully requested password."
  1742. });
  1743. }
  1744. );
  1745. }),
  1746. /**
  1747. * Verifies a password code
  1748. *
  1749. * @param {object} session - the session object automatically added by the websocket
  1750. * @param {string} code - the password code
  1751. * @param {Function} cb - gets called with the result
  1752. */
  1753. verifyPasswordCode: isLoginRequired(async function verifyPasswordCode(session, code, cb) {
  1754. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1755. async.waterfall(
  1756. [
  1757. next => {
  1758. if (!code || typeof code !== "string") return next("Invalid code.");
  1759. return userModel.findOne(
  1760. {
  1761. "services.password.set.code": code,
  1762. _id: session.userId
  1763. },
  1764. next
  1765. );
  1766. },
  1767. (user, next) => {
  1768. if (!user) return next("Invalid code.");
  1769. if (user.services.password.set.expires < new Date()) return next("That code has expired.");
  1770. return next(null);
  1771. }
  1772. ],
  1773. async err => {
  1774. if (err && err !== true) {
  1775. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1776. this.log("ERROR", "VERIFY_PASSWORD_CODE", `Code '${code}' failed to verify. '${err}'`);
  1777. cb({ status: "error", message: err });
  1778. } else {
  1779. this.log("SUCCESS", "VERIFY_PASSWORD_CODE", `Code '${code}' successfully verified.`);
  1780. cb({
  1781. status: "success",
  1782. message: "Successfully verified password code."
  1783. });
  1784. }
  1785. }
  1786. );
  1787. }),
  1788. /**
  1789. * Adds a password to a user with a code
  1790. *
  1791. * @param {object} session - the session object automatically added by the websocket
  1792. * @param {string} code - the password code
  1793. * @param {string} newPassword - the new password code
  1794. * @param {Function} cb - gets called with the result
  1795. */
  1796. changePasswordWithCode: isLoginRequired(async function changePasswordWithCode(session, code, newPassword, cb) {
  1797. const userModel = await DBModule.runJob(
  1798. "GET_MODEL",
  1799. {
  1800. modelName: "user"
  1801. },
  1802. this
  1803. );
  1804. async.waterfall(
  1805. [
  1806. next => {
  1807. if (!code || typeof code !== "string") return next("Invalid code.");
  1808. return userModel.findOne({ "services.password.set.code": code }, next);
  1809. },
  1810. (user, next) => {
  1811. if (!user) return next("Invalid code.");
  1812. if (!user.services.password.set.expires > new Date()) return next("That code has expired.");
  1813. return next();
  1814. },
  1815. next => {
  1816. if (!DBModule.passwordValid(newPassword))
  1817. return next("Invalid password. Check if it meets all the requirements.");
  1818. return next();
  1819. },
  1820. next => {
  1821. bcrypt.genSalt(10, next);
  1822. },
  1823. // hash the password
  1824. (salt, next) => {
  1825. bcrypt.hash(sha256(newPassword), salt, next);
  1826. },
  1827. (hashedPassword, next) => {
  1828. userModel.updateOne(
  1829. { "services.password.set.code": code },
  1830. {
  1831. $set: {
  1832. "services.password.password": hashedPassword
  1833. },
  1834. $unset: { "services.password.set": "" }
  1835. },
  1836. { runValidators: true },
  1837. next
  1838. );
  1839. }
  1840. ],
  1841. async err => {
  1842. if (err && err !== true) {
  1843. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1844. this.log("ERROR", "ADD_PASSWORD_WITH_CODE", `Code '${code}' failed to add password. '${err}'`);
  1845. return cb({ status: "error", message: err });
  1846. }
  1847. this.log("SUCCESS", "ADD_PASSWORD_WITH_CODE", `Code '${code}' successfully added password.`);
  1848. CacheModule.runJob("PUB", {
  1849. channel: "user.linkPassword",
  1850. value: session.userId
  1851. });
  1852. return cb({
  1853. status: "success",
  1854. message: "Successfully added password."
  1855. });
  1856. }
  1857. );
  1858. }),
  1859. /**
  1860. * Unlinks password from user
  1861. *
  1862. * @param {object} session - the session object automatically added by the websocket
  1863. * @param {Function} cb - gets called with the result
  1864. */
  1865. unlinkPassword: isLoginRequired(async function unlinkPassword(session, cb) {
  1866. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1867. async.waterfall(
  1868. [
  1869. next => {
  1870. userModel.findOne({ _id: session.userId }, next);
  1871. },
  1872. (user, next) => {
  1873. if (!user) return next("Not logged in.");
  1874. if (!user.services.github || !user.services.github.id)
  1875. return next("You can't remove password login without having GitHub login.");
  1876. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.password": "" } }, next);
  1877. }
  1878. ],
  1879. async err => {
  1880. if (err && err !== true) {
  1881. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1882. this.log(
  1883. "ERROR",
  1884. "UNLINK_PASSWORD",
  1885. `Unlinking password failed for userId '${session.userId}'. '${err}'`
  1886. );
  1887. return cb({ status: "error", message: err });
  1888. }
  1889. this.log("SUCCESS", "UNLINK_PASSWORD", `Unlinking password successful for userId '${session.userId}'.`);
  1890. CacheModule.runJob("PUB", {
  1891. channel: "user.unlinkPassword",
  1892. value: session.userId
  1893. });
  1894. return cb({
  1895. status: "success",
  1896. message: "Successfully unlinked password."
  1897. });
  1898. }
  1899. );
  1900. }),
  1901. /**
  1902. * Unlinks GitHub from user
  1903. *
  1904. * @param {object} session - the session object automatically added by the websocket
  1905. * @param {Function} cb - gets called with the result
  1906. */
  1907. unlinkGitHub: isLoginRequired(async function unlinkGitHub(session, cb) {
  1908. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1909. async.waterfall(
  1910. [
  1911. next => {
  1912. userModel.findOne({ _id: session.userId }, next);
  1913. },
  1914. (user, next) => {
  1915. if (!user) return next("Not logged in.");
  1916. if (!user.services.password || !user.services.password.password)
  1917. return next("You can't remove GitHub login without having password login.");
  1918. return userModel.updateOne({ _id: session.userId }, { $unset: { "services.github": "" } }, next);
  1919. }
  1920. ],
  1921. async err => {
  1922. if (err && err !== true) {
  1923. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1924. this.log(
  1925. "ERROR",
  1926. "UNLINK_GITHUB",
  1927. `Unlinking GitHub failed for userId '${session.userId}'. '${err}'`
  1928. );
  1929. return cb({ status: "error", message: err });
  1930. }
  1931. this.log("SUCCESS", "UNLINK_GITHUB", `Unlinking GitHub successful for userId '${session.userId}'.`);
  1932. CacheModule.runJob("PUB", {
  1933. channel: "user.unlinkGithub",
  1934. value: session.userId
  1935. });
  1936. return cb({
  1937. status: "success",
  1938. message: "Successfully unlinked GitHub."
  1939. });
  1940. }
  1941. );
  1942. }),
  1943. /**
  1944. * Requests a password reset for an email
  1945. *
  1946. * @param {object} session - the session object automatically added by the websocket
  1947. * @param {string} email - the email of the user that requests a password reset
  1948. * @param {Function} cb - gets called with the result
  1949. */
  1950. async requestPasswordReset(session, email, cb) {
  1951. const code = await UtilsModule.runJob("GENERATE_RANDOM_STRING", { length: 8 }, this);
  1952. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1953. const resetPasswordRequestSchema = await MailModule.runJob(
  1954. "GET_SCHEMA",
  1955. { schemaName: "resetPasswordRequest" },
  1956. this
  1957. );
  1958. async.waterfall(
  1959. [
  1960. next => {
  1961. if (!email || typeof email !== "string") return next("Invalid email.");
  1962. email = email.toLowerCase();
  1963. return userModel.findOne({ "email.address": email }, next);
  1964. },
  1965. (user, next) => {
  1966. if (!user) return next("User not found.");
  1967. if (!user.services.password || !user.services.password.password)
  1968. return next("User does not have a password set, and probably uses GitHub to log in.");
  1969. return next(null, user);
  1970. },
  1971. (user, next) => {
  1972. const expires = new Date();
  1973. expires.setDate(expires.getDate() + 1);
  1974. userModel.findOneAndUpdate(
  1975. { "email.address": email },
  1976. {
  1977. $set: {
  1978. "services.password.reset": {
  1979. code,
  1980. expires
  1981. }
  1982. }
  1983. },
  1984. { runValidators: true },
  1985. next
  1986. );
  1987. },
  1988. (user, next) => {
  1989. resetPasswordRequestSchema(user.email.address, user.username, code, next);
  1990. }
  1991. ],
  1992. async err => {
  1993. if (err && err !== true) {
  1994. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1995. this.log(
  1996. "ERROR",
  1997. "REQUEST_PASSWORD_RESET",
  1998. `Email '${email}' failed to request password reset. '${err}'`
  1999. );
  2000. return cb({ status: "error", message: err });
  2001. }
  2002. this.log(
  2003. "SUCCESS",
  2004. "REQUEST_PASSWORD_RESET",
  2005. `Email '${email}' successfully requested a password reset.`
  2006. );
  2007. return cb({
  2008. status: "success",
  2009. message: "Successfully requested password reset."
  2010. });
  2011. }
  2012. );
  2013. },
  2014. /**
  2015. * Verifies a reset code
  2016. *
  2017. * @param {object} session - the session object automatically added by the websocket
  2018. * @param {string} code - the password reset code
  2019. * @param {Function} cb - gets called with the result
  2020. */
  2021. async verifyPasswordResetCode(session, code, cb) {
  2022. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2023. async.waterfall(
  2024. [
  2025. next => {
  2026. if (!code || typeof code !== "string") return next("Invalid code.");
  2027. return userModel.findOne({ "services.password.reset.code": code }, next);
  2028. },
  2029. (user, next) => {
  2030. if (!user) return next("Invalid code.");
  2031. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2032. return next(null);
  2033. }
  2034. ],
  2035. async err => {
  2036. if (err && err !== true) {
  2037. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2038. this.log("ERROR", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' failed to verify. '${err}'`);
  2039. return cb({ status: "error", message: err });
  2040. }
  2041. this.log("SUCCESS", "VERIFY_PASSWORD_RESET_CODE", `Code '${code}' successfully verified.`);
  2042. return cb({
  2043. status: "success",
  2044. message: "Successfully verified password reset code."
  2045. });
  2046. }
  2047. );
  2048. },
  2049. /**
  2050. * Changes a user's password with a reset code
  2051. *
  2052. * @param {object} session - the session object automatically added by the websocket
  2053. * @param {string} code - the password reset code
  2054. * @param {string} newPassword - the new password reset code
  2055. * @param {Function} cb - gets called with the result
  2056. */
  2057. async changePasswordWithResetCode(session, code, newPassword, cb) {
  2058. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2059. async.waterfall(
  2060. [
  2061. next => {
  2062. if (!code || typeof code !== "string") return next("Invalid code.");
  2063. return userModel.findOne({ "services.password.reset.code": code }, next);
  2064. },
  2065. (user, next) => {
  2066. if (!user) return next("Invalid code.");
  2067. if (!user.services.password.reset.expires > new Date()) return next("That code has expired.");
  2068. return next();
  2069. },
  2070. next => {
  2071. if (!DBModule.passwordValid(newPassword))
  2072. return next("Invalid password. Check if it meets all the requirements.");
  2073. return next();
  2074. },
  2075. next => {
  2076. bcrypt.genSalt(10, next);
  2077. },
  2078. // hash the password
  2079. (salt, next) => {
  2080. bcrypt.hash(sha256(newPassword), salt, next);
  2081. },
  2082. (hashedPassword, next) => {
  2083. userModel.updateOne(
  2084. { "services.password.reset.code": code },
  2085. {
  2086. $set: {
  2087. "services.password.password": hashedPassword
  2088. },
  2089. $unset: { "services.password.reset": "" }
  2090. },
  2091. { runValidators: true },
  2092. next
  2093. );
  2094. }
  2095. ],
  2096. async err => {
  2097. if (err && err !== true) {
  2098. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2099. this.log(
  2100. "ERROR",
  2101. "CHANGE_PASSWORD_WITH_RESET_CODE",
  2102. `Code '${code}' failed to change password. '${err}'`
  2103. );
  2104. return cb({ status: "error", message: err });
  2105. }
  2106. this.log("SUCCESS", "CHANGE_PASSWORD_WITH_RESET_CODE", `Code '${code}' successfully changed password.`);
  2107. return cb({
  2108. status: "success",
  2109. message: "Successfully changed password."
  2110. });
  2111. }
  2112. );
  2113. },
  2114. /**
  2115. * Bans a user by userId
  2116. *
  2117. * @param {object} session - the session object automatically added by the websocket
  2118. * @param {string} value - the user id that is going to be banned
  2119. * @param {string} reason - the reason for the ban
  2120. * @param {string} expiresAt - the time the ban expires
  2121. * @param {Function} cb - gets called with the result
  2122. */
  2123. banUserById: isAdminRequired(function banUserById(session, userId, reason, expiresAt, cb) {
  2124. async.waterfall(
  2125. [
  2126. next => {
  2127. if (!userId) return next("You must provide a userId to ban.");
  2128. if (!reason) return next("You must provide a reason for the ban.");
  2129. return next();
  2130. },
  2131. next => {
  2132. if (!expiresAt || typeof expiresAt !== "string") return next("Invalid expire date.");
  2133. const date = new Date();
  2134. switch (expiresAt) {
  2135. case "1h":
  2136. expiresAt = date.setHours(date.getHours() + 1);
  2137. break;
  2138. case "12h":
  2139. expiresAt = date.setHours(date.getHours() + 12);
  2140. break;
  2141. case "1d":
  2142. expiresAt = date.setDate(date.getDate() + 1);
  2143. break;
  2144. case "1w":
  2145. expiresAt = date.setDate(date.getDate() + 7);
  2146. break;
  2147. case "1m":
  2148. expiresAt = date.setMonth(date.getMonth() + 1);
  2149. break;
  2150. case "3m":
  2151. expiresAt = date.setMonth(date.getMonth() + 3);
  2152. break;
  2153. case "6m":
  2154. expiresAt = date.setMonth(date.getMonth() + 6);
  2155. break;
  2156. case "1y":
  2157. expiresAt = date.setFullYear(date.getFullYear() + 1);
  2158. break;
  2159. case "never":
  2160. expiresAt = new Date(3093527980800000);
  2161. break;
  2162. default:
  2163. return next("Invalid expire date.");
  2164. }
  2165. return next();
  2166. },
  2167. next => {
  2168. PunishmentsModule.runJob(
  2169. "ADD_PUNISHMENT",
  2170. {
  2171. type: "banUserId",
  2172. value: userId,
  2173. reason,
  2174. expiresAt,
  2175. punishedBy: "" // needs changed
  2176. },
  2177. this
  2178. )
  2179. .then(punishment => next(null, punishment))
  2180. .catch(next);
  2181. },
  2182. (punishment, next) => {
  2183. CacheModule.runJob("PUB", {
  2184. channel: "user.ban",
  2185. value: { userId, punishment }
  2186. });
  2187. next();
  2188. }
  2189. ],
  2190. async err => {
  2191. if (err && err !== true) {
  2192. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2193. this.log(
  2194. "ERROR",
  2195. "BAN_USER_BY_ID",
  2196. `User ${session.userId} failed to ban user ${userId} with the reason ${reason}. '${err}'`
  2197. );
  2198. return cb({ status: "error", message: err });
  2199. }
  2200. this.log(
  2201. "SUCCESS",
  2202. "BAN_USER_BY_ID",
  2203. `User ${session.userId} has successfully banned user ${userId} with the reason ${reason}.`
  2204. );
  2205. return cb({
  2206. status: "success",
  2207. message: "Successfully banned user."
  2208. });
  2209. }
  2210. );
  2211. })
  2212. };