users.js 63 KB

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