ownerRequired.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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) => {
  22. next(null, session)
  23. })
  24. .catch(next);
  25. },
  26. (session, next) => {
  27. if (!session || !session.userId)
  28. return next("Login required.");
  29. this.session = session;
  30. userModel.findOne({ _id: session.userId }, next);
  31. },
  32. (user, next) => {
  33. if (!user) return next("Login required.");
  34. if (user.role === "admin") return next(true);
  35. stations
  36. .runJob("GET_STATION", { stationId })
  37. .then((station) => {
  38. next(null, station);
  39. })
  40. .catch(next);
  41. },
  42. (station, next) => {
  43. if (!station) return next("Station not found.");
  44. if (
  45. station.type === "community" &&
  46. station.owner === session.userId
  47. )
  48. return next(true);
  49. next("Invalid permissions.");
  50. },
  51. ],
  52. async (err) => {
  53. if (err !== true) {
  54. err = await utils.runJob("GET_ERROR", { error: err });
  55. console.log(
  56. "INFO",
  57. "OWNER_REQUIRED",
  58. `User failed to pass owner required check for station "${stationId}". "${err}"`
  59. );
  60. return cb({ status: "failure", message: err });
  61. }
  62. console.log(
  63. "INFO",
  64. "OWNER_REQUIRED",
  65. `User "${session.userId}" passed owner required check for station "${stationId}"`,
  66. false
  67. );
  68. next.apply(null, args);
  69. }
  70. );
  71. };
  72. };