我正在尝试在
Node.js
中编写一个使用 passport-facebook
身份验证策略的 Web 应用程序。默认情况下,示例中提供的机制通过将用户重定向到 Facebook API
来工作,用户可以在其中输入用户名和密码进行登录。 Facebook 验证用户后,会将令牌传递回我的应用程序中的回调 URL。
现在这些东西适用于我的应用程序。我可以毫无问题地使用 Facebook 登录。但我希望在我尝试登录时将一个额外的字段传递到服务器。
基本上我的计划是在我的主页中添加一个
TextField
和一个Login Button
。登录成功后,执行回调函数时,我想从这个回调中捕获TextField
的值。有什么办法可以做到这一点吗?非常感谢任何帮助。
这是我的 HTML 页面的正文
<body>
<div class="container">
<div class="jumbotron text-center">
<p>Login or Register with:</p>
<a href="/auth/facebook" class="btn btn-primary"><span class="fa fa-facebook"></span> Facebook</a>
</div>
</div>
</body>
这是我的
Node.js
代码:
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', passport.authenticate('facebook', {
successRedirect : '/dashboard',
failureRedirect : '/'
}));
app.get('/dashboard', isLoggedIn, function(req, res){
res.render('dashboard.ejs', {
user : {
name : req.user.facebook.name,
profilePic : req.user.facebook.profilePic
}
});
});
基本上我只想在
TextField
按钮之前添加一个额外的 LogIn
。从 /dashboard
路线中,我想获取该 TextField
的值。所以我的 /dashboard
代码看起来像这样:
app.get('/dashboard', isLoggedIn, function(req, res){
res.render('dashboard.ejs', {
user : {
role: VALUE_FROM_TEXT_FIELD,
name : req.user.facebook.name,
profilePic : req.user.facebook.profilePic
}
});
});
所以我有一个双重问题:
TextField
值。它应该在 Form
内还是什么?TextField
路线内 /dashboard
的值?您是否考虑过使用自定义回调而不是标准 Passport.js 回调?
“本地”策略的一个例子是:
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
您应该能够在请求中传入附加值并在回调中处理它。
编辑:对于您的特定场景,您可能正在查看类似于此的内容...
app.get('/auth/facebook/callback', function (req, res, next) {
passport.authenticate('facebook', function (err, user, info) {
if (err) {
return next(err);
// let the next route handler do its thing...
// or you can handle the error yourself within this
// callback.
}
// if the user returns as nothing (doesn't exist) then redirect
if (!user) {
// this takes the place of failureRedirect
return res.redirect('/');
}
req.logIn(user, function (err) {
if (err) {
return next(err); // again - on error, 'next' depending on your requirement.
}
// this takes the place of successRedirect
return res.redirect('/dashboard');
});
})(req, res, next);
});
希望这能澄清:)
我所做的是传递一个自定义函数而不是使用 sucessRedirect 并将其传递给变量 need。就我而言,它是 req.session.backurl,用于将它们发送回需要经过身份验证才能访问的页面。
users.get('/auth/facebook/callback',
//req.session.backURL||
passport.authenticate('facebook', { failureRedirect: '/login' }),function(req,res){
res.redirect(req.session.backURL||'/'); //custom function used instead of sucessRedirect
});