ownerRequired.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 => async (session, stationId, ...args) => {
  8. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  9. const cb = args[args.length - 1];
  10. async.waterfall(
  11. [
  12. next => {
  13. CacheModule.runJob("HGET", {
  14. table: "sessions",
  15. key: session.sessionId
  16. })
  17. .then(session => {
  18. next(null, session);
  19. })
  20. .catch(next);
  21. },
  22. (session, next) => {
  23. if (!session || !session.userId) return next("Login required.");
  24. return userModel.findOne({ _id: session.userId }, next);
  25. },
  26. (user, next) => {
  27. if (!user) return next("Login required.");
  28. if (user.role === "admin") return next(true);
  29. return StationsModule.runJob("GET_STATION", { stationId })
  30. .then(station => {
  31. next(null, station);
  32. })
  33. .catch(next);
  34. },
  35. (station, next) => {
  36. if (!station) return next("Station not found.");
  37. if (station.type === "community" && station.owner === session.userId) return next(true);
  38. return next("Invalid permissions.");
  39. }
  40. ],
  41. async err => {
  42. if (err !== true) {
  43. err = await UtilsModule.runJob("GET_ERROR", { error: err });
  44. console.log(
  45. "INFO",
  46. "OWNER_REQUIRED",
  47. `User failed to pass owner required check for station "${stationId}". "${err}"`
  48. );
  49. return cb({ status: "failure", message: err });
  50. }
  51. console.log(
  52. "INFO",
  53. "OWNER_REQUIRED",
  54. `User "${session.userId}" passed owner required check for station "${stationId}"`,
  55. false
  56. );
  57. return destination(session, stationId, ...args);
  58. }
  59. );
  60. };