在调用passport.js身份验证功能之前,是否可以验证google recaptcha是否成功?
我在选择一个或另一个之间遇到困难,因为它们都使用异步回调来验证,而我不能在彼此之间接下来。
function verifyRecaptcha(key, rq, rs, pa, callback) {
https.get('https://www.google.com/recaptcha/api/siteverify?secret=' + SECRET + '&response=' + key, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk.toString();
});
res.on('end', function () {
try {
var parsedData = JSON.parse(data);
// return true;
callback(parsedData.success, rq, rs, pa);
} catch (e) {
// return false;
callback(false, rq, rs, pa);
}
});
});
}
app.post('/auth/signin', can_access.if_not_logged_in(), passport.setupLocalStrategy(),
function (req, res) {
console.log('HERE');
verifyRecaptcha(req.body['g-recaptcha-response'], function (success) {
if (success) {
// find a way to signal captcha succeeded.
return true;
} else {
res.end('Captcha failed, sorry.');
// TODO: take them back to the previous page
// and for the love of everyone, restore their inputs
return false;
}
});
},
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: 'auth/signin',
failureFlash: true
}));
我想在验证码成功后进行身份验证
答案 0 :(得分:3)
Express中间件或路由处理程序的工作方式是,只要前一个调用next()
所以你只需要从你的验证码验证中间件中调用next()
,这样你下一步的passport.authenticate
中间件就可以被执行了。
此外,如果你调用next(err)
(即传递一个错误),它将跳过所有中间件并直接进入下一个具有4参数签名(err, req, res, next)
的中间件,这通常是主要的错误处理程序放置在路由/中间件的末尾或附近。
所以,只需尝试将代码更改为:
app.post('/auth/signin', can_access.if_not_logged_in(), passport.setupLocalStrategy(),
function (req, res, next) { // <<-- 1. have next passed here
console.log('HERE');
verifyRecaptcha(req.body['g-recaptcha-response'], function (success) {
if (success) {
// find a way to signal captcha succeeded.
return next(); // <<-- 2. call next();
} else {
res.end('Captcha failed, sorry.');
// TODO: take them back to the previous page
// and for the love of everyone, restore their inputs
return false;
}
});
},
// this will only be invoked if next() was called from previous middleware
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: 'auth/signin',
failureFlash: true
}));