users.js 71 KB

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