我想做的是将对sailsjs应用程序的express-brute实现为策略。

因此,我注册了一个政策bruteForce。

我的bruteForce.js文件包含:

const ExpressBrute = require('express-brute'),
  moment = require('moment'),
  SequelizeStore = require('express-brute-sequelize'),
  Sequelize = require('sequelize');

const failCallback = (req, res, next, nextValidRequestDate) =>  {
  res.status(429).json({
    message: 'You\'ve made too many failed attempts in a short period of time, please try again '+moment(nextValidRequestDate).fromNow(),
    nextValidRequestDate,
    tryAgainIn: moment(nextValidRequestDate).diff(moment)
  })
}

const handleStoreError = (error) => {
  sails.log.error(error);
  throw {
    message: error.message,
    parent: error.parent
  };
}

const store = new ExpressBrute.MemoryStore();

const bruteForceOptions = {
  freeRetries: 3,
  minWait: 1000*60,
  maxWait: 1000*60*15,
  failCallback,
  handleStoreError
}

const bruteforce = new ExpressBrute(store, bruteForceOptions)

module.exports = async function (req, res, next) {
  return bruteforce.prevent(req, res, next)
};


到目前为止,这是可行的,但是当我尝试设置另一个商店驱动程序时,我现在选择了Sequelize驱动程序。

因此,我添加了:

const sequelize = new Sequelize('table', 'root', 'secret', {
  host: '127.0.0.1',
  dialect: 'mysql',
  operatorsAliases: false,
  logging: sails.log.debug
});

const getBruteforce = async function(){
  new SequelizeStore(sequelize, 'bruteStore', {}, function(store) {
    console.log(store)
    return new ExpressBrute(store, bruteForceOptions)
  });
}


我的新政策职能是:

module.exports = async function (req, res, next) {
  const bruteforce = await getBruteforce()
  return bruteforce.prevent(req, res, next)
};


但是在这里,我总是得到未定义的错误bruteforce,然后在新SequelizeStore的回调中调用console.log。

我不知道该如何解决。

有人知道吗?

最佳答案

因为您的getBruteforce()函数实际上不返回任何内容。

const getBruteforce = async function(){
  new SequelizeStore(sequelize, 'bruteStore', {}, function(store) {
    console.log(store)
    // Below returns from the callback, **not** the async function
    return new ExpressBrute(store, bruteForceOptions)
  });
}


改为这样做:

const getBruteforce = function(){
  return new Promise(resolve => {
    new SequelizeStore(sequelize, 'bruteStore', {}, function(store) {
      console.log(store)
      // Fulfill the returned promise
      resolve(new ExpressBrute(store, bruteForceOptions))
    });
  });
}


我建议您阅读有关如何return values from async functions的内容。

08-08 08:00