ownerRequired.js 1.9 KB

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