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