简体   繁体   中英

Express Passport failureRedirect not working

I set up the local strategy but failureRedirect does not seem to work properly. When a connection error occurs (for instance the URL of the database is wrong), the response is an error 500 instead of redirect to the specified route.

This is my route code:

router.route('/login')
    .post(passport.authenticate('local', {
        failureRedirect: '/' 
    }), function(req, res){ 
        console.log('user logged in');
        res.redirect('../console');
    });

And here is my implementation for the local strategy:

module.exports = function(){
    passport.use(new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'
    },
        function(email, password, done){
            pg.defaults.ssl = true;
            pg.connect(process.env.DATABASE_URL, function(err, client) {
                if (err){
                    console.log('Connection issue when logging in: ' + JSON.stringify(err));
                    done('Error with database,', null); // this is the problem area!!!
                } else {
                    client
                        .query(`SELECT * FROM agent WHERE email='${email}'`, function(err, result) {
                            if(err || result.rows.length === 0 ) {
                                console.log('Query issue when loggin in: '+ JSON.stringify(err));
                                done(null, false);
                            } else {
                                var user = result;
                                console.log('ready to log user in');
                                done(null, user);
                            }
                        });
                }
            });
        }
    ));
};

I was thinking maybe my use of done() callback function is wrong but I followed the documentation. Thanks for your help.

The issue I had was that I was throwing an err if the user didn't exist -- done('some error', null); and that doesn't seem to be what Passport expects.

It supports the notion of a falsy user in done as another sign of failure. So the appropriate signature would be done(null, null) if you don't find a user.

so when there is a database error you put 'Error with database' as the error. you should put null.

You have to

throw new Error('hello world')

to trigger failure Redirect, you may also try

https://docs.nodejitsu.com/articles/errors/what-is-try-catch/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM