adminRequired.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const async = require("async");
  2. const db = require("../../db");
  3. const cache = require("../../cache");
  4. const utils = require("../../utils");
  5. module.exports = function(next) {
  6. return async function(session) {
  7. const userModel = await db.runJob("GET_MODEL", { modelName: "user" });
  8. let args = [];
  9. for (let prop in arguments) args.push(arguments[prop]);
  10. let cb = args[args.length - 1];
  11. async.waterfall(
  12. [
  13. (next) => {
  14. cache
  15. .runJob("HGET", {
  16. table: "sessions",
  17. key: session.sessionId,
  18. })
  19. .then((session) => next(null, session))
  20. .catch(next);
  21. },
  22. (session, next) => {
  23. if (!session || !session.userId)
  24. return next("Login required.");
  25. this.session = session;
  26. userModel.findOne({ _id: session.userId }, next);
  27. },
  28. (user, next) => {
  29. if (!user) return next("Login required.");
  30. if (user.role !== "admin")
  31. return next("Insufficient permissions.");
  32. next();
  33. },
  34. ],
  35. async (err) => {
  36. if (err) {
  37. err = await utils.runJob("GET_ERROR", { error: err });
  38. console.log(
  39. "INFO",
  40. "ADMIN_REQUIRED",
  41. `User failed to pass admin required check. "${err}"`
  42. );
  43. return cb({ status: "failure", message: err });
  44. }
  45. console.log(
  46. "INFO",
  47. "ADMIN_REQUIRED",
  48. `User "${session.userId}" passed admin required check.`,
  49. false
  50. );
  51. next.apply(null, args);
  52. }
  53. );
  54. };
  55. };