adminRequired.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import async from "async";
  2. import moduleManager from "../../../index";
  3. const DBModule = moduleManager.modules.db;
  4. const CacheModule = moduleManager.modules.cache;
  5. const UtilsModule = moduleManager.modules.utils;
  6. export default destination =>
  7. async function adminRequired(session, ...args) {
  8. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  9. const cb = args[args.length - 1];
  10. async.waterfall(
  11. [
  12. next => {
  13. CacheModule.runJob(
  14. "HGET",
  15. {
  16. table: "sessions",
  17. key: session.sessionId
  18. },
  19. this
  20. )
  21. .then(session => {
  22. next(null, session);
  23. })
  24. .catch(next);
  25. },
  26. (session, next) => {
  27. if (!session || !session.userId) return next("Login required.");
  28. return userModel.findOne({ _id: session.userId }, next);
  29. },
  30. (user, next) => {
  31. if (!user) return next("Login required.");
  32. if (user.role !== "admin") return next("Insufficient permissions.");
  33. return next();
  34. }
  35. ],
  36. async err => {
  37. if (err) {
  38. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  39. this.log("INFO", "ADMIN_REQUIRED", `User failed to pass admin required check. "${err}"`);
  40. return cb({ status: "failure", message: err });
  41. }
  42. this.log("INFO", "ADMIN_REQUIRED", `User "${session.userId}" passed admin required check.`, false);
  43. return destination.apply(this, [session].concat(args));
  44. }
  45. );
  46. };