如何仅通过电子邮件使用passport.js对用户进行身份验证?

时间:2018-08-11 16:02:28

标签: node.js authentication passport.js

我正在尝试使用特定流程对用户进行身份验证。

用户将输入用于注册的电子邮件,用户将立即登录到该帐户,我将发送电子邮件确认链接,用户可以使用该链接更新密码并登录到该帐户。

但是我被卡住了

我很困惑如何仅通过电子邮件注册和登录

route.js

  app.post('/get_started', (req, res) => {
         let {email} = req.body;
         let isEmail = emailValidator(email);
         // i will save the user email and try to login
         if(isEmail){
             passport.authenticate('local',{ successRedirect: '/dashboard', failureRedirect: '/' })
         }
    })

Startegy.js

import LocalStrategy from 'passport-local'

export default passport => {

    passport.use('local',new LocalStrategy( (email, done) => {

        console.log(email,'Inside Passport')

    }));

}

2 个答案:

答案 0 :(得分:0)

  

在我演示如何实现您的要求之前,我会   强烈建议不要重新设计登录和注册   这些系统已经存在了很长时间了   在这种情况下,最好坚持传统的做法。

话虽如此

要实现用户仅使用电子邮件即可登录的功能,可以使用passport-custom 模块,该模块使您可以编写自己的逻辑来登录用户。

注册策略:

passport.use(
    "my-custom-strategy",
    new CustomStrategy(function(req, callback) {
        const email = req.body.email;
        User.exists(email).then(exists => {
            const info = {};
            if (exists) {
                // user has already entered password,
                // redirect to some page and where user can enter the password
                info.passwordRequired = true;
            } else {
                // user has not entered password,
                // add the user to db
                // send the link and let them login for now
                info.sendEmailLink = true;
            }
            return callback(null, { email }, info);
        });
        callback(null, user);
    })
);

我假设User.exists(email)方法可用,它将返回将 根据电子邮件是否存在,解析为truefalseinfo对象将在控制器中用于实现实际的逻辑。

app.use("/get_started", (req, res, next) => {
    let { email } = req.body;
    let isEmail = emailValidator(email);
    // i will save the user email and try to login
    if (isEmail) {
        passport.authenticate("my-custom-strategy", (err, user, info) => {
            if (info.passwordRequired) {
                // you can use custom cookie to set the user.email
                // and access it later to fully authenticate the user
                // using the email and password
                res.redirect("/enter_password");
            } else if (info.sendEmailLink) {
                // logic to send the email
                // once the email sent, redirect to dashboard
                res.redirect("/dashboard");
            }
        })(req, res, next);
    }
});

答案 1 :(得分:0)

下面是另外一个使用sequelize和bcrypt的示例:

route.js:

make

Strategy.js:

app.post('/get_started', passport.authenticate('local'), (req, res) => { 
    // Do stuff after successful login here
}