Tips for properly implementing a bcrypt comparison within a promise?

Previously, my code was functioning correctly. However, it now seems to be broken for some unknown reason. I am using MariaDB as my database and attempting to compare passwords. Unfortunately, I keep encountering an error that says "

Unexpected Identifier on "bcrypt" after await
". When I remove the await, the code works but fails to validate the password even if incorrect. Can someone please guide me on where I might be going wrong here? Thank you.

Edit: I realized that I had omitted the user info after .then. It appears that I may have accidentally deleted it while making some comments when posting this question, so I've added it back in. Below is the updated code:

//data connection pool
const pool = require('../models/db');
const { handleError, ErrorHandler } = require('../helpers/error');
const bcrypt = require('bcrypt');

module.exports = (req, res) => {
  //destructuring assignment👇
  const {user_name, password} = req.body;
  let hashedPassword;
  //TODO: hash password

  var sql = `SELECT * FROM Govt_profiles WHERE
    (user_name = ?)`;

  //pool.query() is shortcut for pool.getConnection() + connection.query() + connection.release()
  pool.query(sql, [user_name], async (err, data) => {
  })
  .then(rows => {

    const user = rows.find( user => user['User_Name'] === user_name);
    if (user == null) {
      return res.status(400).send('Cannot find user');
    }

    try {
      if (await bcrypt.compare(password, user['Password'])) {
        console.log('Password: ', password, 'hashedPassword: ', hashedPassword);
        console.log("this is a loginUser: ");
        console.log(req.session);
        //return res.redirect('questions')
        return res.render('user-progress', {
          userName: req.session.user_name,
          attempts: req.session.attempts,
          grade: req.session.grade
        })
      }
    } catch(e) {
        console.log("something broke: ", e);
        res.status(500).send();
    }

  })
  .catch(err => {
    console.log(err.message);
    console.log("hey couldn't find user");
    req.session.error = new ErrorHandler(404, 'Incorrect email or last name');
    res.render('login_user', {
      //err: err (or if same name to this)
      //err
      error: req.session.error
    });
  })
}

I followed Lucas' suggestion, however, I encountered a new error:

C:\users\daniel\documents\git\usa-govt-quiz\controllers\loginUser.js:41
    const isValidPsw = await bcrypt.compare(password, user['Password']);
                       ^^^^^

SyntaxError: await is only valid in async function
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\users\daniel\documents\git\usa-govt-quiz\server.js:5:29)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[nodemon] app crashed - waiting for file changes before starting...

Any other suggestions would be greatly appreciated.

Answer â„–1

By adding the "async" keyword in front of rows, I was able to solve this issue. It may seem unusual to me, and I'm not sure if it's a common practice, but it did the trick.

Below is the updated version of my code:

.then(async rows => {

    const user = rows.find( user => user['User_Name'] === user_name);
    if (user == null) {
      return res.status(400).send('Cannot find user');
    }

    try {
      if (await bcrypt.compare(password, user['Password'])) {
        console.log('Password: ', password, 'hashedPassword: ', hashedPassword);
        console.log("this is a loginUser:");
        console.log(req.session);
        
        return res.render('user-progress', {
          userName: req.session.user_name,
          attempts: req.session.attempts,
          grade: req.session.grade
        })
      }
    } catch(e) {
        console.log("something broke: ", e);
        res.status(500).send();
    }

  })
  .catch(err => {
    console.log(err.message);
    console.log("hey couldn't find user");
    req.session.error = new ErrorHandler(404, 'Incorrect email or last name');
    res.render('login_user', {
      error: req.session.error
    });
  })
}

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

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

Is there someone who can assist me in transforming this constructor function into a factory function using Javascript?

const createAppError = (message, status) => { return { message, status }; }; This is the equivalent code using factory functions to create an AppError with a message and status. It achieves the same result as the constructor fun ...

Interactive carousel featuring responsive image zoom effect on hover

Utilizing the flickity carousel, I have crafted an example which can be found at this link to codepen.io. Here is the CSS code that has been implemented: CSS .image-hoover { overflow: hidden; } .image-hoover img { -moz-transform: scale(1.02); -web ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

NodeJS: Issue with Route is disrupting the functionality of the Restful API

Struggling to develop an API using Node.js and Express, encountering routing issues with express.Router(). Take a look at my code below: Server.js file contents: // Get necessary packages var express = require('express'); var app = express(); ...

Tips on adding a base64 encoded image string to a JSON object using JavaScript

I'm trying to convert an image file into a JSON object using JavaScript. I've managed to turn the image into a string by utilizing base64 encoding, but I'm unsure how to then convert this string into a JSON object. Can anyone help? ...

Create a data attribute object and assign to it the prop object received from the parent component

I am struggling with passing an object as a prop from a parent component and then utilizing it to initialize the child component with the received value. The main objective behind this is to create a dialog box that includes a child form component with mu ...

Express was unable to establish a connection with localhost

Running the following code on http://localhost:5000/ functions properly: const http = require('http') const server = http.createServer((req, res) => { if (req.url === '/') { res.end('Home Page') } }) server.liste ...

Display an image fetched through the Express framework in Node.js

Utilizing the sendfile function in Node Express, I am able to serve an image from my local hard drive like so: app.get('/data/getImage/:Id', function (req, res) { console.log(req.params.Id); res.sendfile('C:\\defaultim ...

Encountering a "Cannot GET" error when utilizing mongoose

Details of my router.js file: const express = require("express") const Note = require("../models/nodeModel") const router = express.Router() router.route("/notes").get((req, res) => { Note.find({ show_day: "2020-9-10" }) .then(foundNotes ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

Why won't my div tag show conditionally with AngularJS ng-show?

I'm having trouble displaying a div tag on a form based on the boolean flag specified in ng-show. Unfortunately, the div is not showing up at all. Here's what I've tried so far without success. Any assistance would be greatly appreciated! F ...

The dropdown menu fails to update in Internet Explorer

Here is the URL for my website: . On this page, there are two fields - category and subcategory. When a category is selected, the corresponding subcategory should change accordingly. This functionality works smoothly in Google Chrome, however it encounte ...

Monitor the input value for any changes in Angular 8 using the listen component

Hey there! I'm currently working with a component that includes the input @Input() userId: number[] = []; to receive a list of user IDs. Specifically, I have integrated this component into another one, such as the news component: <kt-user-post-li ...

In Vuejs, all assignments are made by reference, even when using object spreading

If the HTML structure is: <div id="app"> <button @click="doEditing">Edit</button> <input v-if="editing" v-model="editing.profile.name" /> <span>{{ user.profile.name }}</span> </div> And Vuejs setup is: va ...

JavaScript - Unexpected fluctuations in variable values

After studying Japanese language, I decided to try my hand at experimenting with JavaScript by creating a simple FlashCard game for a project. The game generates an array of random numbers, fills the divs with 6 possible choices using jQuery, randomly sele ...

elementToBeClickable is not supported by webdriverio

I am having some trouble with the 'waitForEnabled' function as it does not seem to behave like Webdriver's elementToBeClickable. Is there anyone who can provide some guidance on how to use this API effectively? ...

What is the process for adding an item to an object?

I currently have the following data in my state: fbPages:{'123':'Teste','142':'Teste2'} However, I am in need of a dynamic solution like the one below: async getFbPages(){ var fbPages = {} awa ...

Error occurs when a callback is not utilized in Node.js, Express, and SQL Server Express interaction

When dealing with mssql, Nodejs, Gulp, Express, and SQL Server Express, an issue arises. While successfully logging in to SQL Server Express, the returned value becomes undefined when utilizing the bookRoute.js code snippet without callback. However, intro ...

Using a Node.js module to shrink HTML files

Is there a way to minify HTML before rendering it? I'm aware of console minifiers like: html-minifier However, I am looking for a solution that can be implemented in the code itself. Something along the lines of: var minifier = require('some- ...