我正在用节点js编写电子邮件确认代码。我采用的以下方法
setTimeout()
methon等待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)
}
答案 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索引将在到期时间后自动删除文档
答案 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);
})
这将为您提供一个 OTP,您可以将其保存在您的服务器中,您可以将其用于将来的身份验证,例如当用户输入 OTP 时从前端向您的服务器发送请求