Using PassportJS, how does one pass additional form fields to the local authentication strategy?

后端 未结 2 1782
情深已故
情深已故 2020-11-29 16:30

I\'m using passportJS and I\'m wanting to supply more than just req.body.username and req.body.password to my authentication strategy (passport-loc

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 16:59

    In most common cases we need to provide 2 options for login

    • with email
    • with mobile

    Its simple , we can take common filed username and query $or by two options , i posted following snippets,if some one have have same question .

    We can also use 'passReqToCallback' is best option too , thanks @Jared Hanson

    passport.use(new LocalStrategy({
        usernameField: 'username', passReqToCallback: true
    }, async (req, username, password, done) => {
        try {
            //find user with email or mobile
            const user = await Users.findOne({ $or: [{ email: username }, { mobile: username }] });
    
            //if not handle it
            if (!user) {
                return done(null, {
                    status: false,
                    message: "That e-mail address or mobile doesn't have an associated user account. Are you sure you've registered?"
                });
            }
    
            //match password
            const isMatch = await user.isValidPassword(password);
            debugger
            if (!isMatch) {
                return done(null, {
                    status: false,
                    message: "Invalid username and password."
                })
            }
    
            //otherwise return user
            done(null, {
                status: true,
                data: user
            });
        } catch (error) {
            done(error, {
                status: false,
                message: error
            });
        }
    }));
    

提交回复
热议问题