节点-添加新用户时将凭据自动保存到file.htpasswd中

时间:2018-11-29 18:04:08

标签: node.js mongodb express http-auth

我有一个mongo数据库,正在阅读本文:https://www.sitepoint.com/build-simple-beginner-app-node-bootstrap-mongodb/我已经看到,谢谢http-auth可以提供保护。 现在,当我将记录保存到db中时:

router.post('/login', function (req, res) {
  console.log(req.body);
  const registration = new Registration(req.body);
  registration.save()
    .then(() => { 
        res.send('Thank you for your registration!' + req.body.name);
        });
      })
    .catch(() => { res.send('Sorry! Something went wrong.'); });      
});

但是我找不到任何允许直接在文件.htpasswd内部写入的内容。

我的意图是自动为所有注册用户提供读取权限。为此,已经以这种方式更新了代码

router.post('/login', function (req, res) {
  console.log(req.body);
  const registration = new Registration(req.body);
  registration.save()
    .then(() => { 
        res.send('Thank you for your registration!' + req.body.name); 
        var crypted = crypto.createHash('md5').update(req.body.name).digest("hex");
        fs.appendFile(path.join(__dirname, '../users.htpasswd'), '\n' +req.body.name+':'+ crypted, function (err) {
          if (err) throw err;
          console.log('Saved!');    
        });
      })
    .catch(() => { res.send('Sorry! Something went wrong.'); });      
});

但是当我尝试访问特定页面时:

router.get('/registrations', auth.connect(basic), (req, res) => {
    Registration.find()
      .then((registrations) => {  res.send(registrations)
        })
      .catch(() => { res.send('Sorry! Something went wrong.'); });
});

系统给我错误。

0 个答案:

没有答案