Constantly getting a false result when using Bcrypt.compareSync

Hey there, I'm currently working on setting up my first login functionality using sequelize, but I'm running into some issues with hashing and comparing hashes as it always returns false. Since I am still learning, I believe I may be making a mistake in the hashing or comparison process. My database of choice is SQL.

Below is my login code snippet that utilizes express session and sequelize:

'processLogin': (req, res) => {
    db.User.findOne({
        where: {
            email: req.body.email
        }
    })
    .then(async user => {
        var eSession = req.session.userLogin;
        let checkPass = await bcrypt.compare(req.body.password, user.password);
        console.log(checkPass);
        if(checkPass){
            eSession = user;
            res.send("Success");
        }else{
            res.render('login', {errors: [{
                msg: "Incorrect password"
            }]});
        }
        if(user == undefined){
            res.render('login', {errors: [{
                msg: "User not found, please Register"
            }]);
        }
    });
}

And here is the portion where I hash passwords during registration:

'save': async (req, res) => {
    var dataArr = [req.body.fullname, req.body.email, req.body.number, bcrypt.hashSync(req.body.password, 10), bcrypt.hashSync(req.body.repassword, 10)];
    let errors = validationResult(req);
    if(errors.isEmpty()){
        db.User.create({
            full_name: dataArr[0],
            email: dataArr[1],
            phone_number: dataArr[2],
            password: await bcrypt.hash(dataArr[3], 10),
            confirm_password: await bcrypt.hash(dataArr[4], 10)
        })
        .then(users => {
            res.send("Success!!");
        }) 
    }else{
        res.render('register', { errors: errors.errors });
    }
}

Answer №1

Instead of using sync operations, have you considered trying async and waiting until the process is hashed or decrypted?

Within an async function to hash the password:

let encryptedPassword = await hash(password, 10);

Similarly, within an async function to compare passwords:

let passwordMatch = await compare(password, user.password);

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

Substitute the functions within a Node.js module with simulated functions

I am currently working on a Node.js project that serves as an API wrapper. To ensure the reliability of my code, I am writing unit tests using nodeunit and need to incorporate mock functions into the module. For instance, I require a function that mimics s ...

Is there a quicker alternative to the 500ms delay caused by utilizing Display:none?

My div is packed with content, including a chart from amCharts and multiple sliders from noUiSlider. It also features various AngularJS functionalities. To hide the page quickly, I use $('#container').addClass('hidden'), where the rule ...

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

Building an Image/Grid system using CSS and Javascript

Currently in the process of constructing a fresh website, I find myself in need of a solution to a particular issue (specifically involving PHP, MySQL, and Zurb Foundation). The challenge at hand is to fashion an image comprised of 1,000,000 pieces, each ...

Learn the process of redirecting to a new page using React JS

Currently facing an issue with the Signup button functionality within the Signin dropdown. Instead of opening a new page, it is displaying below the footer. Seeking assistance on how to redirect to a new page when clicking on the signup button. App.js fi ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

I'm currently attempting to determine the total cost of a series of operations, however, I am not receiving any results

Here is the code snippet from my HTML file: <tr> <td><input id="z1" type="number" oninput="calculateSubTotal()"> </td> <td>Shirts - WASH - Qty 1 to 4</td> <td>2.50 ea</td> ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Checking for username availability in MySQL using PHP registration form

Recently, I developed a registration/sign up form to add new users to my database. During testing, I discovered a loophole where users could register with a username that is already in use. Here's the snippet of my code: <?php require('db.php ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

What could be the reason for the esm loader not recognizing my import?

Running a small express server and encountering an issue in my bin/www.ts where I import my app.ts file like so: import app from '../app'; After building the project into JavaScript using: tsc --project ./ and running it with nodemon ./build/bin ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...

using Angular and RxJS to filter out an element from an array

One of the functions in my service is a delete function. This function calls an API that returns either true or false. If the response is true, I then proceed to find the index of the item in my array, splice it out, and return the updated array. Here&apos ...

Command for optimizing tables

Looking for some advice on optimizing tables in a database while running a code. Each table takes between 3-5 minutes to execute, so I need the next table to start once the previous one is done. Any recommendations? const optimizeQuery = 'OPTIMIZE TAB ...

"Preventing Cross-Origin Requests" error encountered while trying to load a JSON document

I've been working on an online experiment using JavaScript, and I need to load parameters for the task from a JSON file. I managed to do this successfully when running the task through a live server. However, if I try to run it locally by opening the ...

Pausing and then resuming an interval function within the same function

I'm struggling with an $interval function that runs every second. The function retrieves user credentials from local storage and checks if they have expired. If they have, it refreshes them with new ones. Otherwise, it does nothing. This is what my ...

What is the process for extracting a single hashtag using the Twitter API with JSON in JavaScript?

Currently, I am utilizing the npm package 'twit' in conjunction with node js to interact with the Twitter API. My goal is to retrieve the hashtags used by a specific user in their most recent tweets. By employing the following code snippet, I ca ...

What is the best way to handle input data as variables?

I'm looking to learn how to input data in HTML using elements like <input> and then utilize that data. Specifically, I'm interested in entering someone's age and being able to use it as a variable to create functions related to age in ...

"Encountered an issue while trying to POST to /userslist in

Having just started using node js, I've encountered a problem with my application. When the admin logs in, an error message 'Cannot POST /userslist' appears, but upon refreshing the page, it successfully fetches the userslist. The routing co ...

What is the best way to format the incoming data to display as HTML code?

My textarea has a v-model called content where input text is assigned to content.description. Now, I need to transfer this information to another element, specifically a div. The challenge lies in the fact that if my textarea includes HTML code, I want it ...