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

tips for navigating through an AngularJS $resource instance

I am facing a frustrating issue that I need assistance with. The problem arises when I try to extract specific data from each element of the stock data fetched by my controller from Yahoo Stocks. Although the data is stored in $scope.stocks and can be disp ...

The disappearing act of Redux state after being added to a nested array

When attempting to update my redux state, I am facing an issue where the state disappears. My approach involves checking for a parentId - if one exists, I insert the payload into the parent's children array. However, if no parentId is provided, I simp ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Can you explain the functionality of dismissing a Bootstrap alert?

In this example, we can see how Bootstrap handles dismissible alerts: <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidde ...

Instructions on how to toggle the visibility of a div when hovering over a different a tag

To keep things simple, I'm looking to create a visibility toggle effect on a div when someone hovers over an anchor tag. Similar to the behavior of the four buttons on this example link: The issue I'm facing is that I want the div to appear or b ...

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Nashorn poses a security threat due to its ClassFilter vulnerability

Encountering some troubles with Nashorn and came across a concerning security vulnerability highlighted here: It appears that someone can easily execute code using this command: this.engine.factory.scriptEngine.eval('java.lang.Runtime.getRuntime().ex ...

Display the value of a shortened string

My Goal I aim to develop a method for determining the amount of a string visible before it gets cut off. Motivation In my project, there is a collection of items that can be chosen. A panel presents a concatenated string of the selected item names separa ...

Harness the power of JavaScript to generate a dynamic overlay with a see-through image that can be expanded

Within different sections of my website, we display banner ads that are loaded in real-time from third-party sources and come in various sizes. I'm interested in adding a transparent overlay image to each ad which would allow me to trigger a click ev ...

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

Generate a fresh array of elements and combine the objects that share the same value

Looking to create a new array of objects based on the original specs array of objects. I have searched for similar questions but nothing has solved my issue. const specs = [ { label: 'Brand', value: 'Nike' }, { label: 'Age ra ...

What is the process for adding extra CSS to a webpage displayed in WebView2?

Currently, I am utilizing the Webview2 control within a winform application. My goal is to enhance the behavior of the loaded page by injecting additional CSS code when a specific URL is being displayed in the browser control. Specifically, I aim to implem ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

Position the Material-UI AppBar and Tab on the far right of the screen

I am trying to achieve a specific layout where the Links for "Homepage Login Settings and etc.." are placed at the right edge of the AppBar, while keeping the "Website" aligned to the left edge of the screen. Here is what I have: Can someone help me figur ...

Re-enable the jQuery-ui sortable feature after it has been turned off

Here is a snippet of my jQuery code: var status = true; $('#edit').click(function () { if (status) { $('table tbody').sortable({ axis: 'y', update: function (event, ui) { va ...

Combining routes in Express and Angular can be achieved by leveraging the power

How can I successfully integrate Jade AngularJS with ExpressJS? I have an app.js file for Express to run the server using Grunt. This app.js file renders home.jade which leads me to the home page. On the homepage, I have implemented AngularJS. I also creat ...

Unable to trigger the show_popup function by clicking the button

Why won't this piece of code function as expected? <script src="web_push.js"></script> <body> <button onclick="show_popup()"> Button </button> </body> The content of web_push.js file is shown below ...

Using the setInterval function in conjunction with the remoteCommand to create a

I am attempting to create a remote command that calls a bean function and updates a progress bar every 2 seconds until cancelled. The remote command looks like this: <p:remoteCommand id="usedCall" name="queryUsed" onco ...