adminRequired.js 1.4 KB

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