如何在Sequelize中进行身份验证?

时间:2016-03-31 04:45:29

标签: node.js authentication express sequelize.js

我有一条路由,我必须通过获取sequelize来搜索请求正文中的现有用户名和密码的任何实例,以便知道我是否可以继续验证用户。我不知道如何做到这一点(在Sequelize中搜索和检查实例),因为Sequelize的文档很新。我通过阅读http://docs.sequelizejs.com/en/latest/api/model/来尝试User.findOne,例如

db.User.findOne({
    where: { password: req.password, username: req.username }

}).then(function(address) {
    if(address.User !== null) {
        console.log('User name: '+address.User.name);
    } else {
        console.log('User name: NO USER');
    }

但不确定确切的语法/方法。我有这样的事情:

app.post('/authenticate', function (req, res) {
  //TODO validate req.body.username and req.body.password
  //if is invalid, return 401


  if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
    res.status(401).send('Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: 'john@doe.com',
    id: 123
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, secret, { expiresIn: 18000 });

  res.json({ token: token });
});

app.get('/api/restricted', function (req, res) {
  console.log('user ' + req.user.email + ' is calling /api/restricted');
  res.json({
    name: 'foo'
  });
});

0 个答案:

没有答案