我很难将res var传递给护照认证中间件模块。
遵循护照指南:http://passportjs.org/guide/authenticate/
它声明要将res传递给authenticate方法以启用自定义重定向,您需要将passport.authenticate
放入app.post回调中。
由于我希望将所有业务保留在我的护照文件中,而不是在路由中,我想出了以下内容:
路线:
// process the login form
app.post('/login', function( req, res, next ){
console.log(1);
passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
});
});
模块:
....
// expose this function to our app using module.exports
module.exports = function(passport) {
....
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
console.log(2)
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err){
return done(err);
}
console.log(3)
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
if( !user.local.authenticated )
return res.redirect( '/resend-activation/' + user.local.email );
// all is well, return successful user
return done(null, user);
});
}));
然而,从帖子到此路线的日志是:
server-0 (out): 1
server-0 (out): POST /login 200 120002ms
server-0 (out): 2
server-0 (out): POST /login 200 120090ms
多数民众赞成。它从未到达console.log(3);
我不确定我在这里做错了什么,是因为app.post回调中的req
覆盖了passport.auth中的req
?
非常感谢任何帮助,谢谢。
约翰
答案 0 :(得分:1)
首先,我错过了括号以实际运行auth功能,所以我更新到路线:
app.post('/login', function( req, res, next ){
passport.authenticate('local-login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
})(req, res, next);
});
然后在auth护照中我打印了所有传递的参数,并注意到res在req中。因此,执行自定义重定向的方式如下:req.res.redirect...
:
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true },
function(req, email, password, done) {
console.log( arguments.length );
console.log( arguments );
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);
console.log(123);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
if( !user.local.authenticated )
return req.res.redirect( '/resend-activation/' + user.local.email );
// all is well, return successful user
return done(null, user);
});
}));
我不知道这是否是一种正确的做事方式..?