从点击的电子邮件中接收令牌

时间:2018-05-04 09:47:25

标签: html mysql node.js express nodemailer

我正在与一些团队成员合作开发一个Web应用程序,我的任务是密码恢复。我们使用mysql和node.js作为后端和API层。使用以下npm包:nodemailer,mysql,express,body-parser和bcrypt。

手头的问题是我实际上并不知道如何使用bcrypt令牌创建链接,然后重新获取令牌并解释它,然后将其发送到带有用户数据的html页面/表单。

我还没有测试过代码,但有些输入会很棒:

var urlencodedParser = bodyParser.urlencoded({
  extended: true
});
app.use(bodyParser.urlencoded({
  extended: true
}));

var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

var db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  //Change DB name to the one you make.
  database: 'projectracetrack'
});

//User clicks on link in email. 
app.get('/recover/:token', function(req, res) {
  //here
});

app.post('/forget', urlencodedParser, function(req, res) {
  let sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
  db.connect(function(err) {
    if (err) throw err;
    db.query(sql, [req.body.email.toString()], function(err, result) {
      if (err) throw err;
      console.log(result);
      //Comparing email to database 
      if (result.email.toLowerCase() !== req.email.toLowerCase()) {
        //send reply that email 
        return res.send("Your email does not exist in the database, please use the registration page.");
      } else {
        var token;
        //encripting the token
        bcrypt.hash(result.username, saltRounds, function(err, hash) {
          if (err) throw err;
          token = hash;
          sql = "INSERT INTO racers (RecoveryToken, RecoverTimeOut) WHERE email = " + result.email + " VALUES ? LIMIT 1";
          //inserting the token and data to the database                                                         HERE!!
          // 1 hour
          var data = [
            [token,
              Date.now() + 3600000 // 1 hour 
            ]
          ];
          db.query(sql, [data], function(err) {
            if (err) throw err;
          });

          var mailOptions = {
            from: 'youremail@gmail.com',
            to: result.email,
            subject: 'Project Racetrack Password Recovery',
            text: 'Dear ' + result.username + '\n\n\
                                This is a confermation that you would like to recover your password please click on the link:' +
              'http://' + req.headers.host + '/recover/' + token + '\n\n\
                                If this has not been requested by you please contact our customer suppport\n\n\
                                Kind Regards\n\
                                Team'
          };

          transporter.sendMail(mailOptions, function(error, info) {
            if (error) {
              console.log(error);
            } else {
              console.log('Email sent: ' + info.response);
            }
          });
        });
      }
    });
  });
});

0 个答案:

没有答案