节点js中的电子邮件确认

时间:2020-08-02 21:35:35

标签: javascript node.js mongoose

我正在用节点js编写电子邮件确认代码。我采用的以下方法

  • 生成5位数的随机数
  • 将用户数据(电子邮件,密码等)以及5位随机数保存在数据库(mongodb)中
  • 在电子邮件地址上发送随机数。
  • 应用setTimeout() methon等待20分钟以确认邮件地址
  • 如果用户验证地址为20分钟,则可以,否则可以从数据库中删除用户数据。

,但是此代码继续等待20分钟,直到setTimeout周期结束。有什么方法可以应用这种策略而无需等待20分钟?我知道这很简单,但我无法破解。以下是代码...

const emailCode = Math.floor(Math.random()*90000)+10000;
    try
    {
        const user = new User({...req.body, emailCode});
        req.user = user;
        await user.save()
    }
    catch(err)
    {
        if(err.keyPattern)
        {
            res.status(409).send({err: "User Already Exists"})
        }
        else if(err.errors.email)
        {
            res.status(400).send({err: err.errors.email.message})
        }
        else if(err.errors.password)
        {
            res.status(400).send({err: err.errors.password.message})
        }
        res.status(400).send(err);
    }
    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '',
            pass: ''
        }
    });
    const mailOptions = {
        from: '',
        to: req.body.email,
        subject: "Confirm Your Email Address",
        text: "Use the following 5 digit code to confirm your email address \n"+emailCode.toString()
    };
    try
    {
        const mail = await transporter.sendMail(mailOptions);
        console.log("here");
        await new Promise(resolve =>
        {
            setTimeout(resolve, 10000)
        })
        console.log("there");
        console.log(req.user.verify)
        if(!req.user.verify)
        {
            req.user.remove();
        }
    }
    catch(err)
    {
        res.send(err)
    }

3 个答案:

答案 0 :(得分:1)

在数据库中保存确认代码的到期时间。然后,当您验证代码时,还请验证代码尚未过期。

答案 1 :(得分:1)

我们可以在MongoDB中使用TTL索引来完成这项工作,假设有一个isVerified,默认情况下为false,并且在用户验证电子邮件时设置为true

因此我们可以添加TTL索引,例如

db.users.createIndex( {createdAt: 1}, {
    expireAfterSeconds: 20*60, // 20 minutes
    partialFilterExpression: {
        isVerified: false
    }
});

此处createdAt是注册用户的日期时间。

如果isVerified仍然为假,TTL索引将在到期时间后自动删除文档

供参考 https://docs.mongodb.com/manual/core/index-ttl/

答案 2 :(得分:0)

你也可以试试这个方法

通过使用 NPM 包(两步验证)

在你的服务器 index.js 中使用这个包并为它创建一个路由,直接传入变量,你可以做剩下的,

在您的应用程序中,从表单中获取数据并将其传递给您的服务器,然后传递给包,它会返回一个 OTP 供您使用,

Kindly check the full procedures with the example here

用法

const {Auth} = require('two-step-auth');

async function login(emailId){
    const res = await Auth(emailId);
    // You can follw the above approach, But we recommend you to follow the one below, as the mails will be treated as important
    const res = await Auth(emailId, "Company Name");
    console.log(res);
    console.log(res.mail);
    console.log(res.OTP);
    console.log(res.success);
}

const app = express();
app.get('./auth/mailId/CompanyName', async(req, res)=>{
    const {emailId} = req.params;
    const data  = login(emailId);
})

输出

enter image description here 这将为您提供一个 OTP,您可以将其保存在您的服务器中,您可以将其用于将来的身份验证,例如当用户输入 OTP 时从前端向您的服务器发送请求