users.js 71 KB

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