dcodeIO / bcrypt.js

Optimized bcrypt in plain JavaScript with zero dependencies.
Other
3.47k stars 264 forks source link

bcrypt compare isnt working #117

Closed ankur1163 closed 2 years ago

ankur1163 commented 4 years ago

bcrypt compare function isnt working Here's my code

router.post('/register', async (req, res) => {
    try {
        console.log("entered register")
        var salt = await bcrypt.genSaltSync(10);
        const hash = await bcrypt.hashSync(req.body.password, salt)
        console.log("hash is",hash)
        const user = await userRequest.findUser(req.body.email);
        console.log("length",user.user_user);
        if(user.user_user.length===0){
            // create user here
            console.log("user not found")
          const signedupUser =  await userRequest.registerUser(req.body.email,hash); 
            console.log(signedupUser,"after signedup")
            const tokentosend = await createToken(signedupUser)
            console.log("tokentosend",tokentosend)
            //res.send(tokentosend)
            res.status(201).send({message: tokentosend});
        }
        else{
            console.log("user found")
            // return user also exist
        }        

    }
    catch (err) {
        console.log("error has come")
        res.send(400).status("error", err)

    }
})

router.post('/login', async (req, res) => {
    console.log("entered into login",req.body.email,req.body.password)
    try {
        console.log("this is nice")
        const user = await userRequest.findUser(req.body.email);
        console.log("user length")
        if(user.user_user.length===0){
            console.log("user not found")
            //return user does not exist
        }
        else {
            console.log(user.user_user[0].password,"and",req.body.password)

            const passwordCorrect =  bcrypt.compareSync(req.body.password, user.user_user[0].password);

            bcrypt.compare(req.body.password,user.user_user[0].password).then((result)=>{
                console.log("result is ",result)
                if(result){
                  console.log("authentication successful")
                  // do stuff
                } else {
                  console.log("authentication failed. Password doesn't match")
                  // do other stuff
                }
              })
              .catch((err)=>console.error(err))

            console.log("password is not there",passwordCorrect)
            if(!passwordCorrect){
                // return password mismatch
                console.log("password is incorrect")
                res.send(400).status("password is wrong")
            }
            else{
                console.log("password is correct",user.user_user[0])
                const tokentosend = await createToken(user.user_user[0])
                console.log("tokentosend",tokentosend)
                res.status(201).send({message: tokentosend});

                // return token as response
            }
        }
    } catch (err) {
        console.log("error is there")
        res.status(400).send(err)
    }
})

When i sign up. it does store correct hashed password. I bring hashed password from db . But compare always return false. Can someone help me out?

langeneggerma commented 4 years ago

I had the same problem. Try this. is written in the Readme

// Load hash from your password DB. bcrypt.compareSync("B4c0/\/", hash); // true bcrypt.compareSync("not_bacon", hash); // false

ashwamegh commented 4 years ago

@ankur1163 It may take time, if you are generating the salt with higher lengths, can you test generating salt with 10 as the length of the salt const salt = await bcrypt.genSalt(10); like this. Try this, if it is working or not.

langeneggerma commented 4 years ago

I have generated this. I am certainly not the most beautiful variant, but it works for me!

The email and username are unique in the database. With me there will be a maximum of 10 users anyway. Therefore I do not check if the user already exists!


/**
 * POST insert new User
 */
router.post('/', reqAndResHandler.verifyToken, (req, res) => {
  if (!req.body.username || !req.body.password || !req.body.email) {
    return res.json({message: 'No fields'});
  }

  const Promise = reqAndResHandler.ckeckTockenIsValid(req, res);

  Promise.then(function (authData) {

    bcrypt.hash(req.body.password, 10).then(password => {
      req.body.password = password
      db.insert(req.body).into(query.DB_USERS)
        .then(function (data) {
          res.send(data);
        }).catch(function (err) {
        res.send(err.message)
      });
    }).catch(function (err) {
      res.send(err.message);
    })
  })

});

/**
 * Token only valid one houers after login
 */
router.post('/login', (req, res, next) => {
  if (!req.body.username || !req.body.password) {
    return res.json({message: 'No fields'});
  }

    const {username, password} = req.body;

    let user = {};
    db.select().from(query.DB_USERS)
      .where({[query.WHERE_USER_USERNAME]: username})
      .then(function (data) {
      user = data.find((user => {
        return user
      }));

      const correctPW = bcrypt.compareSync(password, user.password);

      if (user && correctPW) {
        jwt.sign({ username: username,  email: user.email , user_id: user.user_id}, 'secretKey', {expiresIn: '10h'}, (err, token) => {
          res.json({token})
        })
      } else {
        res.sendStatus(401)
      }
    }).catch(function (err) {
      res.send(err.message)
    });
});
´´´ 
I hope this helps you a little. :-)
CreativeCactus commented 2 years ago

OP is checking the first argument of the callback, not the second. According to the docs the first argument indicates if there was an error. The library works as expected, and this issue can be closed.