标题已经发送 - Koa和bcrypt

时间:2017-09-19 08:26:46

标签: javascript bcrypt koa

我正在尝试为我的应用创建登录端点。我已经使用bcrypt在创建用户时散列密码。登录时,我想将哈希值与字符串密码进行比较。但是,当我使用邮递员登录时,我收到404错误“标题已被发送”。我查看了koa git论坛using crypto with koa 2,并且接受的答案建议将函数包装在异步等待中,这就是我所做的。我无法弄清楚为什么节点一直向我发送'标题已经发送'错误。

var User = db.get('users');
var Review = db.get('reviews');

//this create user function works as intended...

module.exports.create = async (ctx, next) => {
  if ('POST' != ctx.method) return await next();

  let user = ctx.request.body;

  console.log('CREATE USER params:');
  console.log(user);

  console.log(user.username);
  let users = await User.find({username:user.username});
  console.log(users); //why is this a function???
  if (users.length > 0) {
    ctx.status = 400;
    ctx.body = {
      errors:[
        'Username already exists.'
      ]
    };
  } else {
    const hash = await bcrypt.hash(user.password, 10);
    await User.insert({username:user.username, password:hash});
    console.log('Creating user…');
    console.log(user);
    ctx.body = filterProps(user, ['username']);
    ctx.status = 201;
    }
  };

module.exports.signIn = async (ctx, next) => {

  const encoded = ctx.request.headers.authorization.split(' ')[1];
  const decoded = base64url.decode(encoded);
  const [username, password] = decoded.split(':');
  const user = await User.findOne({username:username});
 
  //problematic code here...

  await bcrypt.compare(password, user.password, function (err, res) {
    if (res) {
      ctx.status = 200;
      ctx.body = 'success';
    } else {
      ctx.status = 401;
      ctx.body = {
        errors:['password incorrect for this username']
      }
    }
  });
}

1 个答案:

答案 0 :(得分:1)

所以问题在于我如何使用bcrypt比较。我将结果存储在变量中,而不是使用回调,它可以工作。为什么,我不知道......



module.exports.signIn = async (ctx, next) => {
  const encoded = ctx.request.headers.authorization.split(' ')[1];
  const decoded = base64url.decode(encoded);
  const [username, password] = decoded.split(':');
  const user = await User.findOne({username:username});
  
  const correct = await bcrypt.compare(password, user.password)
  if (correct) {
    ctx.status = 200;
    ctx.body = 'success';
  }
  else {
    ctx.status = 401;
    ctx.body = {
      errors:['wrong credentials']
    }
  }
};




相关问题