adminRequired.js 1.2 KB

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