ownerRequired.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import async from "async";
  2. import db from "../../db";
  3. import cache from "../../cache";
  4. import utils from "../../utils";
  5. import stations from "../../stations";
  6. export default destination => async (session, stationId, ...args) => {
  7. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  8. const cb = args[args.length - 1];
  9. async.waterfall(
  10. [
  11. next => {
  12. cache
  13. .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 stations
  30. .runJob("GET_STATION", { stationId })
  31. .then(station => {
  32. next(null, station);
  33. })
  34. .catch(next);
  35. },
  36. (station, next) => {
  37. if (!station) return next("Station not found.");
  38. if (station.type === "community" && station.owner === session.userId) return next(true);
  39. return next("Invalid permissions.");
  40. }
  41. ],
  42. async err => {
  43. if (err !== true) {
  44. err = await utils.runJob("GET_ERROR", { error: err });
  45. console.log(
  46. "INFO",
  47. "OWNER_REQUIRED",
  48. `User failed to pass owner required check for station "${stationId}". "${err}"`
  49. );
  50. return cb({ status: "failure", message: err });
  51. }
  52. console.log(
  53. "INFO",
  54. "OWNER_REQUIRED",
  55. `User "${session.userId}" passed owner required check for station "${stationId}"`,
  56. false
  57. );
  58. return destination(session, stationId, ...args);
  59. }
  60. );
  61. };