users.js 63 KB

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