users.js 70 KB

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