can not return jwt on login

I try to make login with node.js and next.js but I can’t return token. I am working with mysql database.

Here is my code. I try with console.logs and its stuck in part where i select from database. My model is simple just username and password. pasword is bcrypt.

import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import db from '../../db/db'


export default async (req, res) => {
  if(req.method === "POST"){
    console.log("POSTED");
      const { username, password } = req.body;
      console.log(req.body)
      try {
        let user = await db.execute("SELECT * FROM user WHERE username = ?", [username]);
        
      console.log("eeeee",user)
      
      if (!user) {
        return res
          .status(400)
          .json({ errors: [{ msg: 'Invalid Credentials' }] });
      }
      const isMatch = await bcrypt.compare(password, user.password);
      console.log(isMatch);

      if (!isMatch) {
        return res
          .status(400)
          .json({ errors: [{ msg: 'Invalid Credentials' }] });
      }

     

      const payload = {
        user: {
          id: user.iduser,
          username: user.username
        },
      };


      
      console.log("tokeeeeen: ",token)
      jwt.sign(
        payload,
        process.env.JWT_SECRET,
        { expiresIn: 24 * 60 * 60 * 1000 },
        (err, token) => {
          if (err) console.log(err);
          console.log(token);
          res.json({ token });
        }
      );
      } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
      }
  }
}

When calling bcrypt-compare I get the following error: ‘data and hash arguments required’

Answer

The issue that you are facing is a missing callback function, since bcrypt.compare takes three args, the password, the hashed password, and a callback:

bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
    // Do stuff here
});

Alternatively you could use bcrypt.compareSync:

// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false
if (bcrypt.compareSync(loginData.password, passwordInDB) === true) {
   /* INFO: Passwords match -> valid access-attempt */
   /* INFO: Create token for client */ 
   const token = jwt.sign({ id: resSelect.rows[0].id }, "secret", { expiresIn: '24h' });
....
else {
   // handle pwd mismatch..
} 

Please refer to https://www.npmjs.com/package/bcrypt for more details.

Fixing that should resolve your problem..

Leave a Reply

Your email address will not be published. Required fields are marked *