users.js 75 KB

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