0

Im trying to do password verification using bcryptjs,

   const bcrypt = require('bcryptjs');
   login(post){
        this.uid = post.uid;
        this.pin = post.pin;
        this.getUser(this.uid);
        if(this.checkUser != undefined && this.pin != undefined){
          console.log(this.checkUser)
          console.log(this.pin)
          console.log(this.checkUser["pin"])
          bcrypt.compare(this.checkUser["pin"], this.pin, (err, res) => {
            if (err){
              console.log("Something went wrong  " +  err)
              // handle error, Wrong password
            }
            else if (res) {
              // Send JWT, Correct password
              console.log("It worked!  " +  res)
              // TEMP
              sessionStorage.setItem("name", this.checkUser["name"]);
              sessionStorage.setItem('loggedin',"true");
              location.reload();
              //
            } 
            else {
              console.log("Something else went wrong!")
            }
          });
         }
       }
    
      
      getUser(uid){
        this.BrukerService.getSingle(uid).subscribe((res: String) => {
          this.checkUser = JSON.parse(res);
        },
        (err) => {
          this.error = err;
        });
      }

this.checkUser:

{id: "1", uid: "1234", pin: "$2a$05$7251G35/U5YfLby9oQrqpOA58szCqWEo4lOSLxRmn0HV1nZ4Tn962", created: "2020-12-21 14:28:00", name: "Martin"}

this.pin:

1234

this.checkUser["pin"]:

$2a$05$7251G35/U5YfLby9oQrqpOA58szCqWEo4lOSLxRmn0HV1nZ4Tn962

the checkUser is retrieved from a database, this.pin is the correct pass for the user. bcrypt.compare goes to the else no matter what, so it always logs "something else went wrong", and i don't understand what could be wrong, it correctly outputs the hash and pin, even when i insert them directly as strings into the bcrypt.compare function it goes to the else, res is always false and err null.

Martin
  • 65
  • 7

1 Answers1

0

Going by what the bcryptjs documentation https://www.npmjs.com/package/bcryptjs says:

bcrypt.compare("not_bacon", hash, function(err, res) {
    // res === false
});

You have the hash (this.checkUser["pin"]) parameter first when it should be the second parameter.

John
  • 3,716
  • 2
  • 19
  • 21
  • Thanks lol! I now realize that I never actually checked what order they were supposed to be in xD – Martin Dec 25 '20 at 18:50