users.js 69 KB

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