ownerRequired.js 1.7 KB

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