users.js 64 KB

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