users.js 64 KB

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