gpt4 book ai didi

javascript - 具有异步函数的 Sailsjs 策略

转载 作者:行者123 更新时间:2023-12-03 01:40:09 24 4
gpt4 key购买 nike

我尝试做的是将express-brute 作为策略实现到 sailsjs 应用程序中。

因此我注册了一个强力策略。

我的 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 undefined 并且随后会调用 new 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 .

关于javascript - 具有异步函数的 Sailsjs 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50881947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com