ownerRequired.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. const async = require('async');
  2. const moduleManager = require("../../../index");
  3. const db = moduleManager.modules["db"];
  4. const cache = moduleManager.modules["cache"];
  5. const utils = moduleManager.modules["utils"];
  6. const logger = moduleManager.modules["logger"];
  7. const stations = moduleManager.modules["stations"];
  8. module.exports = function(next) {
  9. return function(session, stationId) {
  10. let args = [];
  11. for (let prop in arguments) args.push(arguments[prop]);
  12. let cb = args[args.length - 1];
  13. async.waterfall([
  14. (next) => {
  15. cache.hget('sessions', session.sessionId, next);
  16. },
  17. (session, next) => {
  18. if (!session || !session.userId) return next('Login required.');
  19. this.session = session;
  20. db.models.user.findOne({_id: session.userId}, next);
  21. },
  22. (user, next) => {
  23. if (!user) return next('Login required.');
  24. if (user.role === 'admin') return next(true);
  25. stations.getStation(stationId, next);
  26. },
  27. (station, next) => {
  28. if (!station) return next('Station not found.');
  29. if (station.type === 'community' && station.owner === session.userId) return next(true);
  30. next('Invalid permissions.');
  31. }
  32. ], async (err) => {
  33. if (err !== true) {
  34. err = await utils.getError(err);
  35. logger.info("OWNER_REQUIRED", `User failed to pass owner required check for station "${stationId}". "${err}"`);
  36. return cb({status: 'failure', message: err});
  37. }
  38. logger.info("OWNER_REQUIRED", `User "${session.userId}" passed owner required check for station "${stationId}"`, false);
  39. next.apply(null, args);
  40. });
  41. }
  42. };