users.js 64 KB

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