Passport + Node.js / Automatic login after adding user

后端 未结 3 2338
一生所求
一生所求 2020-12-24 11:56

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 adde

相关标签:
3条回答
  • 2020-12-24 12:08

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

    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

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

    0 讨论(0)
  • 2020-12-24 12:23

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

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

    Modifying krasu's code:

    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.

    0 讨论(0)
  • 2020-12-24 12:26

    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);
        });
    });
    
    0 讨论(0)
提交回复
热议问题