ownerRequired.js 2.0 KB

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