Issue with Bcrypt comparison resulting in constant false output

Attempting to implement 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 data is fetched from a database, while this.pin represents the correct password for the user. Despite logging the correct hash and pin values, for some reason, bcrypt.compare always falls into the 'else' condition, outputting "Something else went wrong". This leads to confusion as even directly passing the strings into the function doesn't yield the expected result, with 'res' always being false and 'err' turning up as null.

Answer №1

According to the information provided in the documentation for bcryptjs which can be found at this link:

When using bcrypt.compare("not_bacon", hash, function(err, res) {
    // The result will be false
});

The correct order of parameters should be reversed, with the hash (this.checkUser["pin"]) as the second parameter instead of the first.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An unexpected error occurred while parsing the JSON document: "unexpected token: '{'"

I'm facing an issue where I need to specify a URL in a JavaScript app that retrieves weather data from an API. The URL is constructed using a string and some variables. When I initially wrote the code below, I encountered the error message Missing { b ...

Is it possible for the useUser() function within the Auth0 nextjs-auth0 library to retrieve user information without relying on cookie data?

The useUser() method by Auth0 is designed to retrieve information about a logged-in user by calling the /api/auth/me endpoint. This triggers the handleAuth() function, which sets up Auth0 (creating a sessionCache instance, etc.) and calls profileHandler(re ...

Learn how to retrieve JSON data from the Yahoo Finance REST API using Angular 2

Currently, I am in the process of developing an application that needs to fetch data from the Yahoo Finance REST API. To retrieve a table for the symbol "GOOG," I have implemented the following code: export class ActService{ act = []; url = 'http ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

Middleware in the form of Try and Catch can be utilized to handle errors and

Currently, I am working on developing a backend using node.js with Express. My main goal is to effectively handle any potential status 500 errors that may arise. router.put('/test', async (req, res) => { try { return res.send(await r ...

Ensuring the timely execution of Javascript functions with Selenium before moving on

While working on creating test cases using Selenium, I encountered an issue. In one of my test cases, there is a small form and a search button on the website I'm testing. Filling the form and clicking the button are not the problem. The issue arises ...

What is the best way to fix the "Module not detected: Unable to locate [css file] in [directory]" error when deploying a Next.js website on Netlify?

Trying to deploy my site on Netlify from this GitHub repository: https://github.com/Koda-Pig/joshkoter.com, but encountering an error: 10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages&ap ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Stop music with one click, code in Javascript

I am encountering an issue with a set of 5 div boxes on my website. Each box is supposed to play a specific audio track when clicked, based on data attributes. However, I'm having trouble pausing the previous track when clicking on a new box, resultin ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Tips for choosing an <li> element with JavaScript

<style> .sys_spec_text{} .sys_spec_text li{ float:left; height:28px; position:relative; margin:2px 6px 2px 0; outline:none;} .sys_spec_text li a{ color: #db0401; height:24px; padding:1px 6px; border:1px solid #ccc; background:#fff; dis ...

The Vue.js application appears to be functioning properly with no error messages, however

Currently, I am in the process of learning Vue. Recently, I came across a helpful tutorial that I've been trying to implement using the standard vue-cli webpack template by splitting it into single file components. Despite not encountering any errors ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

Dispatch an angular POST Request

I am facing an issue where Angular is sending a GET request instead of a POST request when I want to send a post request. The code for my Angular request is as follows: $http({ method: 'POST', url: pages_url, params: { ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

The error message appeared as a result of the bluebird and mongoose combination: TypeError: .create(...).then(...).nodeify is

Recently, I encountered an issue while attempting to integrate bluebird with mongoose. Here's the scenario: I wrote some test code using bluebird without incorporating mongoose, and it worked perfectly. The code looked something like this: A().then( ...

Several DIVs with the same class can have varying CSS values

I am looking to modify the left-margin value of various separate DIVs using JavaScript. The challenge is: I only want to use a single className, and I want the margin to increase by 100px for each instance of the class. This way, instead of all the DIVs ...

Access the current page's URL using JavaScript

I have a unique URL structure that looks like this: index.html#page:page.php As I am loading my pages dynamically using AJAX, I want to create hotlinks to load specific pages. Currently, I am using the following function: function getdata(file){ $ ...