adminRequired.js 1.1 KB

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