Search code examples
javascriptbcryptkoa

Headers have already been sent - Koa and bcrypt


I'm trying to create a sign-in endpoint for my app. I've used bcrypt to hash the password when a user a created. When signing in, I want to compare the hash with the string password. However, when I sign-in using postman, I get a 404 error "headers have already been sent". I looked on the koa git forum using crypto with koa 2 and the accepted answer suggests wrapping the function in an async await, which is what I've done. I can't figure out why node keeps sending me a 'headers have already been sent' error.

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']
      }
    }
  });
}


Solution

  • So the problem was with how I was using bcrypt compare. I stored the result in the variable instead of using a callback and it worked. Why, I don't know...

    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']
        }
      }
    };