简体   繁体   中英

Passport.js not calling LocalStrategy if fields are empty

I'm having a problem where if I try to login with no username or password my passport.use function isn't being called at all.

Below is my express post route that runs passport.authenticate .

app.post('/login', passport.authenticate('local-login', {
        failureRedirect: '/login', // redirect back to the login page if there is an error
        failureFlash: true // allow flash messages
    })

And below is my passport.use that should print GOT HERE whenever there is a post request to /login .

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
        console.log("GOT HERE");

This works fine if email and password have some type of value. But I would like this function to be called even if there is no value for email and password so that I can do custom error handling.

How can I achieve this?

You could add middleware befure authentication strategy being called. Something like this:

app.post('/login', function(req, res, next) {
    // do custom error handling
  }, passport.authenticate('local-login', {
        failureRedirect: '/login', // redirect back to the login page if there is an error
        failureFlash: true // allow flash messages
})

And in this middleware you could do some custom error handling

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