adminRequired.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. module.exports = function(next) {
  8. return function(session) {
  9. let args = [];
  10. for (let prop in arguments) args.push(arguments[prop]);
  11. let cb = args[args.length - 1];
  12. async.waterfall([
  13. (next) => {
  14. cache.hget('sessions', session.sessionId, next);
  15. },
  16. (session, next) => {
  17. if (!session || !session.userId) return next('Login required.');
  18. this.session = session;
  19. db.models.user.findOne({_id: session.userId}, next);
  20. },
  21. (user, next) => {
  22. if (!user) return next('Login required.');
  23. if (user.role !== 'admin') return next('Insufficient permissions.');
  24. next();
  25. }
  26. ], async (err) => {
  27. if (err) {
  28. err = await utils.getError(err);
  29. logger.info("ADMIN_REQUIRED", `User failed to pass admin required check. "${err}"`);
  30. return cb({status: 'failure', message: err});
  31. }
  32. logger.info("ADMIN_REQUIRED", `User "${session.userId}" passed admin required check.`, false);
  33. next.apply(null, args);
  34. });
  35. }
  36. };