users.js 69 KB

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