javascript - Node.js Passport 不调用下一个函数

标签 javascript node.js passport.js

我正在使用 Node 构建一个应用程序,该应用程序使用 Passport.js 来处理使用本地数据库的用户登录。

因此,当用户转到/profile 时,我有以下代码被调用。成功登录后,用户将被重定向到/profile。根据 morgan 的说法,这确实发生了。

app.get('/profile', passport.authenticate('local-login', { session : false, failureRedirect : '/login' }), function(req, res) {
    console.log("testnow");
    res.render('profile.ejs', {
        user : req.user // get the user out of session and pass to template
    });
});

我的本​​地登录代码如下。

passport.use('local-login', new LocalStrategy({
    // by default, local strategy uses username and password, we will override with email
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) { // callback with email and password from our form
    // find a user whose email is the same as the forms email
    // 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);

        // if no user is found, return the message
        if (!user)
            return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

        // if the user is found but the password is wrong
        if (!user.validPassword(password))
            return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

        // all is well, return successful user
        console.log("testdone");
        return done(null, user);
    });
}));

测试代码时,我登录并立即重定向到配置文件。控制台打印“testdone”,它位于我的本地登录代码中,但没有按预期打印“testnow”。这意味着我的/profile get 方法中的第二个函数似乎永远不会被调用,即使本地登录正在调用下一个函数。

因此,从最终用户的 Angular 来看,您登录(在幕后,您被重定向到/profile 以进行分割部分),而/profile 将您重定向回/login。

关于如何解决此问题的任何想法,以便我的/profile get 方法中的第二个函数实际上被调用?

提前非常感谢。我也很乐意提供任何其他信息来帮助解决这个问题。

最佳答案

passport.authenticate() 用于处理实际的身份验证;换句话说,获取登录凭据并将其传递给策略。如果请求已通过身份验证,则它并不意味着传递请求,而这正是您尝试使用它的目的。

相反,您想使用类似 connect-ensure-login 的内容保护用户必须登录的路由。

另请参阅this Passport example project .

关于javascript - Node.js Passport 不调用下一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402929/

相关文章:

node.js - 在 Node js + Express + Passport + MongoDB 中更新用户记录

javascript - 如何通过 jQuery 检查 div 类是否存在三次或更多次?

Javascript 继承 : How prototype chain works between native prototypes

mysql - Node.js 中的加密

node.js - Passport.js 无法序列化用户

node.js - Passport-Azure-Ad 似乎异步运行

javascript - 分组交替行颜色与变化

javascript - 在 CRM 2011 中过滤子选项列表

javascript - 解析大型 JSON 失败

javascript - browserify错误: http. createServer不是一个函数