Passport + Node.js / 添加用户后自动登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16817800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:38:39  来源:igfitidea点击:

Passport + Node.js / Automatic login after adding user

javascriptnode.jspassport.js

提问by user937284

I am using passport for authentication and session handling. Everything works fine so far. I implemented a "Sign in" form to add new users to the app. After a user is added I would like to log him/her in automatically.

我正在使用护照进行身份验证和会话处理。到目前为止一切正常。我实现了一个“登录”表单来向应用程序添加新用户。添加用户后,我想自动登录他/她。

What is the best way to achieve this - should I redirect to "/login" with the user credentials or is there another/better way(call serializeUser) to do that?

实现这一目标的最佳方法是什么 - 我应该使用用户凭据重定向到“/login”还是有另一种/更好的方法(调用 serializeUser)来做到这一点?

So far I think I did not really understand the way the "done" function (in serializeUser and LocalStrategy) is working or what it is doing ...

到目前为止,我认为我并没有真正理解“完成”功能(在 serializeUser 和 LocalStrategy 中)的工作方式或它在做什么......

Here is my code:

这是我的代码:

passport.serializeUser(function(user, done) {
    done(null, user._id);
});
passport.deserializeUser(function(id, done) {
    authProvider.findUserById('users', id, function (err, user) {
        done(err, user);
    });
});

passport.use(new LocalStrategy( function(email, password, done) {
    authProvider.getUserByEmail('users', email, function(error, user){
        if(error) { return done(error); }
        if (!user) { return done(null, false, { message: 'Unknown user ' + email });}   
        if (user.password != password) { return done(null, false);}
        return done(null, user);
        });
    }
));

app.post('/login', 
    passport.authenticate('local', { failureRedirect: '/login'}),
    function(req, res) { res.redirect('/');});

app.post('/sign', function(req, res){
    authProvider.saveUser(...do stuff), function(error, user){
        if(error){
            res.redirect('/sign');
        } else {
            res.redirect('/');
        }
    });
});

Does someone know how to do this?

有人知道怎么做吗?

采纳答案by krasu

Please use code from the @Weston answer bellow, because it's more universal and straightforward

请使用@Weston 回答中的代码,因为它更通用和直接

Should look something like this

应该看起来像这样

app.post('/sign', function(req, res){
    authProvider.saveUser(...do stuff), function(error, user){
        if(error){
            res.redirect('/sign');
        } else {
            passport.authenticate('local')(req, res, function () {
                res.redirect('/account');
            })
        }
    });
});         

I don't sure about name of strategy, but by default LocalStrategy should provide 'local' name

我不确定策略的名称,但默认情况下 LocalStrategy 应提供“本地”名称

http://passportjs.org/guide/authenticate/

http://passportjs.org/guide/authenticate/

回答by Weston

Based on the Passport Guidereq.login()is intended for this exact purpose.

基于护照指南req.login()正是为此目的而设计的。

This function is primarily used when users sign up, during which req.login()can be invoked to automatically log in the newly registered user.

该功能主要在用户注册时使用,在此期间req.login()可以调用新注册的用户自动登录。

Modifying krasu's code:

修改 krasu 的代码:

app.post('/sign', function(req, res){
    authProvider.saveUser(...do stuff), function(error, user){
        if ( error ){
            res.redirect('/sign');
        } else {
            req.login(user, function (err) {
                if ( ! err ){
                    res.redirect('/account');
                } else {
                    //handle error
                }
            })
        }
    });
});

The potential error from the login()callback would come from your serializeUser()function.

login()回调的潜在错误将来自您的serializeUser()函数。

回答by alditis

Try with:

尝试:

app.post('/sign', function(req, res){
    authProvider.saveUser(...do stuff), function(error, user){
        passport.authenticate('local', (err, user) => {
            req.logIn(user, (errLogIn) => {
                if (errLogIn) {
                    return next(errLogIn);
                }
                return res.redirect('/account');
            });
        })(req, res, next);
    });
});