ownerRequired.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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.getStation(stationId, next);
  34. },
  35. (station, next) => {
  36. if (!station) return next("Station not found.");
  37. if (
  38. station.type === "community" &&
  39. station.owner === session.userId
  40. )
  41. return next(true);
  42. next("Invalid permissions.");
  43. },
  44. ],
  45. async (err) => {
  46. if (err !== true) {
  47. err = await utils.runJob("GET_ERROR", { error: err });
  48. console.log(
  49. "INFO",
  50. "OWNER_REQUIRED",
  51. `User failed to pass owner required check for station "${stationId}". "${err}"`
  52. );
  53. return cb({ status: "failure", message: err });
  54. }
  55. console.log(
  56. "INFO",
  57. "OWNER_REQUIRED",
  58. `User "${session.userId}" passed owner required check for station "${stationId}"`,
  59. false
  60. );
  61. next.apply(null, args);
  62. }
  63. );
  64. };
  65. };