简体   繁体   中英

I am having a problem with bcrypt compare. I succed to hash password on Register page, but I not to compare successfully on login page. Please help :)

Here is Register form, I get the hashed password:

getAllUsers().then((res) => {
      let user = res.data.find(
        (u) => u.ugovor === ugovor && u.merilo === merilo
      );

      if (user) {
        setUser(user) {
 
        bcrypt.genSalt(10, (err, salt)=> {
          bcrypt.hash(loggedIn.password, salt, (err, hash) => {
            
            postUser(loggedIn.id, hash, password, email).then((res) => {
              user = res.data;
              setPassword(prev => [...prev, hash]);
              //loggedIn.password = hash;
              setEmail(prev => [...prev, user]);
              history("/login");
              setError("");
              console.log("uspesna registracija");
            })
          })
        }) 
      } else {
        setError("Не постоји купац са унесеним бројем Уговора и мерила");
        return 0;
      }
    });
  }}>

And here is LogIn form, everytnihg works but compare hashed password:

getAllUsers().then((res) => {
     
      let user = res.data.find(
        
        (u) => u.ugovor === ugovor && u.password === password
      );
       const doesPasswordMatch = bcrypt.compareSync(password, user.password); 
       if(!doesPasswordMatch) {
         console.log('compare not success');
         return 0;

} else {

        console.log('compare success')

} if (user) {

        setLogIn(true);
        setUser(user);
        history("/profile");
        console.log("uspesno ulogovan");
       
      } else {
        setError("Broj Ugovora i lozinka se ne podudaraju");
      }   

    });
  }}

I tried compare, compareSync, with await, even this, but nothing works, it wont recognise hashed password:

bcrypt.compare(password, user.password, function(err, result) {
// result == true

});

Try this for your login. Please, remember to give some feed up.

getAllUsers().then((res) => {
 // look for user
 let user = res.data.find((u) => u.ugovor === ugovor);

 if (user) {
  // user is found
  const hashedPassword = u.password; // get stored hashed password
  // compare passwords
  const doesPasswordMatch = bcrypt.compareSync(password, hashedPassword, (err, result) => {
    if (err) console.log(err);
     // result == true
    });

  if (doesPasswordMatch) {
   // correct password
   console.log("compare success");
   setLogIn(true);
   setUser(user);
   history("/profile");
   console.log("uspesno ulogovan");
  } else {
   // wrong password
   console.log("compare not success");
   return 0;
  }
} else {
 // user is not found
 setError("Broj Ugovora i lozinka se ne podudaraju");
}

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM