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