ownerRequired.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const async = require("async");
  2. const moduleManager = require("../../../index");
  3. const db = require("../../db");
  4. const cache = require("../../cache");
  5. const utils = require("../../utils");
  6. const stations = require("../../stations");
  7. module.exports = function(next) {
  8. return async function(session, stationId) {
  9. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  10. let args = [];
  11. for (let prop in arguments) args.push(arguments[prop]);
  12. let cb = args[args.length - 1];
  13. async.waterfall(
  14. [
  15. (next) => {
  16. cache
  17. .runJob("HGET", {
  18. table: "sessions",
  19. key: session.sessionId,
  20. })
  21. .then((session) => next(null, session))
  22. .catch(next);
  23. },
  24. (session, next) => {
  25. if (!session || !session.userId)
  26. return next("Login required.");
  27. this.session = session;
  28. userModel.findOne({ _id: session.userId }, next);
  29. },
  30. (user, next) => {
  31. if (!user) return next("Login required.");
  32. if (user.role === "admin") return next(true);
  33. stations
  34. .runJob("GET_STATION", { stationId })
  35. .then((station) => next(null, station))
  36. .catch(next);
  37. },
  38. (station, next) => {
  39. if (!station) return next("Station not found.");
  40. if (
  41. station.type === "community" &&
  42. station.owner === session.userId
  43. )
  44. return next(true);
  45. next("Invalid permissions.");
  46. },
  47. ],
  48. async (err) => {
  49. if (err !== true) {
  50. err = await utils.runJob("GET_ERROR", { error: err });
  51. console.log(
  52. "INFO",
  53. "OWNER_REQUIRED",
  54. `User failed to pass owner required check for station "${stationId}". "${err}"`
  55. );
  56. return cb({ status: "failure", message: err });
  57. }
  58. console.log(
  59. "INFO",
  60. "OWNER_REQUIRED",
  61. `User "${session.userId}" passed owner required check for station "${stationId}"`,
  62. false
  63. );
  64. next.apply(null, args);
  65. }
  66. );
  67. };
  68. };