loginSometimesRequired.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import async from "async";
  2. import config from "config";
  3. // eslint-disable-next-line
  4. import moduleManager from "../../index";
  5. const CacheModule = moduleManager.modules.cache;
  6. const UtilsModule = moduleManager.modules.utils;
  7. // This is for actions that are only restricted to logged-in users if restrictToUsers config option is true
  8. export default destination =>
  9. function loginSometimesRequired(session, ...args) {
  10. const cb = args[args.length - 1];
  11. async.waterfall(
  12. [
  13. next => {
  14. if (!config.get("restrictToUsers")) next(true);
  15. else if (!session || !session.sessionId) next("Login required.");
  16. else next();
  17. },
  18. next => {
  19. CacheModule.runJob(
  20. "HGET",
  21. {
  22. table: "sessions",
  23. key: session.sessionId
  24. },
  25. this
  26. )
  27. .then(session => next(null, session))
  28. .catch(next);
  29. },
  30. (session, next) => {
  31. if (!session || !session.userId) return next("Login required.");
  32. return next();
  33. }
  34. ],
  35. async err => {
  36. if (err && err !== true) {
  37. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  38. this.log("LOGIN_SOMETIMES_REQUIRED", `User failed to pass login required check.`);
  39. return cb({ status: "error", message: err });
  40. }
  41. this.log("LOGIN_SOMETIMES_REQUIRED", `User "${session.userId}" passed login required check.`);
  42. return destination.apply(this, [session].concat(args));
  43. }
  44. );
  45. };