users.js 75 KB

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