ownerRequired.js 2.0 KB

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